Browse Source

workin on idc login flow

feature/document
Stephan Richter 4 months ago
parent
commit
b9bff9733d
  1. 2
      frontend/src/App.svelte
  2. 25
      frontend/src/Components/Login.svelte
  3. 46
      frontend/src/routes/user/ConnectedServices.svelte
  4. 9
      frontend/src/routes/user/LoginServices.svelte
  5. 65
      frontend/src/routes/user/Profile.svelte
  6. 85
      frontend/src/routes/user/User.svelte
  7. 7
      translations/src/main/resources/de.json
  8. 2
      user/src/main/java/de/srsoftware/umbrella/user/Constants.java
  9. 1
      user/src/main/java/de/srsoftware/umbrella/user/Paths.java
  10. 85
      user/src/main/java/de/srsoftware/umbrella/user/UserModule.java
  11. 4
      user/src/main/java/de/srsoftware/umbrella/user/model/ForeignLogin.java

2
frontend/src/App.svelte

@ -32,7 +32,7 @@ @@ -32,7 +32,7 @@
<Menu />
<Route path="/user" component={User} />
<Route path="/user/:user_id/edit" component={UserEdit} />
<Route path="/user/service/:serviceName" component={EditService} />
<Route path="/user/oidc/:serviceName" component={EditService} />
<Route>
<p>Page not found</p>
</Route>

25
frontend/src/Components/Login.svelte

