Browse Source

implemented user list and editing other users for admin

feature/document
Stephan Richter 4 months ago
parent
commit
ea6ca9e45d
  1. 12
      core/src/main/java/de/srsoftware/umbrella/core/ResponseCode.java
  2. 95
      frontend/src/routes/user/Edit.svelte
  3. 13
      frontend/src/routes/user/EditPassword.svelte
  4. 25
      frontend/src/routes/user/User.svelte
  5. 8
      translations/src/main/resources/de.json
  6. 68
      user/src/main/java/de/srsoftware/umbrella/user/UserModule.java
  7. 6
      user/src/main/java/de/srsoftware/umbrella/user/model/DbUser.java
  8. 4
      web/src/main/java/de/srsoftware/umbrella/web/WebHandler.java

12
core/src/main/java/de/srsoftware/umbrella/core/ResponseCode.java

@ -2,13 +2,7 @@ @@ -2,13 +2,7 @@
package de.srsoftware.umbrella.core;
public class ResponseCode {
public static final int OK = 200;
public static final int REDIRECT = 302;
public static final int BAD_REQUEST = 400;
public static final int UNAUTHORIZED = 401;
public static final int FORBIDDEN = 403;
public static final int NOT_FOUND = 404;
public static final int UNPROCESSABLE = 422;
public static final int SERVER_ERROR = 500;
public static final int NOT_IMPLEMENTED = 501;
public static final int HTTP_UNPROCESSABLE = 422;
public static final int HTTP_SERVER_ERROR = 500;
public static final int HTTP_NOT_IMPLEMENTED = 501;
}

95
frontend/src/routes/user/Edit.svelte

