auth

Main authentication module for my projects
git clone git://git.finwo.net/app/auth
Log | Files | Refs

commit 07ce0aa3a1e939e66085641df52a72975e454d94
parent d5d1100cbe90815e959863a8f256ec3886f67707
Author: finwo <finwo@pm.me>
Date:   Sun, 25 Oct 2026 13:52:49 +0100

Added admin user management

Diffstat:
Mapp/account/src/assets/account.css | 2+-
Mapp/admin/src/assets/admin.css | 19+++++++++++++++----
Mapp/admin/src/component/realm-selector.tsx | 15+++++++++++----
Mapp/admin/src/main.ts | 15+++++++++++++++
Mapp/admin/src/screen/admin.tsx | 115+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Aapp/admin/src/screen/global-user.tsx | 225+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/admin/src/screen/user.tsx | 565+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aapp/admin/src/screen/users.tsx | 303+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mapp/admin/src/util/api.ts | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mapp/admin/src/util/auth.ts | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mapp/shared/style/global.css | 31+++++++++++++++++++++++++++----
Mmockup/plain/admin-client-detail.html | 2+-
Mmockup/plain/admin-clients.html | 2+-
Mmockup/plain/admin-dashboard.html | 2+-
Amockup/plain/admin-user-detail.html | 451+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Amockup/plain/admin-user-global-detail.html | 266+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Amockup/plain/admin-users.html | 315+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mmockup/plain/global.css | 38+++++++++++++++++++++++++++++++++++---
Mserver/src/controller/admin/bans/create.js | 12+++++++-----
Mserver/src/controller/admin/bans/delete.js | 12+++++++-----
Mserver/src/controller/admin/consents/revoke.js | 12+++++++-----
Aserver/src/controller/admin/session/me.js | 15+++++++++++++++
Aserver/src/controller/admin/users-global/get.js | 23+++++++++++++++++++++++
Aserver/src/controller/admin/users-global/list.js | 15+++++++++++++++
Aserver/src/controller/admin/users/get.js | 26++++++++++++++++++++++++++
Aserver/src/controller/admin/users/list.js | 21+++++++++++++++++++++
Aserver/src/lib/admin-users.js | 343+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/test/http.test.js | 217+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
28 files changed, 3204 insertions(+), 42 deletions(-)