@ -4,6 +4,7 @@ @@ -4,6 +4,7 @@
import { checkUser, tryLogin } from '../user.svelte.js';
let credentials = { username : null, password : null }
let services = $state([]);
function doLogin(ev){
tryLogin(credentials);
@ -15,7 +16,26 @@ @@ -15,7 +16,26 @@
onMount(async () => {
await checkUser();
const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/user/oidc/buttons`;
const resp = await fetch(url,{credentials:'include'});
if (resp.ok){
const json = await resp.json();
for (let service of json) services.push(service);
}
});
async function redirectTo(service){
const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/user/oidc/redirect/${service}`;
const resp = await fetch(url,{credentials:'include'});
if (resp.ok){
var json = await resp.json();
if (json.authorization_endpoint) {
var endpoint = json.authorization_endpoint;
delete json.authorization_endpoint;
location.href = endpoint + '?' + new URLSearchParams(json);
}
}
}
</script>
<style>
@ -47,6 +67,7 @@ @@ -47,6 +67,7 @@
</form>
<fieldset>
<legend>{t('login.OIDC_Login')}</legend>
<button>SRSoftware</button>
<button>ORC ID</button>
{#each services as service,i}
<button on:click={() => redirectTo(service)}>{service}</button>
{/each}
</fieldset>

46
frontend/src/routes/user/ConnectedServices.svelte

@ -0,0 +1,46 @@ @@ -0,0 +1,46 @@
<script>
import { t } from '../../translations.svelte.js';
import { user } from '../../user.svelte.js';
import { onMount } from 'svelte';
let connections = $state([]);
onMount(async () => {
let url = `${location.protocol}//${location.host.replace('5173','8080')}/api/user/oidc/connected`;
let resp = await fetch(url,{credentials:'include'});
if (resp.ok){
const arr = await resp.json();
for (let entry of arr){
connections.push(entry)
console.log(entry);
}
}
});
</script>
{#if connections.length>0}
<fieldset tabindex="0">
<legend>{t('user.connected_services')}</legend>
<table>
<thead>
<tr>
<th>{t('user.service')}</th>
<th>{t('user.foreign_id')}</th>
<th>{t('user.actions')}</th>
</tr>
</thead>
<tbody>
{#each connections as connection,i}
<tr>
<td>{connection.service}</td>
<td>{connection.foreign_id}</td>
<td>
<button>{t('user.unlink')}</button>
</td>
</tr>
{/each}
</tbody>
</table>
</fieldset>
{/if}

9
frontend/src/routes/user/LoginServices.svelte

@ -9,7 +9,7 @@ @@ -9,7 +9,7 @@
let services = $state([]);
onMount(async () => {
const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/user/service/buttons`;
const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/user/oidc/buttons`;
const resp = await fetch(url,{credentials:'include'});
if (resp.ok){
const json = await resp.json();
@ -20,7 +20,10 @@ @@ -20,7 +20,10 @@
</script>
<fieldset tabindex="0">
<legend>{t('user.login_services')} <button>{t('user.add_login_service')}</button></legend>
<legend>
{t('user.login_services')}
<button>{t('user.add_login_service')}</button>
</legend>
<table>
<thead>
<tr>
@ -35,7 +38,7 @@ @@ -35,7 +38,7 @@
<td>
<button>{t('user.connect_service')}</button>
{#if user.permissions.includes('MANAGE_LOGIN_SERVICES')}
<button onclick={() => router.navigate(`/user/service/${service}`)}>{t('user.edit')}</button>
<button onclick={() => router.navigate(`/user/oidc/${service}`)}>{t('user.edit')}</button>
<button>{t('user.delete')}</button>
{/if}
</td>

65
frontend/src/routes/user/Profile.svelte

@ -0,0 +1,65 @@ @@ -0,0 +1,65 @@
<script>
import { t } from '../../translations.svelte.js';
import { user } from '../../user.svelte.js';
import { useTinyRouter } from 'svelte-tiny-router';
import EditPassword from './EditPassword.svelte';
const router = useTinyRouter();
let editPassword = false;
</script>
<fieldset>
<legend>
{t('user.your_profile')} <button onclick={() => router.navigate(`/user/${user.id}/edit`)}>{t('user.edit')}</button>
</legend>
<table>
<tbody>
<tr>
<th>{t('user.id')}</th>
<td>{user.id}</td>
</tr>
<tr>
<th>{t('user.name')}</th>
<td>{user.name}</td>
</tr>
<tr>
<th>{t('user.login')}</th>
<td>{user.login}</td>
</tr>
<tr>
<th>{t('user.email')}</th>
<td>{user.email}</td>
</tr>
<tr>
<th>{t('user.language')}</th>
<td>{user.language}</td>
</tr>
<tr>
<th>{t('user.theme')}</th>
<td>{user.theme}</td>
</tr>
<tr>
<th>{t('user.password')}</th>
<td>
{#if editPassword}
<EditPassword bind:editPassword={editPassword} />
{:else}
<button onclick={() => editPassword = true}>{t('user.edit_password')}</button>
{/if}
</td>
</tr>
<tr>
<th>{t('user.permissions')}</th>
<td>
<ul>
{#each user.permissions as permission,i}
<li>{t('user.'+permission)}</li>
{/each}
</ul>
</td>
</tr>
</tbody>
</table>
</fieldset>

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

@ -1,92 +1,17 @@ @@ -1,92 +1,17 @@
<script>
import { t } from '../../translations.svelte.js';
import { user } from '../../user.svelte.js';
import { useTinyRouter } from 'svelte-tiny-router';
import EditPassword from './EditPassword.svelte';
import UserList from './List.svelte';
import Services from './ConnectedServices.svelte';
import LoginServiceList from './LoginServices.svelte';
const router = useTinyRouter();
let editPassword = false;
async function patch(changeset){
const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/user/${user.id}`;
const response = await fetch(url,{
method: 'PATCH',
credentials: 'include',
body: JSON.stringify(changeset)
});
if (response.ok) {
const json = await response.json();
for (let key of Object.keys(json)) user[key] = json[key];
}
}
async function fetchThemes(){
const url = `${location.protocol}//${location.host.replace('5173','8080')}/themes.json`;
return fetch(url);
}
import Profile from './Profile.svelte';
import UserList from './List.svelte';
</script>
<h1>{t('user.user_module')}</h1>
<fieldset>
<legend>
{t('user.your_profile')} <button onclick={() => router.navigate(`/user/${user.id}/edit`)}>{t('user.edit')}</button>
</legend>
<table>
<tbody>
<tr>
<th>{t('user.id')}</th>
<td>{user.id}</td>
</tr>
<tr>
<th>{t('user.name')}</th>
<td>{user.name}</td>
</tr>
<tr>
<th>{t('user.login')}</th>
<td>{user.login}</td>
</tr>
<tr>
<th>{t('user.email')}</th>
<td>{user.email}</td>
</tr>
<tr>
<th>{t('user.language')}</th>
<td>{user.language}</td>
</tr>
<tr>
<th>{t('user.theme')}</th>
<td>{user.theme}</td>
</tr>
<tr>
<th>{t('user.password')}</th>
<td>
{#if editPassword}
<EditPassword bind:editPassword={editPassword} />
{:else}
<button onclick={() => editPassword = true}>{t('user.edit_password')}</button>
{/if}
</td>
</tr>
<tr>
<th>{t('user.permissions')}</th>
<td>
<ul>
{#each user.permissions as permission,i}
<li>{t('user.'+permission)}</li>
{/each}
</ul>
</td>
</tr>
</tbody>
</table>
</fieldset>
<Profile />
<Services />
{#if user.permissions.includes('LIST_USERS')}
<UserList />

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

@ -29,6 +29,7 @@ @@ -29,6 +29,7 @@
"client_id": "Client-ID",
"client_secret": "Client-Geheimnis",
"connect_service": "mit Service verbinden",
"connected_services": "verbundene Login-Services",
"CREATE_USERS": "NUTZER ANLEGEN",
"data_sent": "Daten übermittelt",
"delete": "löschen",
@ -39,6 +40,7 @@ @@ -39,6 +40,7 @@
"edit_service": "Login-Service \"{0}\" bearbeiten",
"email": "E-Mail",
"failed": "fehlgeschlagen",
"foreign_id": "externe Kennung",
"id": "Id",
"impersonate": "zu Nutzer wechseln",
"IMPERSONATE": "NUTZER WECHSELN",
@ -62,8 +64,9 @@ @@ -62,8 +64,9 @@
"save_user": "Nutzer speichern",
"service": "Service",
"theme": "Design",
"your_profile": "dein Profil",
"unlink": "Trennen",
"update": "aktualisieren",
"user_module" : "Umbrella User-Verwaltung"
"user_module" : "Umbrella User-Verwaltung",
"your_profile": "dein Profil"
}
}

2
user/src/main/java/de/srsoftware/umbrella/user/Constants.java

@ -28,6 +28,7 @@ public class Constants { @@ -28,6 +28,7 @@ public class Constants {
public static final String LAST_LOGOFF = "last_logoff";
public static final String LOGIN_SERVICES = "login_services";
public static final String MESSAGE_DELIVERY = "message_delivery";
public static final String OIDC = "oidc";
public static final String OIDC_CALLBACK = "redirect_uri";
public static final String OIDC_LINK = "oidc_link";
public static final String OIDC_SCOPE = "openid";
@ -39,7 +40,6 @@ public class Constants { @@ -39,7 +40,6 @@ public class Constants {
public static final String REDIRECT_URI = "redirect_uri";
public static final String RESPONSE_TYPE = "response_type";
public static final String SCOPE = "scope";
public static final String SERVICE = "service";
public static final String SERVICE_ID = "service_id";
public static final String TABLE_LOGIN_SERVICES = "user_login_services";

1
user/src/main/java/de/srsoftware/umbrella/user/Paths.java

@ -5,6 +5,7 @@ public class Paths { @@ -5,6 +5,7 @@ public class Paths {
private Paths(){}
public static final String CALLBACK = "callback";
public static final String CONNECTED = "connected";
public static final String DASH = "dash";
public static final String IMPERSONATE = "impersonate";
public static final String INSTALL = "install";

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

@ -6,7 +6,6 @@ import static de.srsoftware.umbrella.core.Constants.*; @@ -6,7 +6,6 @@ import static de.srsoftware.umbrella.core.Constants.*;
import static de.srsoftware.umbrella.core.Paths.LIST;
import static de.srsoftware.umbrella.core.Paths.LOGOUT;
import static de.srsoftware.umbrella.core.ResponseCode.*;
import static de.srsoftware.umbrella.core.ResponseCode.HTTP_NOT_IMPLEMENTED;
import static de.srsoftware.umbrella.core.ResponseCode.HTTP_SERVER_ERROR;
import static de.srsoftware.umbrella.user.Constants.*;
import static de.srsoftware.umbrella.user.Paths.*;
@ -15,6 +14,7 @@ import static de.srsoftware.umbrella.user.model.DbUser.PERMISSION; @@ -15,6 +14,7 @@ import static de.srsoftware.umbrella.user.model.DbUser.PERMISSION;
import static de.srsoftware.umbrella.user.model.DbUser.PERMISSION.*;
import static java.lang.System.Logger.Level.WARNING;
import static java.net.HttpURLConnection.*;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.text.MessageFormat.format;
import static java.time.temporal.ChronoUnit.DAYS;
@ -22,24 +22,34 @@ import com.sun.net.httpserver.HttpExchange; @@ -22,24 +22,34 @@ 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.LoginServiceDb;
import de.srsoftware.umbrella.user.api.UserDb;
import de.srsoftware.umbrella.user.model.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.*;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.*;
import org.json.JSONObject;
public class UserModule extends PathHandler {
private record State(LoginService loginService, JSONObject config){
public static State of(LoginService loginService, JSONObject config) {
return new State(loginService,config);
}
}
private static final BadHasher BAD_HASHER;
private static final System.Logger LOG = System.getLogger("User");
private final UserDb users;
private final LoginServiceDb logins;
private final HashMap<String, State> stateMep = new HashMap<>(); // map from state to OIDC provider name
static {
try {
@ -83,7 +93,7 @@ public class UserModule extends PathHandler { @@ -83,7 +93,7 @@ public class UserModule extends PathHandler {
switch (head) {
case LIST: return getUserList(ex, user);
case LOGOUT: return logout(ex, sessionToken);
case SERVICE: return getService(ex,user,path);
case OIDC: return getService(ex,user,path);
case WHOAMI: return getUser(ex, user);
};
@ -124,7 +134,7 @@ public class UserModule extends PathHandler { @@ -124,7 +134,7 @@ public class UserModule extends PathHandler {
try {
if (head == null || head.isBlank()) return sendContent(ex, HTTP_UNPROCESSABLE,"User id missing!");
if (PASSWORD.equals(head)) return patchPassword(ex,requestingUser);
if (SERVICE.equals(head)) return patchService(ex,path.pop(),requestingUser);
if (OIDC.equals(head)) return patchService(ex,path.pop(),requestingUser);
userId = Long.parseLong(head);
} catch (NumberFormatException e) {
return sendContent(ex, HTTP_UNPROCESSABLE,"Invalid user id: "+head);
@ -178,11 +188,74 @@ public class UserModule extends PathHandler { @@ -178,11 +188,74 @@ public class UserModule extends PathHandler {
return switch (head){
case BUTTONS -> getOidcButtons(ex);
case LIST -> getServiceList(ex,user);
case CONNECTED -> getConnectedServices(ex,user);
case REDIRECT -> getOidcRedirect(ex,path.pop());
case null -> super.doGet(path,ex);
default -> getService(ex,user,head);
};
}
public static HttpURLConnection open(URL url) throws IOException {
var conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Accept","*/*");
conn.setRequestProperty("Host",url.getHost());
conn.setRequestProperty("User-Agent","Umbrella/0.1");
return conn;
}
private JSONObject getOidcConfig(LoginService service) throws UmbrellaException {
URL url = null;
try {
url = new URI(service.url()+"/.well-known/openid-configuration").toURL();
var is = open(url).getInputStream();
var bos = new ByteArrayOutputStream();
is.transferTo(bos);
is.close();
return new JSONObject(bos.toString(UTF_8));
} catch (MalformedURLException | URISyntaxException e) {
throw new UmbrellaException(500,"Failed to create URL from \"{0}\"!",service.url()).causedBy(e);
} catch (IOException e) {
throw new UmbrellaException(500,"Failed to read from \"{0}\"!",url).causedBy(e);
}
}
private boolean getOidcRedirect(HttpExchange ex, String name) throws IOException {
try {
var loginService = logins.loadLoginService(name);
var config = getOidcConfig(loginService);
if (!config.has(AUTH_ENDPOINT)) {
LOG.log(WARNING, "OpenID-Configuration does not declare an {0}!", AUTH_ENDPOINT);
throw new UmbrellaException(424, "No authorization endpoint configured for {0}", loginService.name());
}
var returnTo = queryParam(ex).get("returnTo");
if (isSet(returnTo)) config.put("returnTo",returnTo);
var url = url(ex);
var callback = url.replaceAll("/api/.*", "/callback"); // TODO: frontendPath an zweiter stelle
var authEndpoint = config.getString(AUTH_ENDPOINT);
var clientId = loginService.clientId();
var state = UUID.randomUUID().toString();
stateMep.put(state, State.of(loginService, config));
return sendContent(ex,Map.of(OIDC_CALLBACK, callback, AUTH_ENDPOINT, authEndpoint, SCOPE, OIDC_SCOPE, CLIENT_ID, clientId, RESPONSE_TYPE, CODE, STATE, state));
} catch (UmbrellaException e){
return send(ex,e);
}
}
private boolean send(HttpExchange ex, UmbrellaException e) throws IOException {
return sendContent(ex,e.statusCode(),e.getMessage());
}
private boolean getConnectedServices(HttpExchange ex, UmbrellaUser user) throws IOException {
if (user == null) return sendEmptyResponse(HTTP_UNAUTHORIZED,ex);
try {
var connections = logins.listAssignments(user.id()).stream().map(ForeignLogin::toMap);
return sendContent(ex,connections);
} catch (UmbrellaException e) {
return sendContent(ex,e.statusCode(),e.getMessage());
}
}
private boolean getService(HttpExchange ex, UmbrellaUser user, String serviceId) throws IOException {
if (!(user instanceof DbUser dbUser && dbUser.permissions().contains(MANAGE_LOGIN_SERVICES))) return sendEmptyResponse(HTTP_FORBIDDEN,ex);
try {

4
user/src/main/java/de/srsoftware/umbrella/user/model/ForeignLogin.java

@ -3,7 +3,7 @@ package de.srsoftware.umbrella.user.model; @@ -3,7 +3,7 @@ package de.srsoftware.umbrella.user.model;
import static de.srsoftware.umbrella.core.Constants.USER_ID;
import static de.srsoftware.umbrella.user.Constants.FOREIGN_ID;
import static de.srsoftware.umbrella.user.Constants.SERVICE;
import static de.srsoftware.umbrella.user.Constants.OIDC;
import de.srsoftware.tools.Mappable;
import java.util.Map;
@ -15,6 +15,6 @@ public record ForeignLogin(String loginService, String foreingId, Long userId) i @@ -15,6 +15,6 @@ public record ForeignLogin(String loginService, String foreingId, Long userId) i
@Override
public Map<String, Object> toMap() {
return Map.of(SERVICE,loginService,FOREIGN_ID,foreingId, USER_ID,userId);
return Map.of(OIDC,loginService,FOREIGN_ID,foreingId, USER_ID,userId);
}
}

Loading…
Cancel
Save