@ -1,19 +1,102 @@ @@ -1,19 +1,102 @@
<script>
import { t } from '../../translations.svelte.js';
import { useTinyRouter } from 'svelte-tiny-router';
import { onMount } from 'svelte';
import { checkUser } from '../../user.svelte.js';
const router = useTinyRouter();
let { user_id } = $props();
let editUser = $state(null);
let options = $state([]);
let sent = $state(false);
let caption = $state(t('user.save_user'));
onMount(async () => {
const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/user/${user.id}`;
const resp = await fetch(url,{credentials:include});
let url = `${location.protocol}//${location.host.replace('5173','8080')}/themes.json`;
let resp = await fetch(url);
if (resp.ok){
const arr = await resp.json();
for (let entry of arr){
const value = entry.value;
const caption = entry.caption ? entry.caption : value;
options.push({caption:caption,value:value})
}
}
url = `${location.protocol}//${location.host.replace('5173','8080')}/api/user/${user_id}`;
resp = await fetch(url,{credentials:'include'});
if (resp.ok) editUser = await resp.json();
});
async function save(elem){
sent = true;
caption = t('user.data_sent');
let url = `${location.protocol}//${location.host.replace('5173','8080')}/api/user/${user_id}`;
let resp = await fetch(url,{
method: 'PATCH',
credentials: 'include',
body: JSON.stringify(editUser)
});
if (resp.ok){
const json = await resp.json();
caption = t('user.saved');
checkUser();
router.navigate('/user');
} else {
caption = t('user.failed');
}
});
}
</script>
<fieldset>
<legend>{t('user.editing')} {user_id}</legend>
…Edit form here…
<legend>{t('user.editing',user_id)}</legend>
{#if editUser}
<table>
<tbody>
<tr>
<th>{t('user.id')}</th>
<td>{editUser.id}</td>
</tr>
<tr>
<th>{t('user.name')}</th>
<td>
<input type="text" bind:value={editUser.name} />
</td>
</tr>
<tr>
<th>{t('user.email')}</th>
<td>
<input type="text" bind:value={editUser.email} />
</td>
</tr>
<tr>
<th>{t('user.language')}</th>
<td>
<input type="text" bind:value={editUser.language} />
</td>
</tr>
<tr>
<th>{t('user.password')}</th>
<td>
<input type="password" bind:value={editUser.password} />
</td>
</tr>
<tr>
<th>{t('user.theme')}</th>
<td>
<select bind:value={editUser.theme}>
{#each options as entry,i}
<option value={entry.value}>{entry.caption}</option>
{/each}
</select>
</td>
</tr>
</tbody>
</table>
<button onclick={save} disabled={sent}>{caption}</button>
{:else}
{t('user.loading_data')}
{/if}
</fieldset>

13
frontend/src/routes/user/EditPassword.svelte

@ -6,18 +6,21 @@ @@ -6,18 +6,21 @@
let oldPass = $state("");
let newPass = $state("");
let repeat = $state("");
let caption = $state(t('user.update'));
let oldEmpty = $derived(!/\S/.test(oldPass));
let newEmpty = $derived(!/\S/.test(newPass));
let mismatch = $derived(newPass != repeat);
let error = $state("");
let sent = $state(false);
function abort(){
editPassword = false;
}
async function submit(){
caption = t('user.data_sent');
const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/user/password`;
const data = {
old: oldPass,
@ -28,11 +31,11 @@ @@ -28,11 +31,11 @@
body: JSON.stringify(data),
credentials: 'include'
});
if (resp.ok){
const json = await resp.json();
console.log(json);
caption = t('user.saved');
} else {
error = await resp.text();
caption = t('user.failed');
}
}
</script>
@ -63,8 +66,8 @@ @@ -63,8 +66,8 @@
<span class="error">{t('user.mismatch')}</span>
{/if}
</label>
<button onclick={submit} disabled={oldEmpty||newEmpty||mismatch}>{t('user.update')}</button>
<button onclick={abort}>{t('user.abort')}</button>
<button onclick={submit} disabled={sent||oldEmpty||newEmpty||mismatch}>{caption}</button>
<button onclick={abort} disabled={sent}>{t('user.abort')}</button>
{#if error}
<span class="error">{error}</span>
{/if}

25
frontend/src/routes/user/User.svelte

@ -1,10 +1,13 @@ @@ -1,10 +1,13 @@
<script>
import { t } from '../../translations.svelte.js';
import { user } from '../../user.svelte.js';
import ClickInput from '../../Components/ClickInput.svelte';
import ClickSelect from '../../Components/ClickSelect.svelte';
import { useTinyRouter } from 'svelte-tiny-router';
import EditPassword from './EditPassword.svelte';
import UserList from './List.svelte';
const router = useTinyRouter();
let editPassword = false;
async function patch(changeset){
@ -31,7 +34,7 @@ @@ -31,7 +34,7 @@
<fieldset>
<legend>
{t('user.profile')}
{t('user.your_profile')} <button onclick={() => router.navigate(`/user/${user.id}/edit`)}>{t('user.edit')}</button>
</legend>
<table>
<tbody>
@ -41,9 +44,7 @@ @@ -41,9 +44,7 @@
</tr>
<tr>
<th>{t('user.name')}</th>
<td>
<ClickInput key='name' value={user.name} onUpdate={patch} />
</td>
<td>{user.name}</td>
</tr>
<tr>
<th>{t('user.login')}</th>
@ -51,21 +52,15 @@ @@ -51,21 +52,15 @@
</tr>
<tr>
<th>{t('user.email')}</th>
<td>
<ClickInput key='email' value={user.email} onUpdate={patch} />
</td>
<td>{user.email}</td>
</tr>
<tr>
<th>{t('user.language')}</th>
<td>
<ClickInput key='language' value={user.language} onUpdate={patch} />
</td>
<td>{user.language}</td>
</tr>
<tr>
<th>{t('user.theme')}</th>
<td>
<ClickSelect key='theme' value={user.theme} fetchOptions={fetchThemes} onUpdate={patch} />
</td>
<td>{user.theme}</td>
</tr>
<tr>
<th>{t('user.password')}</th>

8
translations/src/main/resources/de.json

@ -21,15 +21,19 @@ @@ -21,15 +21,19 @@
"actions": "Aktionen",
"abort": "abbrechen",
"CREATE_USERS": "NUTZER ANLEGEN",
"data_sent": "Daten übermittelt",
"DELETE_USERS": "NUTZER LÖSCHEN",
"edit": "Bearbeiten",
"editing": "Nutzer {0} bearbeiten",
"edit_password": "Passwort ändern",
"email": "E-Mail",
"failed": "fehlgeschlagen",
"id": "Id",
"IMPERSONATE": "NUTZER WECHSELN",
"language": "Sprache",
"list": "Benutzer-Liste",
"LIST_USERS": "NUTZER AUFLISTEN",
"loading_data": "Daten werden geladen…",
"login": "Login",
"MANAGE_LOGIN_SERVICES": "LOGIN-SERVICES VERWALTEN",
"mismatch": "ungleich",
@ -39,9 +43,11 @@ @@ -39,9 +43,11 @@
"old_password": "altes Passwort",
"password": "Passwort",
"permissions": "Berechtigungen",
"profile": "Profil",
"repeat_new_password": "Wiederholung",
"saved": "gespeichert",
"save_user": "Nutzer speichern",
"theme": "Design",
"your_profile": "dein Profil",
"update": "aktualisieren",
"user_module" : "Umbrella User-Verwaltung"
}

68
user/src/main/java/de/srsoftware/umbrella/user/UserModule.java

@ -12,12 +12,14 @@ import static de.srsoftware.umbrella.user.Paths.WHOAMI; @@ -12,12 +12,14 @@ import static de.srsoftware.umbrella.user.Paths.WHOAMI;
import static de.srsoftware.umbrella.user.model.DbUser.PERMISSION.LIST_USERS;
import static de.srsoftware.umbrella.user.model.DbUser.PERMISSION.UPDATE_USERS;
import static java.lang.System.Logger.Level.WARNING;
import static java.net.HttpURLConnection.*;
import static java.time.temporal.ChronoUnit.DAYS;
import com.sun.net.httpserver.HttpExchange;
import de.srsoftware.tools.Path;
import de.srsoftware.tools.PathHandler;
import de.srsoftware.tools.SessionToken;
import de.srsoftware.umbrella.core.ResponseCode;
import de.srsoftware.umbrella.core.UmbrellaException;
import de.srsoftware.umbrella.user.api.UserDb;
import de.srsoftware.umbrella.user.model.*;
@ -26,7 +28,6 @@ import java.security.NoSuchAlgorithmException; @@ -26,7 +28,6 @@ import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import org.json.JSONObject;
@ -72,12 +73,24 @@ public class UserModule extends PathHandler { @@ -72,12 +73,24 @@ public class UserModule extends PathHandler {
LOG.log(WARNING,e);
}
addCors(ex);
return switch (path.toString()) {
case LIST -> getUserList(ex, user);
case LOGOUT -> logout(ex, sessionToken);
case WHOAMI -> getUser(ex, user);
default -> super.doGet(path, ex);
var head = path.pop();
switch (head) {
case LIST: return getUserList(ex, user);
case LOGOUT: return logout(ex, sessionToken);
case WHOAMI: return getUser(ex, user);
};
try {
long userId = Long.parseLong(head);
if (userId == user.id() || (user instanceof DbUser dbUser && dbUser.permissions().contains(LIST_USERS))) {
var requestedUser = users.load(userId);
return sendContent(ex,requestedUser);
}
} catch (UmbrellaException e) {
return sendContent(ex,e.statusCode(),e.getMessage());
} catch (NumberFormatException ignored) {}
return super.doGet(path, ex);
}
@Override
@ -89,7 +102,7 @@ public class UserModule extends PathHandler { @@ -89,7 +102,7 @@ public class UserModule extends PathHandler {
addCors(ex);
var sessionToken = SessionToken.from(ex);
if (sessionToken.isEmpty()) return sendEmptyResponse(UNAUTHORIZED,ex);
if (sessionToken.isEmpty()) return sendEmptyResponse(HTTP_UNAUTHORIZED,ex);
UmbrellaUser requestingUser;
try {
@ -102,11 +115,11 @@ public class UserModule extends PathHandler { @@ -102,11 +115,11 @@ public class UserModule extends PathHandler {
var head = path.pop();
long userId;
try {
if (head == null || head.isBlank()) return sendContent(ex,UNPROCESSABLE,"User id missing!");
if (head == null || head.isBlank()) return sendContent(ex, HTTP_UNPROCESSABLE,"User id missing!");
if (PASSWORD.equals(head)) return patchPassword(ex,requestingUser);
userId = Long.parseLong(head);
} catch (NumberFormatException e) {
return sendContent(ex,UNPROCESSABLE,"Invalid user id: "+head);
return sendContent(ex, HTTP_UNPROCESSABLE,"Invalid user id: "+head);
}
DbUser editedUser;
@ -117,7 +130,7 @@ public class UserModule extends PathHandler { @@ -117,7 +130,7 @@ public class UserModule extends PathHandler {
}
if (requestingUser.id() != userId && (!(requestingUser instanceof DbUser dbUser) || !dbUser.permissions().contains(UPDATE_USERS))){
return sendContent(ex,FORBIDDEN,"You are not allowed to update user "+editedUser.name());
return sendContent(ex,HTTP_FORBIDDEN,"You are not allowed to update user "+editedUser.name());
}
JSONObject json;
@ -125,7 +138,7 @@ public class UserModule extends PathHandler { @@ -125,7 +138,7 @@ public class UserModule extends PathHandler {
json = json(ex);
} catch (Exception e){
LOG.log(WARNING,"Request does not contain valid JSON",e);
return sendContent(ex,BAD_REQUEST,"Body contains no JSON data");
return sendContent(ex,HTTP_BAD_REQUEST,"Body contains no JSON data");
}
@ -137,7 +150,6 @@ public class UserModule extends PathHandler { @@ -137,7 +150,6 @@ public class UserModule extends PathHandler {
}
private boolean getUserList(HttpExchange ex, UmbrellaUser user) throws IOException {
if (user instanceof DbUser dbUser && dbUser.permissions().contains(LIST_USERS)){
try {
var list = users.list(0, null).stream().map(UmbrellaUser::toMap).toList();
@ -146,23 +158,23 @@ public class UserModule extends PathHandler { @@ -146,23 +158,23 @@ public class UserModule extends PathHandler {
return sendContent(ex,e.statusCode(),e.getMessage());
}
}
return sendContent(ex,FORBIDDEN,"You are not allowed to list users!");
return sendContent(ex,HTTP_FORBIDDEN,"You are not allowed to list users!");
}
private boolean patchPassword(HttpExchange ex, UmbrellaUser requestingUser) throws IOException {
if (!(requestingUser instanceof DbUser user)) return sendContent(ex,SERVER_ERROR,"DbUser expected");
if (!(requestingUser instanceof DbUser user)) return sendContent(ex, ResponseCode.HTTP_SERVER_ERROR,"DbUser expected");
JSONObject json;
try {
json = json(ex);
} catch (Exception e){
LOG.log(WARNING,"Request does not contain valid JSON",e);
return sendContent(ex,BAD_REQUEST,"Body contains no JSON data");
return sendContent(ex,HTTP_BAD_REQUEST,"Body contains no JSON data");
}
if (!json.has("old") || !(json.get("old") instanceof String oldpass) || oldpass.isBlank()) return sendContent(ex,UNPROCESSABLE,"old password missing!");
if (!json.has("new") || !(json.get("new") instanceof String newpass) || newpass.isBlank()) return sendContent(ex,UNPROCESSABLE,"new password missing!");
if (!json.has("old") || !(json.get("old") instanceof String oldpass) || oldpass.isBlank()) return sendContent(ex, HTTP_UNPROCESSABLE,"old password missing!");
if (!json.has("new") || !(json.get("new") instanceof String newpass) || newpass.isBlank()) return sendContent(ex, HTTP_UNPROCESSABLE,"new password missing!");
var old = Password.of(BAD_HASHER.hash(oldpass,null));
if (!user.hashedPassword().equals(old)) return sendContent(ex,UNAUTHORIZED,"Wrong password (old)");
if (weak(newpass)) return sendContent(ex,BAD_REQUEST,"New password too weak!");
if (!user.hashedPassword().equals(old)) return sendContent(ex,HTTP_UNAUTHORIZED,"Wrong password (old)");
if (weak(newpass)) return sendContent(ex,HTTP_BAD_REQUEST,"New password too weak!");
var pass = Password.of(BAD_HASHER.hash(newpass,null));
try {
var updated = users.save(new DbUser(user.id(), user.name(), user.email(), pass, user.theme(), user.language(), user.permissions(), null));
@ -183,8 +195,8 @@ public class UserModule extends PathHandler { @@ -183,8 +195,8 @@ public class UserModule extends PathHandler {
}
private boolean getUser(HttpExchange ex, UmbrellaUser user) throws IOException {
if (user != null) return sendContent(ex,OK,user);
return sendEmptyResponse(UNAUTHORIZED,ex);
if (user != null) return sendContent(ex,user);
return sendEmptyResponse(HTTP_UNAUTHORIZED,ex);
}
public boolean logout(HttpExchange ex, Optional<Token> optToken) throws IOException {
@ -196,23 +208,23 @@ public class UserModule extends PathHandler { @@ -196,23 +208,23 @@ public class UserModule extends PathHandler {
}
new SessionToken(token.toString(),"/", Instant.now().minus(1, DAYS),true).addTo(ex);
return sendEmptyResponse(OK,ex);
return sendEmptyResponse(HTTP_OK,ex);
}
return sendEmptyResponse(UNAUTHORIZED,ex);
return sendEmptyResponse(HTTP_UNAUTHORIZED,ex);
}
private boolean postLogin(HttpExchange ex) throws IOException {
var json = json(ex);
if (!(json.has(USERNAME) && json.get(USERNAME) instanceof String username)) return sendContent(ex,UNPROCESSABLE,"Username missing");
if (!(json.has(PASSWORD) && json.get(PASSWORD) instanceof String password)) return sendContent(ex,UNPROCESSABLE,"Password missing");
if (password.isBlank()) return sendContent(ex,UNAUTHORIZED,"Password must not be blank");
if (!(json.has(USERNAME) && json.get(USERNAME) instanceof String username)) return sendContent(ex, HTTP_UNPROCESSABLE,"Username missing");
if (!(json.has(PASSWORD) && json.get(PASSWORD) instanceof String password)) return sendContent(ex, HTTP_UNPROCESSABLE,"Password missing");
if (password.isBlank()) return sendContent(ex,HTTP_UNAUTHORIZED,"Password must not be blank");
var hashedPass = Password.of(BAD_HASHER.hash(password,null));
try {
var user = users.load(username, hashedPass);
users.getSession(user)
.cookie()
.addTo(ex.getResponseHeaders());
return sendContent(ex,200,user);
return sendContent(ex,user);
} catch (UmbrellaException ue){
return sendContent(ex,ue.statusCode(),ue.getMessage());
}
@ -226,7 +238,7 @@ public class UserModule extends PathHandler { @@ -226,7 +238,7 @@ public class UserModule extends PathHandler {
var theme = json.has(THEME) && json.get(THEME) instanceof String t && !t.isBlank() ? t : user.theme();
var lang = json.has(LANGUAGE) && json.get(LANGUAGE) instanceof String l && !l.isBlank() ? l : user.language();
var saved = users.save(new DbUser(id,name,email,pass,theme,lang, user.permissions(),null));
return sendContent(ex,OK,saved);
return sendContent(ex,HTTP_OK,saved);
}
static int score(String password){

6
user/src/main/java/de/srsoftware/umbrella/user/model/DbUser.java

@ -2,14 +2,14 @@ @@ -2,14 +2,14 @@
package de.srsoftware.umbrella.user.model;
import java.util.Map;
import java.util.Set;
import static de.srsoftware.umbrella.user.model.DbUser.PERMISSION.*;
import static de.srsoftware.umbrella.user.model.DbUser.PERMISSION.IMPERSONATE;
import static de.srsoftware.umbrella.user.model.DbUser.PERMISSION.LIST_USERS;
import static de.srsoftware.umbrella.user.model.DbUser.PERMISSION.MANAGE_LOGIN_SERVICES;
import java.util.Map;
import java.util.Set;
public class DbUser extends UmbrellaUser {
public enum PERMISSION {

4
web/src/main/java/de/srsoftware/umbrella/web/WebHandler.java

@ -2,9 +2,9 @@ @@ -2,9 +2,9 @@
package de.srsoftware.umbrella.web;
import static de.srsoftware.tools.Optionals.nullable;
import static de.srsoftware.umbrella.core.ResponseCode.NOT_FOUND;
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.WARNING;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
import com.sun.net.httpserver.HttpExchange;
import de.srsoftware.tools.Path;
@ -52,7 +52,7 @@ public class WebHandler extends PathHandler { @@ -52,7 +52,7 @@ public class WebHandler extends PathHandler {
return sendContent(addCors(ex),bos.toByteArray());
} catch (Exception e) {
LOG.log(WARNING,"Failed to load {0}",url);
return sendContent(ex,NOT_FOUND,"Failed to load "+url);
return sendContent(ex,HTTP_NOT_FOUND,"Failed to load "+url);
}
}
}

Loading…
Cancel
Save