diff --git a/app/account/src/assets/account.css b/app/account/src/assets/account.css @@ -98,7 +98,7 @@ padding: 0.5rem 0; border: 0; background: none; - color: var(--danger); + color: var(--danger-text); font: inherit; font-size: 0.875rem; cursor: pointer; diff --git a/app/admin/src/assets/admin.css b/app/admin/src/assets/admin.css @@ -89,7 +89,7 @@ } .session-badge { - color: var(--danger); + color: var(--danger-text); font-size: 0.75rem; line-height: 1.4; } @@ -170,12 +170,14 @@ margin: 0; } -.client-title { +.client-title, +.user-title { color: inherit; text-decoration: none; } -.client-title:hover { +.client-title:hover, +.user-title:hover { color: var(--accent-text-hover); } @@ -265,6 +267,15 @@ opacity: 1; } +select.field-control, +.realm-select select { + appearance: none; + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='0.75em' height='0.75em' viewBox='0 0 24 24' fill='none' stroke='%238a8f95' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E"); + background-repeat: no-repeat; + background-position: right 0.75rem center; + padding-right: 2.25rem; +} + .role-field { margin: 0; padding: 0; @@ -315,7 +326,7 @@ } .danger-zone h2 { - color: var(--danger); + color: var(--danger-text); } .secret-value { diff --git a/app/admin/src/component/realm-selector.tsx b/app/admin/src/component/realm-selector.tsx @@ -5,23 +5,26 @@ interface RealmSelectorAttrs { realms: AdminRealm[] | null; selected: AdminRealm | null; onchange: (slug: string) => void; + allRealms?: boolean; + selectedAll?: boolean; } export const RealmSelector: m.Component<RealmSelectorAttrs> = { view({ attrs }) { - const { realms, selected } = attrs; + const { realms, selected, allRealms = false, selectedAll = false } = attrs; - if (realms && realms.length > 1) { + if ((realms && realms.length > 1) || allRealms) { return ( <label class="realm-select"> <span>Realm</span> <select - value={selected?.slug || ''} + value={selectedAll ? 'global' : selected?.slug || ''} onchange={(event: Event) => { attrs.onchange((event.target as HTMLSelectElement).value); }} > - {realms.map((realm) => ( + {allRealms ? <option value="global">All realms</option> : null} + {(realms || []).map((realm) => ( <option value={realm.slug}>{realm.display_name}</option> ))} </select> @@ -33,6 +36,10 @@ export const RealmSelector: m.Component<RealmSelectorAttrs> = { return <span class="realm-current">{selected.display_name}</span>; } + if (selectedAll) { + return <span class="realm-current">All realms</span>; + } + return null; }, }; diff --git a/app/admin/src/main.ts b/app/admin/src/main.ts @@ -25,6 +25,21 @@ const routes: m.RouteDefs = { '/clients/:realm/edit/:client': { render: () => m(Admin, {}), }, + '/users': { + render: () => m(Admin, {}), + }, + '/users/global': { + render: () => m(Admin, {}), + }, + '/users/global/:userId': { + render: () => m(Admin, {}), + }, + '/users/:realm': { + render: () => m(Admin, {}), + }, + '/users/:realm/:userId': { + render: () => m(Admin, {}), + }, '/callback': { render: () => m(AdminCallback, {}), }, diff --git a/app/admin/src/screen/admin.tsx b/app/admin/src/screen/admin.tsx @@ -1,4 +1,4 @@ -import { Activity, AppWindow, LayoutGrid } from 'lucide'; +import { Activity, AppWindow, LayoutGrid, Users } from 'lucide'; import m from 'mithril'; import { AppShell } from '@component/app-shell'; import { Nav, type NavItem } from '@component/nav'; @@ -11,6 +11,7 @@ import { clearAdminTokens, completeAdminLogin, getAdminTokens, + loadAdminMe, loadAdminRealms, loadAdminUser, startAdminLogin, @@ -20,6 +21,9 @@ import { OverviewPage } from './overview'; import { SessionsPage } from './sessions'; import { ClientEditPage } from './client-edit'; import { ClientsPage } from './clients'; +import { GlobalUserPage } from './global-user'; +import { UserPage } from './user'; +import { UsersPage } from './users'; function currentPath() { return (m.route.get() || '/').split('?')[0]; @@ -62,8 +66,48 @@ function clientEditPath() { } } +function usersRealm() { + const path = currentPath(); + if (path !== '/users' && !path.startsWith('/users/')) return null; + const suffix = path.slice('/users/'.length); + if (!suffix) return null; + const slug = suffix.split('/')[0]; + try { + return decodeURIComponent(slug); + } catch { + return null; + } +} + +function userDetailPath() { + const path = currentPath(); + if (path === '/users/global' || path.startsWith('/users/global/')) return null; + const match = /^\/users\/([^/]+)\/([^/]+)$/.exec(path); + if (!match) return null; + try { + return { + realmSlug: decodeURIComponent(match[1]), + userId: decodeURIComponent(match[2]), + }; + } catch { + return null; + } +} + +function globalUserDetailPath() { + const path = currentPath(); + const match = /^\/users\/global\/([^/]+)$/.exec(path); + if (!match) return null; + try { + return { userId: decodeURIComponent(match[1]) }; + } catch { + return null; + } +} + export const Admin: m.Component = { user: null as UserInfo | null, + systemAdmin: false, realms: null as AdminRealm[] | null, realmsError: null as Error | null, error: null as Error | null, @@ -115,6 +159,17 @@ export const Admin: m.Component = { this.realms = []; this.realmsError = e as Error; } + + try { + const me = await loadAdminMe(); + this.systemAdmin = me.is_system_admin; + } catch (e: any) { + if (e?.status === 401 || e?.status === 400) { + await this.login(); + return; + } + this.systemAdmin = false; + } m.redraw(); }, @@ -136,13 +191,18 @@ export const Admin: m.Component = { const path = currentPath(); const clients = path === '/clients' || path.startsWith('/clients/'); const sessions = path === '/sessions' || path.startsWith('/sessions/'); + const users = path === '/users' || path.startsWith('/users/'); const title = clients ? path.includes('/edit/') ? 'Edit client | Administration' : 'Clients | Administration' : sessions ? 'Sessions | Administration' - : 'Administration'; + : users + ? userDetailPath() || globalUserDetailPath() + ? 'User | Administration' + : 'Users | Administration' + : 'Administration'; document.title = title; }, @@ -155,9 +215,14 @@ export const Admin: m.Component = { const path = currentPath(); const sessions = path === '/sessions' || path.startsWith('/sessions/'); const clients = path === '/clients' || path.startsWith('/clients/'); + const users = path === '/users' || path.startsWith('/users/'); const realmSlug = sessionsRealm(); const clientRealmSlug = clientsRealm(); + const userRealmSlug = usersRealm(); const clientEdit = clientEditPath(); + const userDetail = userDetailPath(); + const globalUser = globalUserDetailPath(); + const isGlobalUsers = usersRealm() === 'global'; const firstRealm = this.realms && this.realms.length > 0 ? this.realms[0].slug : null; const sessionsHref = firstRealm ? `/sessions/${encodeURIComponent(firstRealm)}` @@ -165,13 +230,14 @@ export const Admin: m.Component = { const clientsHref = firstRealm ? `/clients/${encodeURIComponent(firstRealm)}` : '/clients'; + const usersHref = firstRealm ? `/users/${encodeURIComponent(firstRealm)}` : '/users'; const navItems: NavItem[] = [ { href: appUrl('/'), label: 'Overview', icon: LayoutGrid, - active: !sessions && !clients, + active: !sessions && !clients && !users, onclick: (event: Event) => { event.preventDefault(); m.route.set('/'); @@ -192,12 +258,22 @@ export const Admin: m.Component = { label: 'Sessions', icon: Activity, active: sessions, - onclick: (event: Event) => { - event.preventDefault(); - m.route.set(sessionsHref); + onclick: (event: Event) => { + event.preventDefault(); + m.route.set(sessionsHref); + }, }, - }, - ]; + { + href: appUrl(usersHref), + label: 'Users', + icon: Users, + active: users, + onclick: (event: Event) => { + event.preventDefault(); + m.route.set(usersHref); + }, + }, + ]; return ( <AppShell @@ -249,6 +325,29 @@ export const Admin: m.Component = { realmsError={this.realmsError} onAuthExpired={() => this.authExpired()} /> + ) : users && globalUser ? ( + <GlobalUserPage + userId={globalUser.userId} + realmsError={this.realmsError} + onAuthExpired={() => this.authExpired()} + /> + ) : users && userDetail ? ( + <UserPage + realmSlug={userDetail.realmSlug} + userId={userDetail.userId} + realms={this.realms} + realmsError={this.realmsError} + onAuthExpired={() => this.authExpired()} + /> + ) : users ? ( + <UsersPage + realmSlug={userRealmSlug} + realms={this.realms} + realmsError={this.realmsError} + onAuthExpired={() => this.authExpired()} + isSystemAdmin={Boolean(this.systemAdmin)} + isGlobal={isGlobalUsers} + /> ) : sessions ? ( <SessionsPage realmSlug={realmSlug} diff --git a/app/admin/src/screen/global-user.tsx b/app/admin/src/screen/global-user.tsx @@ -0,0 +1,225 @@ +import m from 'mithril'; +import { PageHeader } from '@component/page-header'; +import { loadAdminGlobalUser } from '../util/auth'; +import { appUrl, type AdminGlobalUserMembership, type AdminGlobalUserDetail } from '../util/api'; +import { formatTime } from '@util/format'; + +interface GlobalUserAttrs { + userId: string | null; + realmsError: Error | null; + onAuthExpired: () => void; +} + +function globalStatusLabel(user: AdminGlobalUserDetail['user']) { + if (user.status !== 'active') return user.status === 'disabled' ? 'Disabled' : user.status; + return 'Active'; +} + +export const GlobalUserPage: m.Component<GlobalUserAttrs> = { + attrs: null as GlobalUserAttrs | null, + loadedUser: null as string | null, + loading: false, + detail: null as AdminGlobalUserDetail | null, + error: null as Error | null, + + oninit(this: any, vnode: m.Vnode<GlobalUserAttrs>) { + this.attrs = vnode.attrs; + this.ensure(); + }, + + onupdate(this: any, vnode: m.Vnode<GlobalUserAttrs>) { + this.attrs = vnode.attrs; + this.ensure(); + }, + + ensure(this: any) { + const { userId } = this.attrs; + if (!userId || this.loadedUser === userId) return; + this.loadedUser = userId; + this.detail = null; + this.error = null; + this.load(userId); + }, + + async load(this: any, userId: string) { + this.loading = true; + this.error = null; + m.redraw(); + + try { + const detail = await loadAdminGlobalUser(userId); + if (this.loadedUser === userId) this.detail = detail; + } catch (e: any) { + if (this.loadedUser !== userId) return; + if (e?.status === 401 || e?.status === 400) { + this.attrs.onAuthExpired(); + return; + } + this.error = e as Error; + } finally { + if (this.loadedUser === userId) this.loading = false; + m.redraw(); + } + }, + + view(this: any) { + const { realmsError, userId } = this.attrs; + const detail = this.detail; + const displayName = detail?.user.display_name || detail?.user.username || userId || 'User'; + + return ( + <div> + <PageHeader row title="User" subtitle="Global identity and realm memberships."> + <a class="button-secondary" href={appUrl('/users/global')} onclick={(event: Event) => { + event.preventDefault(); + m.route.set('/users/global'); + }}> + All realms + </a> + </PageHeader> + + <div class="client-breadcrumb"> + <a + href={appUrl('/users/global')} + onclick={(event: Event) => { + event.preventDefault(); + m.route.set('/users/global'); + }} + > + Users + </a> + <span aria-hidden="true">/</span> + <span>{displayName}</span> + </div> + + {realmsError ? ( + <div class="alert" role="alert"> + {realmsError.message} + </div> + ) : null} + + {this.error ? ( + <div class="alert" role="alert"> + <p>{this.error.message}</p> + {userId ? ( + <button class="button-secondary" type="button" onclick={() => this.load(userId)}> + Try again + </button> + ) : null} + </div> + ) : null} + + {this.loading || !detail ? ( + <div class="panel" aria-busy="true"> + <div class="skeleton skeleton-title"></div> + <div class="skeleton"></div> + <div class="skeleton skeleton-short"></div> + </div> + ) : ( + <div class="client-stack"> + <section class="panel"> + <div class="panel-header"> + <h2>Account</h2> + </div> + <dl class="details"> + <div> + <dt>Display name</dt> + <dd>{detail.user.display_name || detail.user.username}</dd> + </div> + <div> + <dt>Username</dt> + <dd>{detail.user.username}</dd> + </div> + <div> + <dt>Email</dt> + <dd>{detail.user.email || 'No verified email'}</dd> + </div> + <div> + <dt>Home realm</dt> + <dd>{detail.user.home_realm_slug || 'None'}</dd> + </div> + <div> + <dt>Status</dt> + <dd>{globalStatusLabel(detail.user)}</dd> + </div> + <div> + <dt>System admin</dt> + <dd>{detail.user.is_system_admin ? 'Yes' : 'No'}</dd> + </div> + <div> + <dt>Last login</dt> + <dd>{detail.user.last_login_at ? formatTime(detail.user.last_login_at) : 'Never'}</dd> + </div> + <div> + <dt>Created</dt> + <dd>{formatTime(detail.user.created_at)}</dd> + </div> + </dl> + </section> + + <section class="panel"> + <div class="panel-header"> + <div> + <h2>Realm memberships</h2> + <p class="note">App access is managed in the realm where the user is a member.</p> + </div> + </div> + {detail.memberships.length === 0 ? ( + <div class="empty"> + <p>This user is not currently a member of any realm.</p> + </div> + ) : ( + <div class="data-table-wrap"> + <table class="data-table data-table-static"> + <thead> + <tr> + <th class="data-table-primary" scope="col">Realm</th> + <th scope="col">Relationship</th> + <th scope="col">Membership</th> + <th scope="col">Roles</th> + <th scope="col">Action</th> + </tr> + </thead> + <tbody> + {detail.memberships.map((membership: AdminGlobalUserMembership) => { + const href = `/users/${encodeURIComponent(membership.slug)}/${encodeURIComponent(detail.user.id)}`; + return ( + <tr> + <td class="data-table-primary"> + <strong>{membership.display_name}</strong> + <span class="data-table-sub">{membership.slug}</span> + </td> + <td>{membership.relationship === 'home' ? 'Home' : 'Guest'}</td> + <td> + {membership.membership_status} + {membership.banned ? ( + <span class="data-table-status">Banned</span> + ) : null} + </td> + <td>{membership.roles.length ? membership.roles.join(', ') : 'None'}</td> + <td> + <a + class="button-secondary" + href={appUrl(href)} + onclick={(event: Event) => { + event.preventDefault(); + m.route.set(href); + }} + > + Manage access + </a> + </td> + </tr> + ); + })} + </tbody> + </table> + </div> + )} + </section> + </div> + )} + </div> + ); + }, +}; diff --git a/app/admin/src/screen/user.tsx b/app/admin/src/screen/user.tsx @@ -0,0 +1,565 @@ +import m from 'mithril'; +import { Modal } from '@component/modal'; +import { PageHeader } from '@component/page-header'; +import { RealmSelector } from '../component/realm-selector'; +import { + createAdminUserBan, + deleteAdminUserBan, + loadAdminClients, + loadAdminUserDetail, + revokeAdminUserConsent, +} from '../util/auth'; +import { + appUrl, + type AdminClient, + type AdminRealm, + type AdminUserBan, + type AdminUserConsent, + type AdminUserDetail, +} from '../util/api'; +import { formatTime } from '@util/format'; + +interface UserAttrs { + realmSlug: string | null; + userId: string | null; + realms: AdminRealm[] | null; + realmsError: Error | null; + onAuthExpired: () => void; +} + +type UserAction = 'revoke' | 'unban'; + +interface UserConfirm { + type: UserAction; + clientId: string; + label: string; +} + +function detailKey(realmSlug: string | null, userId: string | null) { + return `${realmSlug || ''}:${userId || ''}`; +} + +function actionKey(action: UserConfirm) { + return `${action.type}:${action.clientId}`; +} + +function grantedLabel(consent: AdminUserConsent) { + return consent.granted_via === 'trusted' ? 'Trusted client' : 'User consent'; +} + +function banLabel(ban: AdminUserBan) { + return ban.client_id === '*' ? 'All apps' : ban.client_name || ban.client_id; +} + +function membershipLabel(detail: AdminUserDetail) { + const relationship = detail.user.relationship === 'home' ? 'Home realm' : 'Guest'; + const status = detail.user.membership_status; + return status && status !== 'active' ? `${relationship} ยท ${status}` : relationship; +} + +function statusLabel(detail: AdminUserDetail) { + if (detail.user.status !== 'active') { + return detail.user.status === 'disabled' ? 'Disabled' : detail.user.status; + } + if (detail.user.membership_status && detail.user.membership_status !== 'active') { + const status = detail.user.membership_status; + return status[0].toUpperCase() + status.slice(1); + } + if (detail.user.banned) return 'Banned'; + return 'Active'; +} + +export const UserPage: m.Component<UserAttrs> = { + attrs: null as UserAttrs | null, + loadedKey: null as string | null, + loading: false, + redirecting: false, + detail: null as AdminUserDetail | null, + clients: [] as AdminClient[], + error: null as Error | null, + notice: null as string | null, + confirm: null as UserConfirm | null, + pendingAction: false, + banOpen: false, + banClientId: '*', + banPending: false, + + oninit(this: any, vnode: m.Vnode<UserAttrs>) { + this.attrs = vnode.attrs; + this.ensure(); + }, + + onupdate(this: any, vnode: m.Vnode<UserAttrs>) { + this.attrs = vnode.attrs; + this.ensure(); + }, + + ensure(this: any) { + const { realms, realmSlug, userId } = this.attrs; + if (!realms) return; + + if (realms.length === 0) { + this.detail = null; + this.loading = false; + this.error = null; + return; + } + + const selected = realmSlug && realms.some((realm) => realm.slug === realmSlug); + if (!selected) { + if (!this.redirecting) { + this.redirecting = true; + m.route.set(`/users/${encodeURIComponent(realms[0].slug)}`, null, { replace: true }); + } + return; + } + + this.redirecting = false; + const key = detailKey(realmSlug, userId); + if (key === this.loadedKey) return; + + this.loadedKey = key; + this.detail = null; + this.clients = []; + this.error = null; + this.notice = null; + this.confirm = null; + this.pendingAction = false; + this.banOpen = false; + this.banClientId = '*'; + this.banPending = false; + if (realmSlug && userId) this.load(realmSlug, userId); + }, + + async load(this: any, realmSlug: string, userId: string) { + this.loading = true; + this.error = null; + this.notice = null; + m.redraw(); + + try { + const [detail, clients] = await Promise.all([ + loadAdminUserDetail(realmSlug, userId), + loadAdminClients(realmSlug), + ]); + if (this.loadedKey === detailKey(realmSlug, userId)) { + this.detail = detail; + this.clients = clients; + } + } catch (e: any) { + if (this.loadedKey !== detailKey(realmSlug, userId)) return; + if (e?.status === 401 || e?.status === 400) { + this.attrs.onAuthExpired(); + return; + } + this.error = e as Error; + } finally { + if (this.loadedKey === detailKey(realmSlug, userId)) this.loading = false; + m.redraw(); + } + }, + + cancelAction(this: any) { + this.confirm = null; + this.banOpen = false; + m.redraw(); + }, + + async submitAction(this: any) { + const { realmSlug, userId } = this.attrs; + if (!realmSlug || !userId || !this.confirm) return; + + const action = this.confirm; + this.pendingAction = true; + this.error = null; + this.notice = null; + + try { + if (action.type === 'revoke') { + await revokeAdminUserConsent(realmSlug, userId, action.clientId); + this.notice = 'Consent revoked. The app must request access again.'; + } else { + await deleteAdminUserBan(realmSlug, userId, action.clientId); + this.notice = 'App ban removed.'; + } + this.confirm = null; + await this.load(realmSlug, userId); + } catch (e: any) { + if (e?.status === 401 || e?.status === 400) { + this.attrs.onAuthExpired(); + return; + } + this.error = e as Error; + } finally { + this.pendingAction = false; + m.redraw(); + } + }, + + async submitBan(this: any) { + const { realmSlug, userId } = this.attrs; + if (!realmSlug || !userId) return; + + this.banPending = true; + this.error = null; + this.notice = null; + + try { + await createAdminUserBan(realmSlug, userId, this.banClientId); + this.banOpen = false; + this.notice = 'App ban created.'; + await this.load(realmSlug, userId); + } catch (e: any) { + if (e?.status === 401 || e?.status === 400) { + this.attrs.onAuthExpired(); + return; + } + this.error = e as Error; + } finally { + this.banPending = false; + m.redraw(); + } + }, + + view(this: any) { + const { realms, realmsError, realmSlug, userId } = this.attrs; + const selected = + realms?.find((realm) => realm.slug === realmSlug) || realms?.[0] || null; + const detail = this.detail; + const usersHref = `/users/${encodeURIComponent(realmSlug || '')}`; + const displayName = detail?.user.display_name || detail?.user.username || userId || 'User'; + + return ( + <div> + <PageHeader row title="User" subtitle="Account, consent and app restrictions."> + <RealmSelector + realms={realms} + selected={selected} + onchange={(slug: string) => { + m.route.set(`/users/${encodeURIComponent(slug)}`); + }} + /> + </PageHeader> + + <div class="client-breadcrumb"> + <a + href={appUrl(usersHref)} + onclick={(event: Event) => { + event.preventDefault(); + m.route.set(usersHref); + }} + > + Users + </a> + <span aria-hidden="true">/</span> + <span>{displayName}</span> + </div> + + {realmsError ? ( + <div class="alert" role="alert"> + {realmsError.message} + </div> + ) : null} + + {this.error ? ( + <div class="alert" role="alert"> + <p>{this.error.message}</p> + <button + class="button-secondary" + type="button" + onclick={() => { + if (realmSlug && userId) this.load(realmSlug, userId); + }} + > + Try again + </button> + </div> + ) : null} + + {this.notice ? ( + <div class="notice" role="status"> + {this.notice} + </div> + ) : null} + + {!realms ? ( + <div class="loading">Loading realms</div> + ) : this.loading || this.redirecting ? ( + <div class="panel" aria-busy="true"> + <div class="skeleton skeleton-title"></div> + <div class="skeleton"></div> + <div class="skeleton skeleton-short"></div> + </div> + ) : detail ? ( + <div class="client-stack"> + <section class="panel"> + <h2>Account</h2> + <dl class="details"> + <div> + <dt>Display name</dt> + <dd>{detail.user.display_name || detail.user.username}</dd> + </div> + <div> + <dt>Username</dt> + <dd>{detail.user.username}</dd> + </div> + <div> + <dt>Email</dt> + <dd>{detail.user.email || 'No verified email'}</dd> + </div> + <div> + <dt>Realm membership</dt> + <dd>{membershipLabel(detail)}</dd> + </div> + <div> + <dt>Status</dt> + <dd>{statusLabel(detail)}</dd> + </div> + <div> + <dt>Roles</dt> + <dd>{detail.user.roles.length ? detail.user.roles.join(', ') : 'None'}</dd> + </div> + <div> + <dt>System admin</dt> + <dd>{detail.user.is_system_admin ? 'Yes' : 'No'}</dd> + </div> + <div> + <dt>Last login</dt> + <dd>{detail.user.last_login_at ? formatTime(detail.user.last_login_at) : 'Never'}</dd> + </div> + </dl> + </section> + + <section class="panel"> + <div class="panel-header"> + <h2>Application consents</h2> + </div> + {detail.consents.length === 0 ? ( + <div class="empty"> + <p>No consents have been recorded for this realm.</p> + </div> + ) : ( + <div class="data-table-wrap"> + <table class="data-table data-table-static"> + <thead> + <tr> + <th class="data-table-primary" scope="col">Application</th> + <th scope="col">Scopes</th> + <th scope="col">Granted</th> + <th scope="col">Status</th> + <th scope="col">Updated</th> + <th scope="col">Action</th> + </tr> + </thead> + <tbody> + {detail.consents.map((consent: AdminUserConsent) => ( + <tr> + <td class="data-table-primary"> + <strong>{consent.client_name || 'Unknown client'}</strong> + <span class="data-table-sub">{consent.client_id}</span> + </td> + <td>{consent.scopes.length ? consent.scopes.join(', ') : 'None'}</td> + <td> + {grantedLabel(consent)} + {consent.client_consent_mode ? ( + <span class="data-table-sub"> + {consent.client_consent_mode} + </span> + ) : null} + </td> + <td> + {consent.active ? 'Active' : 'Revoked'} + {!consent.active ? ( + <span class="data-table-status">Revoked</span> + ) : null} + </td> + <td>{formatTime(consent.updated_at)}</td> + <td> + {consent.active ? ( + <button + class="button-secondary" + type="button" + disabled={Boolean(this.pendingAction)} + onclick={() => { + this.confirm = { + type: 'revoke', + clientId: consent.client_id, + label: consent.client_name || consent.client_id, + }; + m.redraw(); + }} + > + Revoke + </button> + ) : ( + 'None' + )} + </td> + </tr> + ))} + </tbody> + </table> + </div> + )} + </section> + + <section class="panel"> + <div class="panel-header"> + <div> + <h2>Application bans</h2> + <p class="note">Bans persist independently of consent.</p> + </div> + <button + class="button-danger" + type="button" + onclick={() => { + this.banClientId = '*'; + this.banOpen = true; + this.error = null; + m.redraw(); + }} + > + Ban from app + </button> + </div> + {detail.bans.length === 0 ? ( + <div class="empty"> + <p>This user is not banned from any app.</p> + </div> + ) : ( + <div class="data-table-wrap"> + <table class="data-table data-table-static"> + <thead> + <tr> + <th class="data-table-primary" scope="col">Application</th> + <th scope="col">Banned by</th> + <th scope="col">Created</th> + <th scope="col">Action</th> + </tr> + </thead> + <tbody> + {detail.bans.map((ban: AdminUserBan) => ( + <tr> + <td class="data-table-primary"> + <strong>{banLabel(ban)}</strong> + {ban.client_id !== '*' ? ( + <span class="data-table-sub">{ban.client_id}</span> + ) : null} + </td> + <td>{ban.created_by_username || 'Unknown'}</td> + <td>{formatTime(ban.created_at)}</td> + <td> + <button + class="button-secondary" + type="button" + disabled={Boolean(this.pendingAction)} + onclick={() => { + this.confirm = { + type: 'unban', + clientId: ban.client_id, + label: banLabel(ban), + }; + m.redraw(); + }} + > + Unban + </button> + </td> + </tr> + ))} + </tbody> + </table> + </div> + )} + </section> + </div> + ) : ( + <div class="empty"> + <p>This user is not a member of the selected realm.</p> + </div> + )} + + {this.confirm && detail ? ( + <Modal + title={this.confirm.type === 'revoke' ? 'Revoke consent' : 'Remove app ban'} + onClose={() => this.cancelAction()} + > + {this.confirm.type === 'revoke' ? ( + <p class="modal-note"> + Revoke {this.confirm.label} for {displayName}? The app must request access again. + </p> + ) : ( + <p class="modal-note"> + Remove the {this.confirm.label} ban for {displayName}? Revoked consents are not + restored automatically. + </p> + )} + <div class="modal-actions"> + <button + class="button-secondary" + type="button" + disabled={this.pendingAction} + onclick={() => this.cancelAction()} + > + Cancel + </button> + <button + class={this.confirm.type === 'revoke' ? 'button' : 'button-danger'} + type="button" + disabled={this.pendingAction} + onclick={() => this.submitAction()} + > + {this.pendingAction + ? this.confirm.type === 'revoke' ? 'Revoking' : 'Removing' + : this.confirm.type === 'revoke' ? 'Revoke consent' : 'Remove ban'} + </button> + </div> + </Modal> + ) : null} + + {this.banOpen && detail ? ( + <Modal title="Ban from app" onClose={() => this.cancelAction()}> + <div class="form-field"> + <span class="field-label">Application</span> + <select + class="field-control" + value={this.banClientId} + onchange={(event: Event) => { + this.banClientId = (event.target as HTMLSelectElement).value; + m.redraw(); + }} + > + <option value="*">All apps</option> + {this.clients.map((client: AdminClient) => ( + <option value={client.client_id}>{client.name}</option> + ))} + </select> + </div> + <p class="modal-note"> + Banning {displayName} revokes matching consents and refresh tokens. The ban remains + in force after later sign-in attempts. + </p> + <div class="modal-actions"> + <button + class="button-secondary" + type="button" + disabled={this.banPending} + onclick={() => this.cancelAction()} + > + Cancel + </button> + <button + class="button-danger" + type="button" + disabled={this.banPending} + onclick={() => this.submitBan()} + > + {this.banPending ? 'Creating ban' : 'Ban user'} + </button> + </div> + </Modal> + ) : null} + </div> + ); + }, +}; diff --git a/app/admin/src/screen/users.tsx b/app/admin/src/screen/users.tsx @@ -0,0 +1,303 @@ +import { Users } from 'lucide'; +import m from 'mithril'; +import { Icon } from '@component/icon'; +import { PageHeader } from '@component/page-header'; +import { RealmSelector } from '../component/realm-selector'; +import { loadAdminGlobalUsers, loadAdminUsers } from '../util/auth'; +import { + appUrl, + type AdminGlobalUser, + type AdminRealm, + type AdminRealmUser, +} from '../util/api'; + +interface UsersAttrs { + realmSlug: string | null; + realms: AdminRealm[] | null; + realmsError: Error | null; + onAuthExpired: () => void; + isSystemAdmin: boolean; + isGlobal: boolean; +} + +type AnyUser = AdminRealmUser | AdminGlobalUser; + +function matchesSearch(user: AnyUser, term: string) { + if (!term) return true; + const values = [user.display_name, user.username, user.email || '']; + if ('relationship' in user) values.push(user.relationship); + if ('roles' in user) values.push(user.roles.join(' ')); + if ('home_realm_slug' in user) values.push(user.home_realm_slug || ''); + return values.join(' ').toLowerCase().includes(term); +} + +function relationshipLabel(user: AdminRealmUser) { + return user.relationship === 'home' ? 'Home' : 'Guest'; +} + +function realmStatus(user: AdminRealmUser) { + if (user.status !== 'active') return user.status === 'disabled' ? 'Disabled' : user.status; + if (user.membership_status && user.membership_status !== 'active') { + return user.membership_status[0].toUpperCase() + user.membership_status.slice(1); + } + if (user.banned) return 'Banned'; + return 'Active'; +} + +function globalStatusLabel(user: AdminGlobalUser) { + if (user.status !== 'active') return user.status === 'disabled' ? 'Disabled' : user.status; + return 'Active'; +} + +function userHref(isGlobal: boolean, realmSlug: string | null, userId: string) { + const encodedUser = encodeURIComponent(userId); + if (isGlobal) return `/users/global/${encodedUser}`; + return `/users/${encodeURIComponent(realmSlug || '')}/${encodedUser}`; +} + +export const UsersPage: m.Component<UsersAttrs> = { + attrs: null as UsersAttrs | null, + loadedScope: null as string | null, + loading: false, + redirecting: false, + users: null as AnyUser[] | null, + search: '', + error: null as Error | null, + + oninit(this: any, vnode: m.Vnode<UsersAttrs>) { + this.attrs = vnode.attrs; + this.ensure(); + }, + + onupdate(this: any, vnode: m.Vnode<UsersAttrs>) { + this.attrs = vnode.attrs; + this.ensure(); + }, + + ensure(this: any) { + const { realms, realmSlug, isSystemAdmin, isGlobal } = this.attrs; + if (!realms) return; + + if (realms.length === 0 && !isGlobal) { + this.users = []; + this.loading = false; + this.error = null; + return; + } + + if (isGlobal && !isSystemAdmin) { + if (realms.length > 0) { + m.route.set(`/users/${encodeURIComponent(realms[0].slug)}`, null, { replace: true }); + } + return; + } + + const scope = isGlobal ? 'global' : realmSlug; + if (!isGlobal && !(realmSlug && realms.some((realm) => realm.slug === realmSlug))) { + if (!this.redirecting && realms.length > 0) { + this.redirecting = true; + m.route.set(`/users/${encodeURIComponent(realms[0].slug)}`, null, { replace: true }); + } + return; + } + + this.redirecting = false; + if (this.loadedScope !== scope) { + this.search = ''; + this.error = null; + this.load(scope); + } + }, + + async load(this: any, scope: string) { + this.loadedScope = scope; + this.loading = true; + this.error = null; + this.users = null; + m.redraw(); + + try { + const users = scope === 'global' ? await loadAdminGlobalUsers() : await loadAdminUsers(scope); + if (this.loadedScope === scope) this.users = users; + } catch (e: any) { + if (this.loadedScope !== scope) return; + if (e?.status === 401 || e?.status === 400) { + this.attrs.onAuthExpired(); + return; + } + this.error = e as Error; + } finally { + if (this.loadedScope === scope) this.loading = false; + m.redraw(); + } + }, + + view(this: any) { + const { realms, realmsError, isSystemAdmin, isGlobal, realmSlug } = this.attrs; + const selected = isGlobal + ? null + : realms?.find((realm) => realm.slug === realmSlug) || realms?.[0] || null; + const term = this.search.trim().toLowerCase(); + const visibleUsers = (this.users || []).filter((user: AnyUser) => matchesSearch(user, term)); + + return ( + <div> + <PageHeader + row + title="Users" + subtitle={isGlobal ? 'All global user identities.' : 'Home and guest members in this realm.'} + > + <RealmSelector + realms={realms} + selected={selected} + allRealms={isSystemAdmin} + selectedAll={isGlobal} + onchange={(slug: string) => { + this.search = ''; + this.error = null; + m.route.set(slug === 'global' ? '/users/global' : `/users/${encodeURIComponent(slug)}`); + }} + /> + </PageHeader> + + {realmsError ? ( + <div class="alert" role="alert"> + {realmsError.message} + </div> + ) : null} + + {this.error ? ( + <div class="alert" role="alert"> + <p>{this.error.message}</p> + <button class="button-secondary" type="button" onclick={() => this.load(this.loadedScope)}> + Try again + </button> + </div> + ) : null} + + {!realms ? ( + <div class="loading">Loading realms</div> + ) : !isGlobal && realms.length === 0 ? ( + <div class="empty"> + <p>No realms are available for this account.</p> + </div> + ) : ( + <div class="table-panel"> + <div class="table-toolbar"> + <div class="table-search"> + <input + type="search" + value={this.search} + aria-label="Search users" + placeholder="Search users" + oninput={(event: Event) => { + this.search = (event.target as HTMLInputElement).value; + }} + /> + </div> + </div> + + {this.loading || this.redirecting || !this.users ? ( + <div class="panel" aria-busy="true"> + <div class="skeleton skeleton-title"></div> + <div class="skeleton"></div> + <div class="skeleton skeleton-short"></div> + <div class="skeleton"></div> + <div class="skeleton skeleton-short"></div> + </div> + ) : this.users.length === 0 ? ( + <div class="empty"> + <p>{isGlobal ? 'No users exist yet.' : 'No users are members of this realm.'}</p> + </div> + ) : ( + <div class="data-table-wrap"> + <table class="data-table"> + <thead> + <tr> + <th class="table-icon-column" scope="col"> + <span class="sr-only">User</span> + </th> + <th class="data-table-primary" scope="col">User</th> + <th scope="col">{isGlobal ? 'Home realm' : 'Membership'}</th> + {isGlobal ? <th scope="col">Realms</th> : null} + <th scope="col">Status</th> + </tr> + </thead> + <tbody> + {visibleUsers.map((user: AnyUser) => { + const href = userHref(isGlobal, realmSlug, user.id); + return ( + <tr + tabindex="0" + onclick={() => m.route.set(href)} + onkeydown={(event: KeyboardEvent) => { + if (event.target !== event.currentTarget) return; + if (event.key !== 'Enter' && event.key !== ' ') return; + event.preventDefault(); + m.route.set(href); + }} + > + <td> + <span class="table-icon" aria-hidden="true"> + Icon(Users) + </span> + </td> + <td class="data-table-primary"> + <a + class="user-title" + href={appUrl(href)} + onclick={(event: MouseEvent) => { + event.preventDefault(); + event.stopPropagation(); + m.route.set(href); + }} + > + <strong>{user.display_name || user.username}</strong> + </a> + <span class="data-table-sub">{user.email || user.username}</span> + {user.email ? <span class="data-table-sub">{user.username}</span> : null} + </td> + {isGlobal ? ( + <td> + {(user as AdminGlobalUser).home_realm_slug || 'None'} + {(user as AdminGlobalUser).is_system_admin ? ( + <span class="data-table-status">System admin</span> + ) : null} + </td> + ) : ( + <td> + {relationshipLabel(user as AdminRealmUser)} + {(user as AdminRealmUser).roles.includes('realm-admin') ? ( + <span class="data-table-status">Realm admin</span> + ) : null} + {(user as AdminRealmUser).is_system_admin ? ( + <span class="data-table-status">System admin</span> + ) : null} + </td> + )} + {isGlobal ? ( + <td>{(user as AdminGlobalUser).membership_count}</td> + ) : null} + <td> + {isGlobal + ? globalStatusLabel(user as AdminGlobalUser) + : realmStatus(user as AdminRealmUser)} + </td> + </tr> + ); + })} + </tbody> + </table> + {visibleUsers.length === 0 ? ( + <div class="empty"> + <p>No users match this search.</p> + </div> + ) : null} + </div> + )} + </div> + )} + </div> + ); + }, +}; diff --git a/app/admin/src/util/api.ts b/app/admin/src/util/api.ts @@ -63,6 +63,110 @@ export interface AdminClientSecretResponse { client_secret: string; } +export interface AdminRealmUser { + id: string; + username: string; + display_name: string; + email: string | null; + status: string; + membership_status: string | null; + relationship: 'home' | 'guest'; + roles: string[]; + is_system_admin: boolean; + banned: boolean; + ban_count: number; + last_login_at: number | null; + created_at: number; +} + +export interface AdminUserConsent { + client_id: string; + client_name: string | null; + client_consent_mode: string | null; + scopes: string[]; + granted_via: 'user' | 'trusted' | string; + created_at: number; + updated_at: number; + revoked_at: number | null; + active: boolean; +} + +export interface AdminUserBan { + client_id: string; + client_name: string | null; + created_by: string | null; + created_by_username: string | null; + created_at: number; +} + +export interface AdminUserDetail { + user: { + id: string; + username: string; + display_name: string; + email: string | null; + status: string; + membership_status: string | null; + relationship: 'home' | 'guest'; + roles: string[]; + is_system_admin: boolean; + banned: boolean; + ban_count: number; + home_realm_id: string | null; + last_login_at: number | null; + created_at: number; + updated_at: number; + }; + consents: AdminUserConsent[]; + bans: AdminUserBan[]; +} + +export interface AdminMeUser { + id: string; + username: string; + display_name: string; + email: string | null; + is_system_admin: boolean; +} + +export interface AdminGlobalUser { + id: string; + username: string; + display_name: string; + email: string | null; + status: string; + is_system_admin: boolean; + home_realm_slug: string | null; + membership_count: number; + last_login_at: number | null; + created_at: number; +} + +export interface AdminGlobalUserMembership { + slug: string; + display_name: string; + relationship: 'home' | 'guest'; + membership_status: string; + roles: string[]; + banned: boolean; +} + +export interface AdminGlobalUserDetail { + user: { + id: string; + username: string; + display_name: string; + email: string | null; + status: string; + is_system_admin: boolean; + home_realm_slug: string | null; + last_login_at: number | null; + created_at: number; + updated_at: number; + }; + memberships: AdminGlobalUserMembership[]; +} + export interface AdminSession { public_id: string; user: { diff --git a/app/admin/src/util/auth.ts b/app/admin/src/util/auth.ts @@ -9,9 +9,15 @@ import { type AdminClientInput, type AdminClientResponse, type AdminClientSecretResponse, + type AdminGlobalUser, + type AdminGlobalUserDetail, + type AdminMeUser, type AdminRealm, + type AdminRealmUser, type AdminRole, type AdminSession, + type AdminUserBan, + type AdminUserDetail, } from './api'; export type AdminTokens = StoredTokens; @@ -46,6 +52,11 @@ async function adminJson<T>(path: string, init: RequestInit = {}): Promise<T> { return parseJsonResponse<T>(response); } +export async function loadAdminMe(): Promise<AdminMeUser> { + const response = await adminJson<{ user: AdminMeUser }>('/api/v1/admin/me'); + return response.user; +} + export async function loadAdminRealms(): Promise<AdminRealm[]> { const response = await adminJson<{ realms: AdminRealm[] }>('/api/v1/admin/realms'); return response.realms; @@ -140,3 +151,72 @@ export async function rotateAdminClientSecret( } ); } + +export async function loadAdminUsers(realmSlug: string): Promise<AdminRealmUser[]> { + const realm = encodeURIComponent(realmSlug); + const response = await adminJson<{ users: AdminRealmUser[] }>( + `/api/v1/admin/realms/${realm}/users` + ); + return response.users; +} + +export async function loadAdminGlobalUsers(): Promise<AdminGlobalUser[]> { + const response = await adminJson<{ users: AdminGlobalUser[] }>('/api/v1/admin/users'); + return response.users; +} + +export async function loadAdminGlobalUser(userId: string): Promise<AdminGlobalUserDetail> { + const user = encodeURIComponent(userId); + return adminJson<AdminGlobalUserDetail>(`/api/v1/admin/users/${user}`); +} + +export async function loadAdminUserDetail( + realmSlug: string, + userId: string +): Promise<AdminUserDetail> { + const realm = encodeURIComponent(realmSlug); + const user = encodeURIComponent(userId); + return adminJson<AdminUserDetail>(`/api/v1/admin/realms/${realm}/users/${user}`); +} + +export async function revokeAdminUserConsent( + realmSlug: string, + userId: string, + clientId: string +) { + const realm = encodeURIComponent(realmSlug); + const user = encodeURIComponent(userId); + const client = encodeURIComponent(clientId); + return adminJson(`/api/v1/admin/realms/${realm}/users/${user}/consents/${client}`, { + method: 'DELETE', + }); +} + +export async function createAdminUserBan( + realmSlug: string, + userId: string, + clientId: string +): Promise<{ ok: boolean; ban: AdminUserBan }> { + const realm = encodeURIComponent(realmSlug); + const user = encodeURIComponent(userId); + return adminJson<{ ok: boolean; ban: AdminUserBan }>( + `/api/v1/admin/realms/${realm}/users/${user}/bans`, + { + method: 'POST', + body: JSON.stringify({ client_id: clientId }), + } + ); +} + +export async function deleteAdminUserBan( + realmSlug: string, + userId: string, + clientId: string +) { + const realm = encodeURIComponent(realmSlug); + const user = encodeURIComponent(userId); + const client = encodeURIComponent(clientId); + return adminJson(`/api/v1/admin/realms/${realm}/users/${user}/bans/${client}`, { + method: 'DELETE', + }); +} diff --git a/app/shared/style/global.css b/app/shared/style/global.css @@ -20,6 +20,7 @@ --row-hover: #0000000d; --skeleton: #00000012; --danger: #c9190b; + --danger-text: #c9190b; --field-line: rgba(0, 0, 0, 0.42); --shadow: 0 0.125em 0.25em #0008; --hex: url('./assets/hex-grid-light.svg'); @@ -253,6 +254,22 @@ textarea { line-height: 1.6; } +.panel-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 1rem; + margin-bottom: 1rem; +} + +.panel-header h2 { + margin: 0; +} + +.panel-header .note { + margin-top: 0.25rem; +} + .button, .button-secondary, .button-danger { @@ -315,7 +332,7 @@ textarea { .alert { margin: 0 0 1rem; - color: var(--danger); + color: var(--danger-text); font-size: 0.875rem; line-height: 1.5; } @@ -532,7 +549,7 @@ textarea { .status-error { margin: 0; - color: var(--danger); + color: var(--danger-text); font-size: 0.875rem; line-height: 1.6; } @@ -640,6 +657,12 @@ textarea { outline-offset: -2pt; } +.data-table-static tbody tr, +.data-table-static tbody tr:hover { + cursor: default; + background: transparent; +} + .data-table tbody tr:last-child td { border-bottom: 0; } @@ -857,7 +880,7 @@ select:focus-visible { --row: #ffffff0d; --row-hover: #ffffff14; --skeleton: #ffffff14; - --danger: #f28b82; + --danger-text: #f28b82; --field-line: rgba(255, 255, 255, 0.42); --hex: url('./assets/hex-grid-dark.svg'); color-scheme: dark; @@ -883,7 +906,7 @@ select:focus-visible { --row: #ffffff0d; --row-hover: #ffffff14; --skeleton: #ffffff14; - --danger: #f28b82; + --danger-text: #f28b82; --field-line: rgba(255, 255, 255, 0.42); --hex: url('./assets/hex-grid-dark.svg'); color-scheme: dark; diff --git a/mockup/plain/admin-client-detail.html b/mockup/plain/admin-client-detail.html @@ -99,7 +99,7 @@ </svg> <span>Realms</span> </a> - <a class="nav-item" href="#"> + <a class="nav-item" href="./admin-users.html"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" /> <circle cx="12" cy="7" r="4" /> diff --git a/mockup/plain/admin-clients.html b/mockup/plain/admin-clients.html @@ -99,7 +99,7 @@ </svg> <span>Realms</span> </a> - <a class="nav-item" href="#"> + <a class="nav-item" href="./admin-users.html"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" /> <circle cx="12" cy="7" r="4" /> diff --git a/mockup/plain/admin-dashboard.html b/mockup/plain/admin-dashboard.html @@ -134,7 +134,7 @@ </svg> <span>Realms</span> </a> - <a class="nav-item" href="#"> + <a class="nav-item" href="./admin-users.html"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" /> <circle cx="12" cy="7" r="4" /> diff --git a/mockup/plain/admin-user-detail.html b/mockup/plain/admin-user-detail.html @@ -0,0 +1,451 @@ +<!doctype html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1" /> + <title>Admin user detail mockup</title> + <link rel="stylesheet" href="./global.css" /> + </head> + <body> + <header class="topbar"> + <a class="brand" href="./admin-dashboard.html"> + <svg class="brand-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" /> + </svg> + <span class="brand-name">Auth</span> + </a> + <details class="user-menu"> + <summary aria-label="Account menu"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <circle cx="12" cy="12" r="10" /> + <circle cx="12" cy="10" r="3" /> + <path d="M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662" /> + </svg> + </summary> + <div class="user-panel"> + <div class="user-summary"> + <span class="user-name">Acme IT</span> + <span class="user-meta">it@acme.test</span> + </div> + <div class="user-menu-list"> + <a class="user-menu-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" /> + <circle cx="12" cy="12" r="3" /> + </svg> + <span>Account settings</span> + </a> + <button class="user-menu-item" type="button" data-user-theme> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <circle cx="12" cy="12" r="4" /> + <path d="M12 2v2" /> + <path d="M12 20v2" /> + <path d="m4.93 4.93 1.41 1.41" /> + <path d="m17.66 17.66 1.41 1.41" /> + <path d="M2 12h2" /> + <path d="M20 12h2" /> + <path d="m6.34 17.66-1.41 1.41" /> + <path d="m19.07 4.93-1.41 1.41" /> + </svg> + <span>Theme</span> + <span class="user-menu-value" data-user-theme-value>Auto</span> + </button> + <a class="user-menu-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" /> + <path d="m16 17 5-5-5-5" /> + <path d="M21 12H9" /> + </svg> + <span>Sign out</span> + </a> + </div> + </div> + </details> + </header> + + <div class="app"> + <aside class="sidebar"> + <nav class="nav" aria-label="Administration"> + <p class="nav-label">Administration</p> + <a class="nav-item" href="./admin-dashboard.html"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <rect x="3" y="3" width="7" height="7" /> + <rect x="14" y="3" width="7" height="7" /> + <rect x="3" y="14" width="7" height="7" /> + <rect x="14" y="14" width="7" height="7" /> + </svg> + <span>Overview</span> + </a> + <a class="nav-item" href="./admin-clients.html"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <rect x="2" y="4" width="20" height="16" rx="2" /> + <path d="M10 4v4" /> + <path d="M2 8h20" /> + <path d="M6 4v4" /> + </svg> + <span>Clients</span> + </a> + <a class="nav-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M22 12h-4l-3 8-6-16-3 8H2" /> + </svg> + <span>Sessions</span> + </a> + <a class="nav-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <circle cx="12" cy="12" r="9" /> + <path d="M3 12h18" /> + <path d="M12 3a15 15 0 0 1 0 18a15 15 0 0 1 0-18" /> + </svg> + <span>Realms</span> + </a> + <a class="nav-item is-active" href="./admin-users.html" aria-current="page"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" /> + <circle cx="12" cy="7" r="4" /> + </svg> + <span>Users</span> + </a> + </nav> + </aside> + + <div class="main"> + <main class="content"> + <div class="page-header page-header-row"> + <div> + <div class="client-breadcrumb"> + <a href="./admin-users.html">Users</a> + <span aria-hidden="true">/</span> + <span>Alice</span> + </div> + <h1>Alice</h1> + <p>alice@acme.test</p> + </div> + <label class="realm-select"> + <span>Realm</span> + <select> + <option selected>Acme</option> + <option>Globex</option> + </select> + </label> + </div> + + <div class="client-stack"> + <section class="panel"> + <h2>Account</h2> + <dl class="details"> + <div> + <dt>Display name</dt> + <dd>Alice</dd> + </div> + <div> + <dt>Username</dt> + <dd>alice</dd> + </div> + <div> + <dt>Email</dt> + <dd>alice@acme.test</dd> + </div> + <div> + <dt>Realm membership</dt> + <dd>Home realm</dd> + </div> + <div> + <dt>Status</dt> + <dd>Banned</dd> + </div> + <div> + <dt>Roles</dt> + <dd>None</dd> + </div> + <div> + <dt>System admin</dt> + <dd>No</dd> + </div> + <div> + <dt>Last login</dt> + <dd>2026-10-25 10:14</dd> + </div> + </dl> + </section> + + <section class="panel"> + <div class="panel-header"> + <h2>Application consents</h2> + </div> + <div class="data-table-wrap"> + <table class="data-table data-table-static"> + <thead> + <tr> + <th class="data-table-primary" scope="col">Application</th> + <th scope="col">Scopes</th> + <th scope="col">Granted</th> + <th scope="col">Status</th> + <th scope="col">Updated</th> + <th scope="col">Action</th> + </tr> + </thead> + <tbody> + <tr> + <td class="data-table-primary"> + <strong>Internal App</strong> + <span class="data-table-sub">internal-app</span> + </td> + <td>openid, profile, email</td> + <td> + User consent + <span class="data-table-sub">remembered</span> + </td> + <td>Active</td> + <td>2026-10-24 16:02</td> + <td> + <button class="button-secondary" type="button" data-dialog-open="consent-revoke-dialog">Revoke</button> + </td> + </tr> + <tr> + <td class="data-table-primary"> + <strong>Secure Service</strong> + <span class="data-table-sub">secure-app</span> + </td> + <td>None</td> + <td> + User consent + <span class="data-table-sub">remembered</span> + </td> + <td> + Revoked + <span class="data-table-status">Revoked</span> + </td> + <td>2026-10-25 09:18</td> + <td>None</td> + </tr> + </tbody> + </table> + </div> + </section> + + <section class="panel"> + <div class="panel-header"> + <div> + <h2>Application bans</h2> + <p class="note">Bans persist independently of consent.</p> + </div> + <button class="button-danger" type="button" data-dialog-open="user-ban-dialog">Ban from app</button> + </div> + <div class="data-table-wrap"> + <table class="data-table data-table-static"> + <thead> + <tr> + <th class="data-table-primary" scope="col">Application</th> + <th scope="col">Banned by</th> + <th scope="col">Created</th> + <th scope="col">Action</th> + </tr> + </thead> + <tbody> + <tr> + <td class="data-table-primary"> + <strong>All apps</strong> + </td> + <td>acme-it</td> + <td>2026-10-25 09:18</td> + <td> + <button class="button-secondary" type="button" data-dialog-open="all-apps-unban-dialog">Unban</button> + </td> + </tr> + <tr> + <td class="data-table-primary"> + <strong>Internal App</strong> + <span class="data-table-sub">internal-app</span> + </td> + <td>acme-it</td> + <td>2026-10-25 09:20</td> + <td> + <button class="button-secondary" type="button" data-dialog-open="app-unban-dialog">Unban</button> + </td> + </tr> + </tbody> + </table> + </div> + </section> + </div> + </main> + </div> + </div> + + <div id="user-ban-dialog" class="modal-overlay" hidden> + <div class="modal" role="dialog" aria-modal="true" aria-labelledby="user-ban-title"> + <div class="modal-header"> + <h2 id="user-ban-title">Ban from app</h2> + <button class="modal-close" type="button" aria-label="Close dialog" data-dialog-close> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M18 6 6 18" /> + <path d="m6 6 12 12" /> + </svg> + </button> + </div> + <div class="modal-body"> + <label class="form-field"> + <span class="field-label">Application</span> + <select class="field-control"> + <option selected>All apps</option> + <option>Internal App</option> + <option>Members Portal</option> + <option>Secure Service</option> + </select> + </label> + <p class="modal-note"> + Banning Alice revokes matching consents and refresh tokens. The ban remains in force + after later sign-in attempts. + </p> + <div class="modal-actions"> + <button class="button-secondary" type="button" data-dialog-close>Cancel</button> + <button class="button-danger" type="button" data-dialog-close>Ban user</button> + </div> + </div> + </div> + </div> + + <div id="consent-revoke-dialog" class="modal-overlay" hidden> + <div class="modal" role="dialog" aria-modal="true" aria-labelledby="consent-revoke-title"> + <div class="modal-header"> + <h2 id="consent-revoke-title">Revoke consent</h2> + <button class="modal-close" type="button" aria-label="Close dialog" data-dialog-close> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M18 6 6 18" /> + <path d="m6 6 12 12" /> + </svg> + </button> + </div> + <div class="modal-body"> + <p class="modal-note">Revoke Internal App for Alice? The app must request access again.</p> + <div class="modal-actions"> + <button class="button-secondary" type="button" data-dialog-close>Cancel</button> + <button class="button" type="button" data-dialog-close>Revoke consent</button> + </div> + </div> + </div> + </div> + + <div id="app-unban-dialog" class="modal-overlay" hidden> + <div class="modal" role="dialog" aria-modal="true" aria-labelledby="app-unban-title"> + <div class="modal-header"> + <h2 id="app-unban-title">Remove app ban</h2> + <button class="modal-close" type="button" aria-label="Close dialog" data-dialog-close> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M18 6 6 18" /> + <path d="m6 6 12 12" /> + </svg> + </button> + </div> + <div class="modal-body"> + <p class="modal-note">Remove the Internal App ban for Alice? Revoked consents are not restored automatically.</p> + <div class="modal-actions"> + <button class="button-secondary" type="button" data-dialog-close>Cancel</button> + <button class="button-danger" type="button" data-dialog-close>Remove ban</button> + </div> + </div> + </div> + </div> + + <div id="all-apps-unban-dialog" class="modal-overlay" hidden> + <div class="modal" role="dialog" aria-modal="true" aria-labelledby="all-apps-unban-title"> + <div class="modal-header"> + <h2 id="all-apps-unban-title">Remove app ban</h2> + <button class="modal-close" type="button" aria-label="Close dialog" data-dialog-close> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M18 6 6 18" /> + <path d="m6 6 12 12" /> + </svg> + </button> + </div> + <div class="modal-body"> + <p class="modal-note">Remove the All apps ban for Alice? Exact app bans remain in force.</p> + <div class="modal-actions"> + <button class="button-secondary" type="button" data-dialog-close>Cancel</button> + <button class="button-danger" type="button" data-dialog-close>Remove ban</button> + </div> + </div> + </div> + </div> + + <div class="mockup-controls" aria-label="Mockup theme"> + <span class="mockup-label">Mockup</span> + <button class="mockup-button is-active" type="button" data-theme-target="auto">Auto</button> + <button class="mockup-button" type="button" data-theme-target="light">Light</button> + <button class="mockup-button" type="button" data-theme-target="dark">Dark</button> + </div> + + <script> + const root = document.documentElement; + const themeButtons = document.querySelectorAll('[data-theme-target]'); + const userThemeButton = document.querySelector('[data-user-theme]'); + const userThemeValue = document.querySelector('[data-user-theme-value]'); + let currentTheme = 'auto'; + + function setTheme(value) { + currentTheme = value; + if (value === 'auto') { + root.removeAttribute('data-theme'); + } else { + root.setAttribute('data-theme', value); + } + themeButtons.forEach((button) => { + button.classList.toggle('is-active', button.dataset.themeTarget === value); + }); + if (userThemeValue) { + userThemeValue.textContent = value.charAt(0).toUpperCase() + value.slice(1); + } + } + + themeButtons.forEach((button) => { + button.addEventListener('click', () => setTheme(button.dataset.themeTarget)); + }); + + userThemeButton?.addEventListener('click', () => { + const themes = ['auto', 'light', 'dark']; + setTheme(themes[(themes.indexOf(currentTheme) + 1) % themes.length]); + }); + + const userMenu = document.querySelector('.user-menu'); + document.addEventListener('click', (event) => { + if (userMenu && userMenu.open && !userMenu.contains(event.target)) { + userMenu.open = false; + } + }); + + function visibleDialogs() { + return [...document.querySelectorAll('.modal-overlay:not([hidden])')]; + } + + document.querySelectorAll('[data-dialog-open]').forEach((button) => { + button.addEventListener('click', () => { + const dialog = document.getElementById(button.dataset.dialogOpen); + if (!dialog) return; + dialog.hidden = false; + dialog.querySelector('.modal-close')?.focus(); + }); + }); + + document.querySelectorAll('[data-dialog-close]').forEach((button) => { + button.addEventListener('click', () => { + button.closest('.modal-overlay').hidden = true; + }); + }); + + document.querySelectorAll('.modal-overlay').forEach((overlay) => { + overlay.addEventListener('mousedown', (event) => { + if (event.target === overlay) overlay.hidden = true; + }); + }); + + document.addEventListener('keydown', (event) => { + if (event.key === 'Escape') { + visibleDialogs().forEach((dialog) => { + dialog.hidden = true; + }); + } + }); + </script> + </body> +</html> diff --git a/mockup/plain/admin-user-global-detail.html b/mockup/plain/admin-user-global-detail.html @@ -0,0 +1,266 @@ +<!doctype html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1" /> + <title>Admin global user detail mockup</title> + <link rel="stylesheet" href="./global.css" /> + </head> + <body> + <header class="topbar"> + <a class="brand" href="./admin-dashboard.html"> + <svg class="brand-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" /> + </svg> + <span class="brand-name">Auth</span> + </a> + <details class="user-menu"> + <summary aria-label="Account menu"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <circle cx="12" cy="12" r="10" /> + <circle cx="12" cy="10" r="3" /> + <path d="M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662" /> + </svg> + </summary> + <div class="user-panel"> + <div class="user-summary"> + <span class="user-name">System Admin</span> + <span class="user-meta">admin@system.test</span> + </div> + <div class="user-menu-list"> + <a class="user-menu-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" /> + <circle cx="12" cy="12" r="3" /> + </svg> + <span>Account settings</span> + </a> + <button class="user-menu-item" type="button" data-user-theme> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <circle cx="12" cy="12" r="4" /> + <path d="M12 2v2" /> + <path d="M12 20v2" /> + <path d="m4.93 4.93 1.41 1.41" /> + <path d="m17.66 17.66 1.41 1.41" /> + <path d="M2 12h2" /> + <path d="M20 12h2" /> + <path d="m6.34 17.66-1.41 1.41" /> + <path d="m19.07 4.93-1.41 1.41" /> + </svg> + <span>Theme</span> + <span class="user-menu-value" data-user-theme-value>Auto</span> + </button> + <a class="user-menu-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" /> + <path d="m16 17 5-5-5-5" /> + <path d="M21 12H9" /> + </svg> + <span>Sign out</span> + </a> + </div> + </div> + </details> + </header> + + <div class="app"> + <aside class="sidebar"> + <nav class="nav" aria-label="Administration"> + <p class="nav-label">Administration</p> + <a class="nav-item" href="./admin-dashboard.html"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <rect x="3" y="3" width="7" height="7" /> + <rect x="14" y="3" width="7" height="7" /> + <rect x="3" y="14" width="7" height="7" /> + <rect x="14" y="14" width="7" height="7" /> + </svg> + <span>Overview</span> + </a> + <a class="nav-item" href="./admin-clients.html"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <rect x="2" y="4" width="20" height="16" rx="2" /> + <path d="M10 4v4" /> + <path d="M2 8h20" /> + <path d="M6 4v4" /> + </svg> + <span>Clients</span> + </a> + <a class="nav-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M22 12h-4l-3 8-6-16-3 8H2" /> + </svg> + <span>Sessions</span> + </a> + <a class="nav-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <circle cx="12" cy="12" r="9" /> + <path d="M3 12h18" /> + <path d="M12 3a15 15 0 0 1 0 18a15 15 0 0 1 0-18" /> + </svg> + <span>Realms</span> + </a> + <a class="nav-item is-active" href="./admin-users.html" aria-current="page"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" /> + <circle cx="12" cy="7" r="4" /> + </svg> + <span>Users</span> + </a> + </nav> + </aside> + + <div class="main"> + <main class="content"> + <div class="page-header page-header-row"> + <div> + <div class="client-breadcrumb"> + <a href="./admin-users.html">Users</a> + <span aria-hidden="true">/</span> + <span>Alice</span> + </div> + <h1>Alice</h1> + <p>alice@acme.test</p> + </div> + <a class="button-secondary" href="./admin-users.html">All realms</a> + </div> + + <div class="client-stack"> + <section class="panel"> + <div class="panel-header"> + <h2>Account</h2> + </div> + <dl class="details"> + <div> + <dt>Display name</dt> + <dd>Alice</dd> + </div> + <div> + <dt>Username</dt> + <dd>alice</dd> + </div> + <div> + <dt>Email</dt> + <dd>alice@acme.test</dd> + </div> + <div> + <dt>Home realm</dt> + <dd>acme</dd> + </div> + <div> + <dt>Status</dt> + <dd>Active</dd> + </div> + <div> + <dt>System admin</dt> + <dd>No</dd> + </div> + <div> + <dt>Last login</dt> + <dd>2026-10-25 10:14</dd> + </div> + <div> + <dt>Created</dt> + <dd>2026-10-20 09:00</dd> + </div> + </dl> + </section> + + <section class="panel"> + <div class="panel-header"> + <div> + <h2>Realm memberships</h2> + <p class="note">App access is managed in the realm where the user is a member.</p> + </div> + </div> + <div class="data-table-wrap"> + <table class="data-table data-table-static"> + <thead> + <tr> + <th class="data-table-primary" scope="col">Realm</th> + <th scope="col">Relationship</th> + <th scope="col">Membership</th> + <th scope="col">Roles</th> + <th scope="col">Action</th> + </tr> + </thead> + <tbody> + <tr> + <td class="data-table-primary"> + <strong>Acme</strong> + <span class="data-table-sub">acme</span> + </td> + <td>Home</td> + <td>active</td> + <td>None</td> + <td> + <a class="button-secondary" href="./admin-user-detail.html">Manage access</a> + </td> + </tr> + <tr> + <td class="data-table-primary"> + <strong>Globex</strong> + <span class="data-table-sub">globex</span> + </td> + <td>Guest</td> + <td>active</td> + <td>None</td> + <td> + <a class="button-secondary" href="./admin-user-detail.html">Manage access</a> + </td> + </tr> + </tbody> + </table> + </div> + </section> + </div> + </main> + </div> + </div> + + <div class="mockup-controls" aria-label="Mockup theme"> + <span class="mockup-label">Mockup</span> + <button class="mockup-button is-active" type="button" data-theme-target="auto">Auto</button> + <button class="mockup-button" type="button" data-theme-target="light">Light</button> + <button class="mockup-button" type="button" data-theme-target="dark">Dark</button> + </div> + + <script> + const root = document.documentElement; + const themeButtons = document.querySelectorAll('[data-theme-target]'); + const userThemeButton = document.querySelector('[data-user-theme]'); + const userThemeValue = document.querySelector('[data-user-theme-value]'); + let currentTheme = 'auto'; + + function setTheme(value) { + currentTheme = value; + if (value === 'auto') { + root.removeAttribute('data-theme'); + } else { + root.setAttribute('data-theme', value); + } + themeButtons.forEach((button) => { + button.classList.toggle('is-active', button.dataset.themeTarget === value); + }); + if (userThemeValue) { + userThemeValue.textContent = value.charAt(0).toUpperCase() + value.slice(1); + } + } + + themeButtons.forEach((button) => { + button.addEventListener('click', () => setTheme(button.dataset.themeTarget)); + }); + + userThemeButton?.addEventListener('click', () => { + const themes = ['auto', 'light', 'dark']; + setTheme(themes[(themes.indexOf(currentTheme) + 1) % themes.length]); + }); + + const userMenu = document.querySelector('.user-menu'); + document.addEventListener('click', (event) => { + if (userMenu && userMenu.open && !userMenu.contains(event.target)) { + userMenu.open = false; + } + }); + </script> + </body> +</html> diff --git a/mockup/plain/admin-users.html b/mockup/plain/admin-users.html @@ -0,0 +1,315 @@ +<!doctype html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1" /> + <title>Admin users mockup</title> + <link rel="stylesheet" href="./global.css" /> + </head> + <body> + <header class="topbar"> + <a class="brand" href="./admin-dashboard.html"> + <svg class="brand-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" /> + </svg> + <span class="brand-name">Auth</span> + </a> + <details class="user-menu"> + <summary aria-label="Account menu"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <circle cx="12" cy="12" r="10" /> + <circle cx="12" cy="10" r="3" /> + <path d="M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662" /> + </svg> + </summary> + <div class="user-panel"> + <div class="user-summary"> + <span class="user-name">System Admin</span> + <span class="user-meta">admin@system.test</span> + </div> + <div class="user-menu-list"> + <a class="user-menu-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" /> + <circle cx="12" cy="12" r="3" /> + </svg> + <span>Account settings</span> + </a> + <button class="user-menu-item" type="button" data-user-theme> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <circle cx="12" cy="12" r="4" /> + <path d="M12 2v2" /> + <path d="M12 20v2" /> + <path d="m4.93 4.93 1.41 1.41" /> + <path d="m17.66 17.66 1.41 1.41" /> + <path d="M2 12h2" /> + <path d="M20 12h2" /> + <path d="m6.34 17.66-1.41 1.41" /> + <path d="m19.07 4.93-1.41 1.41" /> + </svg> + <span>Theme</span> + <span class="user-menu-value" data-user-theme-value>Auto</span> + </button> + <a class="user-menu-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" /> + <path d="m16 17 5-5-5-5" /> + <path d="M21 12H9" /> + </svg> + <span>Sign out</span> + </a> + </div> + </div> + </details> + </header> + + <div class="app"> + <aside class="sidebar"> + <nav class="nav" aria-label="Administration"> + <p class="nav-label">Administration</p> + <a class="nav-item" href="./admin-dashboard.html"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <rect x="3" y="3" width="7" height="7" /> + <rect x="14" y="3" width="7" height="7" /> + <rect x="3" y="14" width="7" height="7" /> + <rect x="14" y="14" width="7" height="7" /> + </svg> + <span>Overview</span> + </a> + <a class="nav-item" href="./admin-clients.html"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <rect x="2" y="4" width="20" height="16" rx="2" /> + <path d="M10 4v4" /> + <path d="M2 8h20" /> + <path d="M6 4v4" /> + </svg> + <span>Clients</span> + </a> + <a class="nav-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M22 12h-4l-3 8-6-16-3 8H2" /> + </svg> + <span>Sessions</span> + </a> + <a class="nav-item" href="#"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <circle cx="12" cy="12" r="9" /> + <path d="M3 12h18" /> + <path d="M12 3a15 15 0 0 1 0 18a15 15 0 0 1 0-18" /> + </svg> + <span>Realms</span> + </a> + <a class="nav-item is-active" href="./admin-users.html" aria-current="page"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" /> + <circle cx="12" cy="7" r="4" /> + </svg> + <span>Users</span> + </a> + </nav> + </aside> + + <div class="main"> + <main class="content"> + <div class="page-header page-header-row"> + <div> + <h1>Users</h1> + <p>All global user identities.</p> + </div> + <label class="realm-select"> + <span>Realm</span> + <select class="field-control"> + <option selected>All realms</option> + <option>Acme</option> + <option>Globex</option> + </select> + </label> + </div> + + <section class="table-panel" aria-labelledby="user-table-title"> + <h2 id="user-table-title" class="sr-only">Realm users</h2> + <div class="table-toolbar"> + <div class="table-search"> + <input id="user-search" type="search" aria-label="Search users" placeholder="Search users" /> + </div> + </div> + + <div class="data-table-wrap"> + <table class="data-table"> + <thead> + <tr> + <th class="table-icon-column" scope="col"><span class="sr-only">User</span></th> + <th class="data-table-primary" scope="col">User</th> + <th scope="col">Home realm</th> + <th scope="col">Realms</th> + <th scope="col">Status</th> + </tr> + </thead> + <tbody id="user-rows"> + <tr data-row-href="./admin-user-global-detail.html" data-search="alice alice alice@acme.test acme 2 active"> + <td> + <span class="table-icon" aria-hidden="true"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> + <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" /> + <circle cx="12" cy="7" r="4" /> + </svg> + </span> + </td> + <td class="data-table-primary"> + <a href="./admin-user-global-detail.html">Alice</a> + <span class="data-table-sub">alice@acme.test</span> + <span class="data-table-sub">alice</span> + </td> + <td>acme</td> + <td>2</td> + <td>Active</td> + </tr> + <tr data-row-href="./admin-user-global-detail.html" data-search="acme it acme-it it@acme.test acme 1 realm-admin active"> + <td> + <span class="table-icon" aria-hidden="true"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> + <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" /> + <circle cx="12" cy="7" r="4" /> + </svg> + </span> + </td> + <td class="data-table-primary"> + <a href="./admin-user-global-detail.html">Acme IT</a> + <span class="data-table-sub">it@acme.test</span> + <span class="data-table-sub">acme-it</span> + </td> + <td>acme <span class="data-table-status">Realm admin</span></td> + <td>1</td> + <td>Active</td> + </tr> + <tr data-row-href="./admin-user-global-detail.html" data-search="guest user guest guest@personal.test none 1 active"> + <td> + <span class="table-icon" aria-hidden="true"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> + <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" /> + <circle cx="12" cy="7" r="4" /> + </svg> + </span> + </td> + <td class="data-table-primary"> + <a href="./admin-user-global-detail.html">Guest User</a> + <span class="data-table-sub">guest@personal.test</span> + <span class="data-table-sub">guest</span> + </td> + <td>None</td> + <td>1</td> + <td>Active</td> + </tr> + <tr data-row-href="./admin-user-global-detail.html" data-search="contractor contractor contractor@personal.test none 1 realm-admin active"> + <td> + <span class="table-icon" aria-hidden="true"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> + <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" /> + <circle cx="12" cy="7" r="4" /> + </svg> + </span> + </td> + <td class="data-table-primary"> + <a href="./admin-user-global-detail.html">Contractor</a> + <span class="data-table-sub">contractor@personal.test</span> + <span class="data-table-sub">contractor</span> + </td> + <td>None <span class="data-table-status">Realm admin</span></td> + <td>1</td> + <td>Active</td> + </tr> + <tr data-row-href="./admin-user-global-detail.html" data-search="system admin admin admin@system.test none 0 system-admin active"> + <td> + <span class="table-icon" aria-hidden="true"> + <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> + <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" /> + <circle cx="12" cy="7" r="4" /> + </svg> + </span> + </td> + <td class="data-table-primary"> + <a href="./admin-user-global-detail.html">System Admin</a> + <span class="data-table-sub">admin@system.test</span> + <span class="data-table-sub">admin</span> + </td> + <td>None <span class="data-table-status">System admin</span></td> + <td>0</td> + <td>Active</td> + </tr> + </tbody> + </table> + <div id="user-search-empty" class="empty" hidden> + <p>No users match this search.</p> + </div> + </div> + </section> + </main> + </div> + </div> + + <div class="mockup-controls" aria-label="Mockup theme"> + <span class="mockup-label">Mockup</span> + <button class="mockup-button is-active" type="button" data-theme-target="auto">Auto</button> + <button class="mockup-button" type="button" data-theme-target="light">Light</button> + <button class="mockup-button" type="button" data-theme-target="dark">Dark</button> + </div> + + <script> + const root = document.documentElement; + const themeButtons = document.querySelectorAll('[data-theme-target]'); + const userThemeButton = document.querySelector('[data-user-theme]'); + const userThemeValue = document.querySelector('[data-user-theme-value]'); + let currentTheme = 'auto'; + + function setTheme(value) { + currentTheme = value; + if (value === 'auto') { + root.removeAttribute('data-theme'); + } else { + root.setAttribute('data-theme', value); + } + themeButtons.forEach((button) => { + button.classList.toggle('is-active', button.dataset.themeTarget === value); + }); + if (userThemeValue) { + userThemeValue.textContent = value.charAt(0).toUpperCase() + value.slice(1); + } + } + + themeButtons.forEach((button) => { + button.addEventListener('click', () => setTheme(button.dataset.themeTarget)); + }); + + userThemeButton?.addEventListener('click', () => { + const themes = ['auto', 'light', 'dark']; + setTheme(themes[(themes.indexOf(currentTheme) + 1) % themes.length]); + }); + + const userMenu = document.querySelector('.user-menu'); + document.addEventListener('click', (event) => { + if (userMenu && userMenu.open && !userMenu.contains(event.target)) { + userMenu.open = false; + } + }); + + const search = document.getElementById('user-search'); + const empty = document.getElementById('user-search-empty'); + search?.addEventListener('input', () => { + const term = search.value.trim().toLowerCase(); + let visible = 0; + document.querySelectorAll('#user-rows tr').forEach((row) => { + const match = !term || row.dataset.search.includes(term); + row.hidden = !match; + if (match) visible += 1; + }); + if (empty) empty.hidden = visible > 0; + }); + + document.querySelectorAll('#user-rows tr[data-row-href]').forEach((row) => { + row.addEventListener('click', () => { + window.location.href = row.dataset.rowHref; + }); + }); + </script> + </body> +</html> diff --git a/mockup/plain/global.css b/mockup/plain/global.css @@ -20,6 +20,7 @@ --row-hover: #0000000d; --skeleton: #00000012; --danger: #c9190b; + --danger-text: #c9190b; --field-line: rgba(0, 0, 0, 0.42); --shadow: 0 0.125em 0.25em #0008; --hex: url('./hex-grid-light.svg'); @@ -258,6 +259,22 @@ body { line-height: 1.6; } +.panel-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 1rem; + margin-bottom: 1rem; +} + +.panel-header h2 { + margin: 0; +} + +.panel-header .note { + margin-top: 0.25rem; +} + .button { display: inline-block; padding: 0.625rem 1.25rem; @@ -596,6 +613,12 @@ body { border-bottom: 0; } +.data-table-static tbody tr, +.data-table-static tbody tr:hover { + cursor: default; + background: transparent; +} + .table-icon-column { width: 1%; } @@ -682,7 +705,7 @@ body { } .danger-zone h2 { - color: var(--danger); + color: var(--danger-text); } .secret-value { @@ -796,6 +819,15 @@ body { line-height: 1.5; } +select.field-control, +.realm-select select { + appearance: none; + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='0.75em' height='0.75em' viewBox='0 0 24 24' fill='none' stroke='%238a8f95' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E"); + background-repeat: no-repeat; + background-position: right 0.75rem center; + padding-right: 2.25rem; +} + a:focus-visible, button:focus-visible, summary:focus-visible { @@ -874,7 +906,7 @@ summary:focus-visible { --row: #ffffff0d; --row-hover: #ffffff14; --skeleton: #ffffff14; - --danger: #f28b82; + --danger-text: #f28b82; --field-line: rgba(255, 255, 255, 0.42); --hex: url('./hex-grid-dark.svg'); color-scheme: dark; @@ -896,7 +928,7 @@ summary:focus-visible { --row: #ffffff0d; --row-hover: #ffffff14; --skeleton: #ffffff14; - --danger: #f28b82; + --danger-text: #f28b82; --field-line: rgba(255, 255, 255, 0.42); --hex: url('./hex-grid-dark.svg'); color-scheme: dark; diff --git a/server/src/controller/admin/bans/create.js b/server/src/controller/admin/bans/create.js @@ -1,5 +1,6 @@ import { app } from '../../../app.js'; import { authenticateAdminRequest } from '../../../lib/admin-auth.js'; +import { assertAdminRealmUser } from '../../../lib/admin-users.js'; import { createBan, revokeBannedClientAccess, @@ -8,7 +9,6 @@ import { } from '../../../lib/bans.js'; import { HttpError } from '../../../lib/http/http-error.js'; import { getClient } from '../../../lib/oidc/clients.js'; -import { findUserById } from '../../../lib/users.js'; export default { method: 'post', @@ -23,10 +23,12 @@ export default { throw new HttpError(400, 'invalid_request', 'client_id is required'); } - const user = await findUserById(auth.systemDb, req.params.userId); - if (!user) { - throw new HttpError(404, 'user_not_found', 'User not found'); - } + const user = await assertAdminRealmUser({ + systemDb: auth.systemDb, + realmDb: auth.realmDb, + realmId: auth.realm.id, + userId: req.params.userId, + }); const clientId = body.client_id; if (clientId !== '*') { diff --git a/server/src/controller/admin/bans/delete.js b/server/src/controller/admin/bans/delete.js @@ -1,8 +1,8 @@ import { app } from '../../../app.js'; import { authenticateAdminRequest } from '../../../lib/admin-auth.js'; +import { assertAdminRealmUser } from '../../../lib/admin-users.js'; import { deleteBan } from '../../../lib/bans.js'; import { HttpError } from '../../../lib/http/http-error.js'; -import { findUserById } from '../../../lib/users.js'; export default { method: 'delete', @@ -12,10 +12,12 @@ export default { const auth = await authenticateAdminRequest(req, { realmSlug: req.params.realm, }); - const user = await findUserById(auth.systemDb, req.params.userId); - if (!user) { - throw new HttpError(404, 'user_not_found', 'User not found'); - } + const user = await assertAdminRealmUser({ + systemDb: auth.systemDb, + realmDb: auth.realmDb, + realmId: auth.realm.id, + userId: req.params.userId, + }); const removed = await deleteBan(auth.realmDb, { userId: user.id, diff --git a/server/src/controller/admin/consents/revoke.js b/server/src/controller/admin/consents/revoke.js @@ -1,5 +1,6 @@ import { app } from '../../../app.js'; import { authenticateAdminRequest } from '../../../lib/admin-auth.js'; +import { assertAdminRealmUser } from '../../../lib/admin-users.js'; import { revokeConsent, revokeConsentRefreshTokens, @@ -7,7 +8,6 @@ import { } from '../../../lib/consents.js'; import { HttpError } from '../../../lib/http/http-error.js'; import { getClient } from '../../../lib/oidc/clients.js'; -import { findUserById } from '../../../lib/users.js'; function serializeConsent(consent) { return { @@ -30,10 +30,12 @@ export default { const auth = await authenticateAdminRequest(req, { realmSlug: req.params.realm, }); - const user = await findUserById(auth.systemDb, req.params.userId); - if (!user) { - throw new HttpError(404, 'user_not_found', 'User not found'); - } + const user = await assertAdminRealmUser({ + systemDb: auth.systemDb, + realmDb: auth.realmDb, + realmId: auth.realm.id, + userId: req.params.userId, + }); const client = await getClient(auth.realmDb, req.params.clientId); if (!client || client.system_client) { diff --git a/server/src/controller/admin/session/me.js b/server/src/controller/admin/session/me.js @@ -0,0 +1,15 @@ +import { app } from '../../../app.js'; +import { authenticateAdminSession } from '../../../lib/admin-auth.js'; +import { getAdminCurrentUser } from '../../../lib/admin-users.js'; + +export default { + method: 'get', + path: '/api/v1/admin/me', + name: 'admin.me', + async handler(req) { + const auth = await authenticateAdminSession(req); + const user = await getAdminCurrentUser(auth.systemDb, auth.user); + + return new app.HttpOk({ user }, { 'cache-control': 'no-store' }); + }, +}; diff --git a/server/src/controller/admin/users-global/get.js b/server/src/controller/admin/users-global/get.js @@ -0,0 +1,23 @@ +import { app } from '../../../app.js'; +import { authenticateAdminSession } from '../../../lib/admin-auth.js'; +import { getAdminGlobalUserOverview } from '../../../lib/admin-users.js'; +import { HttpError } from '../../../lib/http/http-error.js'; + +export default { + method: 'get', + path: '/api/v1/admin/users/:userId', + name: 'admin.users.get_global', + async handler(req) { + const auth = await authenticateAdminSession(req); + const user = await getAdminGlobalUserOverview( + auth.systemDb, + auth.user, + req.params.userId + ); + if (!user) { + throw new HttpError(404, 'user_not_found', 'User not found'); + } + + return new app.HttpOk(user, { 'cache-control': 'no-store' }); + }, +}; diff --git a/server/src/controller/admin/users-global/list.js b/server/src/controller/admin/users-global/list.js @@ -0,0 +1,15 @@ +import { app } from '../../../app.js'; +import { authenticateAdminSession } from '../../../lib/admin-auth.js'; +import { listAdminGlobalUsers } from '../../../lib/admin-users.js'; + +export default { + method: 'get', + path: '/api/v1/admin/users', + name: 'admin.users.list_global', + async handler(req) { + const auth = await authenticateAdminSession(req); + const users = await listAdminGlobalUsers(auth.systemDb, auth.user); + + return new app.HttpOk({ users }, { 'cache-control': 'no-store' }); + }, +}; diff --git a/server/src/controller/admin/users/get.js b/server/src/controller/admin/users/get.js @@ -0,0 +1,26 @@ +import { app } from '../../../app.js'; +import { authenticateAdminRequest } from '../../../lib/admin-auth.js'; +import { getAdminRealmUserDetail } from '../../../lib/admin-users.js'; +import { HttpError } from '../../../lib/http/http-error.js'; + +export default { + method: 'get', + path: '/api/v1/admin/realms/:realm/users/:userId', + name: 'admin.users.get', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const detail = await getAdminRealmUserDetail( + auth.systemDb, + auth.realmDb, + auth.realm.id, + req.params.userId + ); + if (!detail) { + throw new HttpError(404, 'user_not_found', 'User not found'); + } + + return new app.HttpOk(detail, { 'cache-control': 'no-store' }); + }, +}; diff --git a/server/src/controller/admin/users/list.js b/server/src/controller/admin/users/list.js @@ -0,0 +1,21 @@ +import { app } from '../../../app.js'; +import { authenticateAdminRequest } from '../../../lib/admin-auth.js'; +import { listAdminRealmUsers } from '../../../lib/admin-users.js'; + +export default { + method: 'get', + path: '/api/v1/admin/realms/:realm/users', + name: 'admin.users.list', + async handler(req) { + const auth = await authenticateAdminRequest(req, { + realmSlug: req.params.realm, + }); + const users = await listAdminRealmUsers( + auth.systemDb, + auth.realmDb, + auth.realm.id + ); + + return new app.HttpOk({ users }, { 'cache-control': 'no-store' }); + }, +}; diff --git a/server/src/lib/admin-users.js b/server/src/lib/admin-users.js @@ -0,0 +1,343 @@ +import { HttpError } from './http/http-error.js'; +import { inClause } from './db/query.js'; +import { splitScopes } from './consents.js'; +import { isSystemAdmin } from './policy.js'; +import { openRealmDatabase, realmMetadata } from './realm.js'; +import { + findUserById, + getMembership, + getPrimaryEmail, + getUserRoles, +} from './users.js'; + +function uniqueUserIds(...groups) { + return [...new Set(groups.flat().map((group) => group.user_id || group.id))]; +} + +function groupRows(rows, key, valueKey = null) { + const grouped = new Map(); + for (const row of rows) { + const current = grouped.get(row[key]) || []; + current.push(valueKey ? row[valueKey] : row); + grouped.set(row[key], current); + } + return grouped; +} + +function firstRows(rows, key) { + const first = new Map(); + for (const row of rows) { + if (!first.has(row[key])) first.set(row[key], row); + } + return first; +} + +function compareUsers(a, b) { + const left = `${a.display_name || a.username} ${a.username}`.toLowerCase(); + const right = `${b.display_name || b.username} ${b.username}`.toLowerCase(); + if (left < right) return -1; + if (left > right) return 1; + return 0; +} + +export async function assertAdminRealmUser({ systemDb, realmDb, realmId, userId }) { + const user = await findUserById(systemDb, userId); + if (!user) { + throw new HttpError(404, 'user_not_found', 'User not found'); + } + + const membership = await getMembership(realmDb, userId); + if (user.home_realm_id !== realmId && !membership) { + throw new HttpError(404, 'user_not_found', 'User not found'); + } + + return user; +} + +export async function listAdminRealmUsers(systemDb, realmDb, realmId) { + const membershipRows = await realmDb.all( + 'SELECT user_id, status FROM realm_memberships' + ); + const homeRows = await systemDb.all( + 'SELECT id FROM users WHERE home_realm_id = {realmId}', + { realmId } + ); + const ids = uniqueUserIds(membershipRows, homeRows); + if (ids.length === 0) return []; + + const userClause = inClause('userId', ids); + const userRows = await systemDb.all( + `SELECT id, username, display_name, status, home_realm_id, + is_system_admin, last_login_at, created_at, updated_at + FROM users + WHERE id IN (${userClause.sql})`, + userClause.params + ); + + const emailClause = inClause('emailUserId', ids); + const emailRows = await systemDb.all( + `SELECT user_id, email + FROM user_emails + WHERE verified = 1 AND user_id IN (${emailClause.sql}) + ORDER BY user_id ASC, is_primary DESC, created_at ASC`, + emailClause.params + ); + + const roleRows = await realmDb.all( + `SELECT mr.user_id, r.slug + FROM membership_roles mr + JOIN roles r ON r.id = mr.role_id + ORDER BY r.slug ASC` + ); + const banRows = await realmDb.all( + 'SELECT user_id, client_id FROM app_bans ORDER BY client_id ASC' + ); + + const usersById = new Map(userRows.map((row) => [row.id, row])); + const membershipsByUser = new Map(membershipRows.map((row) => [row.user_id, row])); + const emailsByUser = firstRows(emailRows, 'user_id'); + const rolesByUser = groupRows(roleRows, 'user_id', 'slug'); + const bansByUser = groupRows(banRows, 'user_id'); + + return userRows + .map((user) => { + const membership = membershipsByUser.get(user.id) || null; + const relationship = user.home_realm_id === realmId ? 'home' : 'guest'; + const bans = bansByUser.get(user.id) || []; + return { + id: user.id, + username: user.username, + display_name: user.display_name, + email: emailsByUser.get(user.id)?.email || null, + status: user.status, + membership_status: membership?.status || (relationship === 'home' ? 'active' : null), + relationship, + roles: rolesByUser.get(user.id) || [], + is_system_admin: Boolean(user.is_system_admin), + banned: bans.length > 0, + ban_count: bans.length, + last_login_at: user.last_login_at, + created_at: user.created_at, + }; + }) + .sort(compareUsers); +} + +export async function getAdminRealmUserDetail(systemDb, realmDb, realmId, userId) { + const user = await findUserById(systemDb, userId); + if (!user) return null; + + const membership = await getMembership(realmDb, userId); + if (user.home_realm_id !== realmId && !membership) return null; + + const roles = await getUserRoles(realmDb, userId); + const email = await systemDb.get( + `SELECT email + FROM user_emails + WHERE user_id = {userId} AND verified = 1 + ORDER BY is_primary DESC, created_at ASC + LIMIT 1`, + { userId } + ); + const consentRows = await systemDb.all( + `SELECT user_id, realm_id, client_id, scopes, granted_via, created_at, + updated_at, revoked_at + FROM client_consents + WHERE user_id = {userId} AND realm_id = {realmId} + ORDER BY client_id ASC`, + { userId, realmId } + ); + const clientRows = await realmDb.all( + 'SELECT client_id, name, consent_mode FROM oidc_clients' + ); + const banRows = await realmDb.all( + `SELECT user_id, client_id, created_by, created_at + FROM app_bans + WHERE user_id = {userId} + ORDER BY CASE WHEN client_id = '*' THEN 0 ELSE 1 END, client_id ASC`, + { userId } + ); + + const creatorIds = [...new Set(banRows.map((row) => row.created_by).filter(Boolean))]; + const creatorsById = new Map(); + if (creatorIds.length > 0) { + const creatorClause = inClause('creatorId', creatorIds); + const creatorRows = await systemDb.all( + `SELECT id, username FROM users WHERE id IN (${creatorClause.sql})`, + creatorClause.params + ); + for (const creator of creatorRows) { + creatorsById.set(creator.id, creator.username); + } + } + + const clientsById = new Map( + clientRows.map((row) => [ + row.client_id, + { name: row.name, consent_mode: row.consent_mode || 'remembered' }, + ]) + ); + + return { + user: { + id: user.id, + username: user.username, + display_name: user.display_name, + email: email?.email || null, + status: user.status, + membership_status: membership?.status || (user.home_realm_id === realmId ? 'active' : null), + relationship: user.home_realm_id === realmId ? 'home' : 'guest', + roles, + is_system_admin: Boolean(user.is_system_admin), + banned: banRows.length > 0, + ban_count: banRows.length, + home_realm_id: user.home_realm_id, + last_login_at: user.last_login_at, + created_at: user.created_at, + updated_at: user.updated_at, + }, + consents: consentRows.map((consent) => { + const client = clientsById.get(consent.client_id) || null; + return { + client_id: consent.client_id, + client_name: client?.name || null, + client_consent_mode: client?.consent_mode || null, + scopes: splitScopes(consent.scopes), + granted_via: consent.granted_via, + created_at: consent.created_at, + updated_at: consent.updated_at, + revoked_at: consent.revoked_at, + active: !consent.revoked_at, + }; + }), + bans: banRows.map((ban) => ({ + client_id: ban.client_id, + client_name: ban.client_id === '*' ? 'All apps' : clientsById.get(ban.client_id)?.name || null, + created_by: ban.created_by, + created_by_username: creatorsById.get(ban.created_by) || null, + created_at: ban.created_at, + })), + }; +} + +export async function getAdminCurrentUser(systemDb, user) { + const email = await getPrimaryEmail(systemDb, user.id); + return { + id: user.id, + username: user.username, + display_name: user.display_name, + email: email?.email || null, + is_system_admin: isSystemAdmin(user), + }; +} + +export async function listAdminGlobalUsers(systemDb, actor) { + if (!isSystemAdmin(actor)) { + throw new HttpError(403, 'forbidden', 'System administrator access is required'); + } + + const userRows = await systemDb.all( + `SELECT id, username, display_name, status, home_realm_id, + is_system_admin, last_login_at, created_at + FROM users` + ); + if (userRows.length === 0) return []; + + const ids = userRows.map((row) => row.id); + const emailClause = inClause('emailUserId', ids); + const emailRows = await systemDb.all( + `SELECT user_id, email + FROM user_emails + WHERE verified = 1 AND user_id IN (${emailClause.sql}) + ORDER BY user_id ASC, is_primary DESC, created_at ASC`, + emailClause.params + ); + + const realmRows = await systemDb.all( + 'SELECT id, slug, db_file FROM realms ORDER BY slug ASC' + ); + const realmsById = new Map(realmRows.map((row) => [row.id, row])); + const membershipCounts = new Map(); + for (const realm of realmRows) { + const realmDb = await openRealmDatabase(realm); + const members = await realmDb.all('SELECT user_id FROM realm_memberships'); + for (const member of members) { + membershipCounts.set(member.user_id, (membershipCounts.get(member.user_id) || 0) + 1); + } + } + + const emailsByUser = firstRows(emailRows, 'user_id'); + return userRows + .map((user) => ({ + id: user.id, + username: user.username, + display_name: user.display_name, + email: emailsByUser.get(user.id)?.email || null, + status: user.status, + is_system_admin: Boolean(user.is_system_admin), + home_realm_slug: realmsById.get(user.home_realm_id)?.slug || null, + membership_count: membershipCounts.get(user.id) || 0, + last_login_at: user.last_login_at, + created_at: user.created_at, + })) + .sort(compareUsers); +} + +export async function getAdminGlobalUserOverview(systemDb, actor, userId) { + if (!isSystemAdmin(actor)) { + throw new HttpError(403, 'forbidden', 'System administrator access is required'); + } + + const user = await findUserById(systemDb, userId); + if (!user) return null; + + const email = await getPrimaryEmail(systemDb, userId); + const realmRows = await systemDb.all( + 'SELECT id, slug, db_file FROM realms ORDER BY slug ASC' + ); + const memberships = []; + for (const realm of realmRows) { + const realmDb = await openRealmDatabase(realm); + const membership = await getMembership(realmDb, userId); + const isHome = user.home_realm_id === realm.id; + if (!isHome && !membership) continue; + + const roles = await getUserRoles(realmDb, userId); + const bannedRow = await realmDb.get( + 'SELECT 1 AS banned FROM app_bans WHERE user_id = {userId} LIMIT 1', + { userId } + ); + let displayName = realm.slug; + try { + const metadata = await realmMetadata(realm); + displayName = metadata.display_name; + } catch { + continue; + } + + memberships.push({ + slug: realm.slug, + display_name: displayName, + relationship: isHome ? 'home' : 'guest', + membership_status: membership?.status || 'active', + roles, + banned: Boolean(bannedRow), + }); + } + + return { + user: { + id: user.id, + username: user.username, + display_name: user.display_name, + email: email?.email || null, + status: user.status, + is_system_admin: Boolean(user.is_system_admin), + home_realm_slug: memberships.find((realm) => realm.relationship === 'home')?.slug || null, + last_login_at: user.last_login_at, + created_at: user.created_at, + updated_at: user.updated_at, + }, + memberships, + }; +} diff --git a/server/test/http.test.js b/server/test/http.test.js @@ -217,6 +217,34 @@ function clearConsent(env, { username, realm, clientId }) { }); } +function setAdminConsent( + env, + { username, realm, clientId, scopes = 'openid', grantedVia = 'user', revokedAt = null } +) { + const now = Date.now(); + const targetUserId = userId(env, username); + const targetRealmId = realmId(env, realm); + withSystemDatabase(env, (database) => { + database + .prepare( + `INSERT OR REPLACE INTO client_consents + (user_id, realm_id, client_id, scopes, granted_via, created_at, updated_at, revoked_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)` + ) + .run( + targetUserId, + targetRealmId, + clientId, + scopes, + grantedVia, + now, + revokedAt || now, + revokedAt + ); + }); + return revokedAt || now; +} + function setConsentMode(env, { realm, clientId, mode }) { withRealmDatabase(env, realm, (database) => { database @@ -2065,6 +2093,195 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { } }); + await t.test('admin user directory and app restrictions are realm scoped', async () => { + const admin = await adminToken('it@acme.test'); + const systemAdmin = await adminToken(); + const aliceId = userId(env, 'alice'); + const acmeId = realmId(env, 'acme'); + const adminId = userId(env, 'admin'); + + clearBans(env, { username: 'alice', realm: 'acme' }); + clearConsent(env, { username: 'alice', realm: 'acme', clientId: 'internal-app' }); + clearConsent(env, { + username: 'alice', + realm: 'acme', + clientId: 'acme-members-app', + }); + + try { + setAdminConsent(env, { + username: 'alice', + realm: 'acme', + clientId: 'internal-app', + scopes: 'openid profile', + grantedVia: 'trusted', + }); + const revokedAt = setAdminConsent(env, { + username: 'alice', + realm: 'acme', + clientId: 'acme-members-app', + scopes: '', + revokedAt: Date.now(), + }); + + withRealmDatabase(env, 'acme', (database) => { + database + .prepare( + `INSERT INTO app_bans (user_id, client_id, created_by, created_at) + VALUES (?, ?, ?, ?)` + ) + .run(aliceId, 'internal-app', userId(env, 'acme-it'), Date.now()); + }); + + const acmeUsers = await identity({ + path: '/api/v1/admin/realms/acme/users', + bearer: admin.access_token, + }); + assert.equal(acmeUsers.status, 200); + assert.deepEqual( + acmeUsers.json.users.map((user) => user.username).sort(), + ['acme-it', 'alice', 'guest'] + ); + + const acmeAlice = acmeUsers.json.users.find((user) => user.username === 'alice'); + assert.equal(acmeAlice.relationship, 'home'); + assert.equal(acmeAlice.membership_status, 'active'); + assert.equal(acmeAlice.email, 'alice@acme.test'); + assert.equal(acmeAlice.banned, true); + assert.equal(acmeAlice.ban_count, 1); + + const acmeAdminUser = acmeUsers.json.users.find((user) => user.username === 'acme-it'); + assert.deepEqual(acmeAdminUser.roles, ['realm-admin']); + + const acmeGuest = acmeUsers.json.users.find((user) => user.username === 'guest'); + assert.equal(acmeGuest.relationship, 'guest'); + + const globexUsers = await identity({ + path: '/api/v1/admin/realms/globex/users', + bearer: systemAdmin.access_token, + }); + assert.equal(globexUsers.status, 200); + assert.deepEqual( + globexUsers.json.users.map((user) => user.username).sort(), + ['alice', 'contractor'] + ); + + const detail = await identity({ + path: `/api/v1/admin/realms/acme/users/${aliceId}`, + bearer: admin.access_token, + }); + assert.equal(detail.status, 200); + assert.equal(detail.json.user.id, aliceId); + assert.equal(detail.json.user.relationship, 'home'); + assert.equal(detail.json.user.home_realm_id, acmeId); + assert.equal(detail.json.user.banned, true); + + const internalConsent = detail.json.consents.find( + (consent) => consent.client_id === 'internal-app' + ); + assert.equal(internalConsent.active, true); + assert.equal(internalConsent.granted_via, 'trusted'); + assert.deepEqual(internalConsent.scopes, ['openid', 'profile']); + assert.equal(internalConsent.client_name, 'Internal App'); + + const revokedConsent = detail.json.consents.find( + (consent) => consent.client_id === 'acme-members-app' + ); + assert.equal(revokedConsent.active, false); + assert.equal(revokedConsent.revoked_at, revokedAt); + assert.deepEqual(revokedConsent.scopes, []); + + const ban = detail.json.bans.find((item) => item.client_id === 'internal-app'); + assert.equal(ban.client_name, 'Internal App'); + assert.equal(ban.created_by_username, 'acme-it'); + + const outsiderDetail = await identity({ + path: `/api/v1/admin/realms/acme/users/${adminId}`, + bearer: admin.access_token, + }); + assert.equal(outsiderDetail.status, 404); + assert.equal(outsiderDetail.json.error.code, 'user_not_found'); + + const outsiderBan = await identity({ + method: 'POST', + path: `/api/v1/admin/realms/acme/users/${adminId}/bans`, + bearer: admin.access_token, + body: { client_id: '*' }, + }); + assert.equal(outsiderBan.status, 404); + assert.equal(outsiderBan.json.error.code, 'user_not_found'); + assert.equal( + withRealmDatabase(env, 'acme', (database) => + database.prepare('SELECT COUNT(*) AS count FROM app_bans WHERE user_id = ?').get(adminId).count + ), + 0 + ); + } finally { + clearBans(env, { username: 'alice', realm: 'acme' }); + clearConsent(env, { username: 'alice', realm: 'acme', clientId: 'internal-app' }); + clearConsent(env, { + username: 'alice', + realm: 'acme', + clientId: 'acme-members-app', + }); + } + }); + + await t.test('system admins can manage users outside a realm', async () => { + const acmeAdmin = await adminToken('it@acme.test'); + const systemAdmin = await adminToken(); + const aliceId = userId(env, 'alice'); + + const acmeMe = await identity({ + path: '/api/v1/admin/me', + bearer: acmeAdmin.access_token, + }); + assert.equal(acmeMe.status, 200); + assert.equal(acmeMe.json.user.is_system_admin, false); + + const systemMe = await identity({ + path: '/api/v1/admin/me', + bearer: systemAdmin.access_token, + }); + assert.equal(systemMe.status, 200); + assert.equal(systemMe.json.user.is_system_admin, true); + + const forbidden = await identity({ + path: '/api/v1/admin/users', + bearer: acmeAdmin.access_token, + }); + assert.equal(forbidden.status, 403); + assert.equal(forbidden.json.error.code, 'forbidden'); + + const users = await identity({ + path: '/api/v1/admin/users', + bearer: systemAdmin.access_token, + }); + assert.equal(users.status, 200); + const usernames = users.json.users.map((user) => user.username); + assert.ok(usernames.includes('alice')); + assert.ok(usernames.includes('admin')); + + const globalAlice = users.json.users.find((user) => user.username === 'alice'); + assert.equal(globalAlice.home_realm_slug, 'acme'); + assert.equal(globalAlice.membership_count, 2); + + const globalAdmin = users.json.users.find((user) => user.username === 'admin'); + assert.equal(globalAdmin.home_realm_slug, null); + assert.equal(globalAdmin.membership_count, 0); + assert.equal(globalAdmin.is_system_admin, true); + + const overview = await identity({ + path: `/api/v1/admin/users/${aliceId}`, + bearer: systemAdmin.access_token, + }); + assert.equal(overview.status, 200); + assert.deepEqual( + overview.json.memberships.map((membership) => [membership.slug, membership.relationship]).sort(), + [['acme', 'home'], ['globex', 'guest']] + ); + }); + await t.test('system admins can use the admin client on the canonical host', async () => { const admin = await adminToken(); assert.ok(admin.access_token);