auth

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

admin.tsx (21853B)


      1 import { Activity, AppWindow, LayoutGrid, LibraryBig, Settings, Users } from 'lucide';
      2 import m from 'mithril';
      3 import { AppShell } from '@component/app-shell';
      4 import { type NavItem } from '@component/nav';
      5 import { MobileNavAccount, MobileNavToggle } from '@component/mobile-nav';
      6 import { StatusPage } from '@component/status-page';
      7 import { Topbar } from '@component/topbar';
      8 import { UserMenu } from '@component/user-menu';
      9 import { applyTheme, cycleTheme, getTheme, type Theme } from '@util/theme';
     10 import {
     11   adminSignOut,
     12   clearAdminTokens,
     13   completeAdminLogin,
     14   getAdminTokens,
     15   loadAdminMe,
     16   loadAdminRealms,
     17   loadAdminUser,
     18   startAdminLogin,
     19 } from '../util/auth';
     20 import { appUrl, getAuthUrl, type AdminRealm, type UserInfo } from '../util/api';
     21 import { realmNavigation } from '../util/navigation';
     22 import { OverviewPage } from './overview';
     23 import { RealmsPage } from './realms';
     24 import { SessionsPage } from './sessions';
     25 import { ClientEditPage } from './client-edit';
     26 import { ClientsPage } from './clients';
     27 import { GlobalUserPage } from './global-user';
     28 import { HostsPage } from './hosts';
     29 import { EmailDomainsPage } from './email-domains';
     30 import { ProvidersPage } from './providers';
     31 import { ProviderEditPage } from './provider-edit';
     32 import { UserPage } from './user';
     33 import { UsersPage } from './users';
     34 import { SettingsPage } from './settings';
     35 import { SystemSettingsPage } from './system-settings';
     36 
     37 function currentPath() {
     38   return (m.route.get() || '/').split('?')[0];
     39 }
     40 
     41 function sessionsRealm() {
     42   const path = currentPath();
     43   if (!path.startsWith('/sessions/')) return null;
     44   try {
     45     return decodeURIComponent(path.slice('/sessions/'.length));
     46   } catch {
     47     return null;
     48   }
     49 }
     50 
     51 function clientsRealm() {
     52   const path = currentPath();
     53   if (path !== '/clients' && !path.startsWith('/clients/')) return null;
     54   const suffix = path.slice('/clients/'.length);
     55   if (!suffix) return null;
     56   const slug = suffix.split('/')[0];
     57   try {
     58     return decodeURIComponent(slug);
     59   } catch {
     60     return null;
     61   }
     62 }
     63 
     64 function clientEditPath() {
     65   const path = currentPath();
     66   const match = /^\/clients\/([^/]+)\/edit\/(.+)$/.exec(path);
     67   if (!match) return null;
     68   try {
     69     return {
     70       realmSlug: decodeURIComponent(match[1]),
     71       clientId: decodeURIComponent(match[2]),
     72     };
     73   } catch {
     74     return null;
     75   }
     76 }
     77 
     78 function usersRealm() {
     79   const path = currentPath();
     80   if (path !== '/users' && !path.startsWith('/users/')) return null;
     81   const suffix = path.slice('/users/'.length);
     82   if (!suffix) return null;
     83   const slug = suffix.split('/')[0];
     84   try {
     85     return decodeURIComponent(slug);
     86   } catch {
     87     return null;
     88   }
     89 }
     90 
     91 function userDetailPath() {
     92   const path = currentPath();
     93   if (path === '/users/global' || path.startsWith('/users/global/')) return null;
     94   const match = /^\/users\/([^/]+)\/([^/]+)$/.exec(path);
     95   if (!match) return null;
     96   try {
     97     return {
     98       realmSlug: decodeURIComponent(match[1]),
     99       userId: decodeURIComponent(match[2]),
    100     };
    101   } catch {
    102     return null;
    103   }
    104 }
    105 
    106 function globalUserDetailPath() {
    107   const path = currentPath();
    108   const match = /^\/users\/global\/([^/]+)$/.exec(path);
    109   if (!match) return null;
    110   try {
    111     return { userId: decodeURIComponent(match[1]) };
    112   } catch {
    113     return null;
    114   }
    115 }
    116 
    117 function settingsRealm() {
    118   const path = currentPath();
    119   if (path !== '/settings' && !path.startsWith('/settings/')) return null;
    120   const suffix = path.slice('/settings/'.length);
    121   if (!suffix) return null;
    122   const slug = suffix.split('/')[0];
    123   try {
    124     return decodeURIComponent(slug);
    125   } catch {
    126     return null;
    127   }
    128 }
    129 
    130 function hostsRealm() {
    131   const path = currentPath();
    132   if (path !== '/hosts' && !path.startsWith('/hosts/')) return null;
    133   const suffix = path.slice('/hosts/'.length);
    134   if (!suffix) return null;
    135   const slug = suffix.split('/')[0];
    136   try {
    137     return decodeURIComponent(slug);
    138   } catch {
    139     return null;
    140   }
    141 }
    142 
    143 function emailDomainsRealm() {
    144   const path = currentPath();
    145   if (path !== '/email-domains' && !path.startsWith('/email-domains/')) return null;
    146   const suffix = path.slice('/email-domains/'.length);
    147   if (!suffix) return null;
    148   const slug = suffix.split('/')[0];
    149   try {
    150     return decodeURIComponent(slug);
    151   } catch {
    152     return null;
    153   }
    154 }
    155 
    156 function providersRealm() {
    157   const path = currentPath();
    158   if (path !== '/providers' && !path.startsWith('/providers/')) return null;
    159   const suffix = path.slice('/providers/'.length);
    160   if (!suffix) return null;
    161   const slug = suffix.split('/')[0];
    162   try {
    163     return decodeURIComponent(slug);
    164   } catch {
    165     return null;
    166   }
    167 }
    168 
    169 function providerEditPath() {
    170   const path = currentPath();
    171   const create = /^\/providers\/([^/]+)\/new$/.exec(path);
    172   if (create) {
    173     try {
    174       return { realmSlug: decodeURIComponent(create[1]), providerSlug: null };
    175     } catch {
    176       return null;
    177     }
    178   }
    179   const match = /^\/providers\/([^/]+)\/edit\/(.+)$/.exec(path);
    180   if (!match) return null;
    181   try {
    182     return {
    183       realmSlug: decodeURIComponent(match[1]),
    184       providerSlug: decodeURIComponent(match[2]),
    185     };
    186   } catch {
    187     return null;
    188   }
    189 }
    190 
    191 export const Admin: m.Component = {
    192   user: null as UserInfo | null,
    193   systemAdmin: false,
    194   canCreateRealm: false,
    195   adminAccessLoaded: false,
    196   accountRedirecting: false,
    197   routeGuardActive: false,
    198   realms: null as AdminRealm[] | null,
    199   realmsError: null as Error | null,
    200   error: null as Error | null,
    201   authUrl: window.location.origin,
    202   theme: getTheme() as Theme,
    203   mobileNavOpen: false,
    204   lastPath: '',
    205   desktopMedia: null as MediaQueryList | null,
    206   onDesktopMediaChange: null as ((event: MediaQueryListEvent) => void) | null,
    207 
    208   oninit(this: any) {
    209     applyTheme(this.theme);
    210     this.lastPath = currentPath();
    211     this.load();
    212   },
    213 
    214   oncreate(this: any) {
    215     this.desktopMedia = window.matchMedia('(min-width: 60em)');
    216     this.onDesktopMediaChange = (event: MediaQueryListEvent) => {
    217       if (event.matches) this.mobileNavOpen = false;
    218     };
    219     this.desktopMedia.addEventListener('change', this.onDesktopMediaChange);
    220   },
    221 
    222   onremove(this: any) {
    223     if (this.desktopMedia && this.onDesktopMediaChange) {
    224       this.desktopMedia.removeEventListener('change', this.onDesktopMediaChange);
    225     }
    226   },
    227 
    228   onupdate(this: any) {
    229     const path = currentPath();
    230     if (path !== this.lastPath) {
    231       this.lastPath = path;
    232       this.mobileNavOpen = false;
    233     }
    234     this.ensureRouteAccess();
    235     this.updateTitle();
    236   },
    237 
    238   async load(this: any) {
    239     try {
    240       this.authUrl = await getAuthUrl();
    241     } catch {
    242       this.authUrl = window.location.origin;
    243     }
    244 
    245     if (!getAdminTokens()) {
    246       await this.login();
    247       return;
    248     }
    249 
    250     try {
    251       this.user = await loadAdminUser();
    252       this.updateTitle();
    253     } catch (e: any) {
    254       if (e?.status === 401 || e?.status === 400 || !getAdminTokens()) {
    255         await this.login();
    256         return;
    257       }
    258       this.error = e as Error;
    259       m.redraw();
    260       return;
    261     }
    262 
    263     try {
    264       this.realms = await loadAdminRealms();
    265       this.realmsError = null;
    266     } catch (e: any) {
    267       if (e?.status === 401 || e?.status === 400) {
    268         await this.login();
    269         return;
    270       }
    271       this.realms = [];
    272       this.realmsError = e as Error;
    273     }
    274 
    275     try {
    276       const me = await loadAdminMe();
    277       this.systemAdmin = me.is_system_admin;
    278       this.canCreateRealm = me.can_create_realm;
    279       this.adminAccessLoaded = true;
    280     } catch (e: any) {
    281       if (e?.status === 401 || e?.status === 400) {
    282         await this.login();
    283         return;
    284       }
    285       this.systemAdmin = false;
    286       this.canCreateRealm = false;
    287     }
    288 
    289     this.ensureRouteAccess();
    290     m.redraw();
    291   },
    292 
    293   async login(this: any) {
    294     try {
    295       await startAdminLogin();
    296     } catch (e) {
    297       this.error = e as Error;
    298       m.redraw();
    299     }
    300   },
    301 
    302   async authExpired(this: any) {
    303     clearAdminTokens();
    304     await this.login();
    305   },
    306 
    307   async reloadRealms(this: any) {
    308     let reloadFailed = false;
    309 
    310     try {
    311       this.realms = await loadAdminRealms();
    312       this.realmsError = null;
    313     } catch (e: any) {
    314       reloadFailed = true;
    315       if (e?.status === 401 || e?.status === 400) {
    316         await this.login();
    317         return;
    318       }
    319       this.realmsError = e as Error;
    320     }
    321 
    322     try {
    323       const me = await loadAdminMe();
    324       this.systemAdmin = me.is_system_admin;
    325       this.canCreateRealm = me.can_create_realm;
    326       this.adminAccessLoaded = true;
    327     } catch (e: any) {
    328       reloadFailed = true;
    329       if (e?.status === 401 || e?.status === 400) {
    330         await this.login();
    331         return;
    332       }
    333       this.canCreateRealm = false;
    334       this.adminAccessLoaded = false;
    335     }
    336 
    337     if (!reloadFailed) {
    338       this.ensureRouteAccess();
    339     }
    340     m.redraw();
    341   },
    342 
    343   ensureRouteAccess(this: any) {
    344     if (!this.realms || !this.adminAccessLoaded || this.accountRedirecting) return false;
    345 
    346     const path = currentPath();
    347 
    348     if (this.realms.length === 0 && !this.canCreateRealm) {
    349       this.accountRedirecting = true;
    350       this.routeGuardActive = true;
    351       clearAdminTokens();
    352       window.location.assign(`${this.authUrl}/app/account`);
    353       return true;
    354     }
    355 
    356     if (
    357       path === '/realms' &&
    358       this.realms.length === 1 &&
    359       !this.canCreateRealm
    360     ) {
    361       this.routeGuardActive = true;
    362       m.route.set(`/settings/${encodeURIComponent(this.realms[0].slug)}`, null, {
    363         replace: true,
    364       });
    365       return true;
    366     }
    367 
    368     if (path === '/system-settings' && !this.systemAdmin) {
    369       this.routeGuardActive = true;
    370       m.route.set('/', null, { replace: true });
    371       return true;
    372     }
    373 
    374     this.routeGuardActive = false;
    375     return false;
    376   },
    377 
    378   updateTitle(this: any) {
    379     const path = currentPath();
    380     const realmsPath = path === '/realms';
    381     const clients = path === '/clients' || path.startsWith('/clients/');
    382     const sessions = path === '/sessions' || path.startsWith('/sessions/');
    383     const users = path === '/users' || path.startsWith('/users/');
    384     const systemSettings = path === '/system-settings';
    385     const realmSettings = path === '/settings' || path.startsWith('/settings/');
    386     const hosts = path === '/hosts' || path.startsWith('/hosts/');
    387     const emailDomains = path === '/email-domains' || path.startsWith('/email-domains/');
    388     const providers = path === '/providers' || path.startsWith('/providers/');
    389     const title = realmsPath
    390       ? 'Realms | Administration'
    391       : clients
    392       ? path.includes('/edit/')
    393         ? 'Edit client | Administration'
    394         : 'Clients | Administration'
    395       : sessions
    396         ? 'Sessions | Administration'
    397         : users
    398           ? userDetailPath() || globalUserDetailPath()
    399             ? 'User | Administration'
    400             : 'Users | Administration'
    401           : systemSettings
    402             ? 'System settings | Administration'
    403             : hosts
    404               ? 'Hosts | Administration'
    405               : emailDomains
    406                 ? 'Email domains | Administration'
    407                 : providers
    408                   ? path.endsWith('/new')
    409                     ? 'Add provider | Administration'
    410                     : path.includes('/edit/')
    411                       ? 'Edit provider | Administration'
    412                       : 'Identity providers | Administration'
    413                   : realmSettings
    414                     ? 'Realm settings | Administration'
    415                     : 'Administration';
    416     document.title = title;
    417   },
    418 
    419   toggleMobileNav(this: any) {
    420     this.mobileNavOpen = !this.mobileNavOpen;
    421   },
    422 
    423   closeMobileNav(this: any) {
    424     this.mobileNavOpen = false;
    425   },
    426 
    427   cycleTheme(this: any) {
    428     this.theme = cycleTheme();
    429   },
    430 
    431   view(this: any) {
    432     const user = this.user;
    433     const path = currentPath();
    434     const routeGuardActive = Boolean(this.routeGuardActive || this.accountRedirecting);
    435     const realmsPath = path === '/realms';
    436     const sessions = path === '/sessions' || path.startsWith('/sessions/');
    437     const clients = path === '/clients' || path.startsWith('/clients/');
    438     const users = path === '/users' || path.startsWith('/users/');
    439     const systemSettings = path === '/system-settings';
    440     const realmSettings = path === '/settings' || path.startsWith('/settings/');
    441     const hosts = path === '/hosts' || path.startsWith('/hosts/');
    442     const emailDomains = path === '/email-domains' || path.startsWith('/email-domains/');
    443     const providers = path === '/providers' || path.startsWith('/providers/');
    444     const realmSlug = sessionsRealm();
    445     const clientRealmSlug = clientsRealm();
    446     const userRealmSlug = usersRealm();
    447     const settingsRealmSlug = settingsRealm();
    448     const hostsRealmSlug = hostsRealm();
    449     const emailDomainsRealmSlug = emailDomainsRealm();
    450     const providersRealmSlug = providersRealm();
    451     const providerEdit = providerEditPath();
    452     const clientEdit = clientEditPath();
    453     const userDetail = userDetailPath();
    454     const globalUser = globalUserDetailPath();
    455     const isGlobalUsers = usersRealm() === 'global';
    456     const firstRealm = this.realms && this.realms.length > 0 ? this.realms[0].slug : null;
    457     const sessionsHref = firstRealm
    458       ? `/sessions/${encodeURIComponent(firstRealm)}`
    459       : '/sessions';
    460     const clientsHref = firstRealm
    461       ? `/clients/${encodeURIComponent(firstRealm)}`
    462       : '/clients';
    463     const usersHref = firstRealm ? `/users/${encodeURIComponent(firstRealm)}` : '/users';
    464     const realmNav = realmNavigation(this.realms, Boolean(this.canCreateRealm));
    465 
    466     const navItems: NavItem[] = [
    467       {
    468         href: appUrl('/'),
    469         label: 'Overview',
    470         icon: LayoutGrid,
    471         active: path === '/',
    472         onclick: (event: Event) => {
    473           event.preventDefault();
    474           m.route.set('/');
    475         },
    476       },
    477     ];
    478 
    479     if (realmNav.visible) {
    480       navItems.push({
    481         href: appUrl(realmNav.href),
    482         label: realmNav.label,
    483         icon: LibraryBig,
    484         active: realmsPath || realmSettings || hosts || emailDomains || providers,
    485         onclick: (event: Event) => {
    486           event.preventDefault();
    487           m.route.set(realmNav.href);
    488         },
    489       });
    490     }
    491 
    492     if (firstRealm) {
    493       navItems.push(
    494         {
    495           href: appUrl(clientsHref),
    496           label: 'Clients',
    497           icon: AppWindow,
    498           active: clients,
    499           onclick: (event: Event) => {
    500             event.preventDefault();
    501             m.route.set(clientsHref);
    502           },
    503         },
    504         {
    505           href: appUrl(sessionsHref),
    506           label: 'Sessions',
    507           icon: Activity,
    508           active: sessions,
    509           onclick: (event: Event) => {
    510             event.preventDefault();
    511             m.route.set(sessionsHref);
    512           },
    513         },
    514         {
    515           href: appUrl(usersHref),
    516           label: 'Users',
    517           icon: Users,
    518           active: users,
    519           onclick: (event: Event) => {
    520             event.preventDefault();
    521             m.route.set(usersHref);
    522           },
    523         }
    524       );
    525     }
    526 
    527     if (this.systemAdmin) {
    528       navItems.push({
    529         href: appUrl('/system-settings'),
    530         label: 'Settings',
    531         icon: Settings,
    532         active: systemSettings,
    533         onclick: (event: Event) => {
    534           event.preventDefault();
    535           m.route.set('/system-settings');
    536         },
    537       });
    538     }
    539 
    540     return (
    541       <AppShell
    542         topbar={
    543           <Topbar
    544             href={appUrl('/')}
    545             onclick={(event: Event) => {
    546               event.preventDefault();
    547               this.closeMobileNav();
    548               m.route.set('/');
    549             }}
    550             menuButton={
    551               <MobileNavToggle
    552                 expanded={this.mobileNavOpen}
    553                 onToggle={() => this.toggleMobileNav()}
    554               />
    555             }
    556           >
    557             <UserMenu
    558               name={user?.name || 'Administrator'}
    559               meta={user?.email || user?.preferred_username || 'Identity provider'}
    560               accountHref={`${this.authUrl}/app/account`}
    561               theme={this.theme}
    562               onCycleTheme={() => this.cycleTheme()}
    563               onSignOut={() => {
    564                 this.closeMobileNav();
    565                 adminSignOut().catch((error: Error) => {
    566                   this.error = error;
    567                   m.redraw();
    568                 });
    569               }}
    570             />
    571           </Topbar>
    572         }
    573         navLabel="Administration"
    574         navAriaLabel="Administration"
    575         navItems={navItems}
    576         accountPanel={
    577           <MobileNavAccount
    578             name={user?.name || 'Administrator'}
    579             meta={user?.email || user?.preferred_username || 'Identity provider'}
    580             accountHref={`${this.authUrl}/app/account`}
    581             theme={this.theme}
    582             onCycleTheme={() => this.cycleTheme()}
    583             onSignOut={() => {
    584               this.closeMobileNav();
    585               adminSignOut().catch((error: Error) => {
    586                 this.error = error;
    587                 m.redraw();
    588               });
    589             }}
    590           />
    591         }
    592         mobileNavOpen={this.mobileNavOpen}
    593         onMobileNavClose={() => this.closeMobileNav()}
    594       >
    595         {this.error ? (
    596           <div class="alert" role="alert">
    597             {this.error.message}
    598           </div>
    599         ) : null}
    600 
    601         {!user || routeGuardActive || this.accountRedirecting ? (
    602           <p class="note">Loading session</p>
    603         ) : realmsPath ? (
    604           <RealmsPage
    605             realms={this.realms}
    606             realmsError={this.realmsError}
    607             canCreateRealm={Boolean(this.canCreateRealm)}
    608             onAuthExpired={() => this.authExpired()}
    609             onRealmsChanged={() => this.reloadRealms()}
    610           />
    611         ) : clients && clientEdit ? (
    612           <ClientEditPage
    613             realmSlug={clientEdit.realmSlug}
    614             clientId={clientEdit.clientId}
    615             realms={this.realms}
    616             realmsError={this.realmsError}
    617             onAuthExpired={() => this.authExpired()}
    618           />
    619         ) : clients ? (
    620           <ClientsPage
    621             realmSlug={clientRealmSlug}
    622             realms={this.realms}
    623             realmsError={this.realmsError}
    624             onAuthExpired={() => this.authExpired()}
    625           />
    626         ) : users && globalUser ? (
    627           <GlobalUserPage
    628             userId={globalUser.userId}
    629             realmsError={this.realmsError}
    630             onAuthExpired={() => this.authExpired()}
    631           />
    632         ) : users && userDetail ? (
    633           <UserPage
    634             realmSlug={userDetail.realmSlug}
    635             userId={userDetail.userId}
    636             realms={this.realms}
    637             realmsError={this.realmsError}
    638             onAuthExpired={() => this.authExpired()}
    639           />
    640         ) : users ? (
    641           <UsersPage
    642             realmSlug={userRealmSlug}
    643             realms={this.realms}
    644             realmsError={this.realmsError}
    645             onAuthExpired={() => this.authExpired()}
    646             isSystemAdmin={Boolean(this.systemAdmin)}
    647             isGlobal={isGlobalUsers}
    648           />
    649         ) : systemSettings ? (
    650           <SystemSettingsPage onAuthExpired={() => this.authExpired()} />
    651         ) : hosts ? (
    652           <HostsPage
    653             realmSlug={hostsRealmSlug}
    654             realms={this.realms}
    655             realmsError={this.realmsError}
    656             canCreateRealm={Boolean(this.canCreateRealm)}
    657             onAuthExpired={() => this.authExpired()}
    658           />
    659         ) : emailDomains ? (
    660           <EmailDomainsPage
    661             realmSlug={emailDomainsRealmSlug}
    662             realms={this.realms}
    663             realmsError={this.realmsError}
    664             canCreateRealm={Boolean(this.canCreateRealm)}
    665             onAuthExpired={() => this.authExpired()}
    666           />
    667         ) : providers && providerEdit ? (
    668           <ProviderEditPage
    669             realmSlug={providerEdit.realmSlug}
    670             providerSlug={providerEdit.providerSlug}
    671             realms={this.realms}
    672             realmsError={this.realmsError}
    673             canCreateRealm={Boolean(this.canCreateRealm)}
    674             onAuthExpired={() => this.authExpired()}
    675           />
    676         ) : providers ? (
    677           <ProvidersPage
    678             realmSlug={providersRealmSlug}
    679             realms={this.realms}
    680             realmsError={this.realmsError}
    681             canCreateRealm={Boolean(this.canCreateRealm)}
    682             onAuthExpired={() => this.authExpired()}
    683           />
    684         ) : realmSettings ? (
    685           <SettingsPage
    686             realmSlug={settingsRealmSlug}
    687             realms={this.realms}
    688             realmsError={this.realmsError}
    689             canCreateRealm={Boolean(this.canCreateRealm)}
    690             onAuthExpired={() => this.authExpired()}
    691             onRealmsChanged={() => this.reloadRealms()}
    692           />
    693         ) : sessions ? (
    694           <SessionsPage
    695             realmSlug={realmSlug}
    696             realms={this.realms}
    697             realmsError={this.realmsError}
    698             onAuthExpired={() => this.authExpired()}
    699           />
    700         ) : (
    701           <OverviewPage user={user} />
    702         )}
    703       </AppShell>
    704     );
    705   },
    706 };
    707 
    708 export const AdminCallback: m.Component = {
    709   error: null as Error | null,
    710 
    711   oninit(this: any) {
    712     this.complete();
    713   },
    714 
    715   async complete(this: any) {
    716     const query = (m.route.get() || '').split('?')[1] || '';
    717     try {
    718       await completeAdminLogin(query);
    719       m.route.set('/');
    720     } catch (e) {
    721       this.error = e as Error;
    722       m.redraw();
    723     }
    724   },
    725 
    726   view(this: any) {
    727     return (
    728       <StatusPage
    729         title={this.error ? 'Sign-in failed' : 'Completing sign-in'}
    730         message={
    731           this.error
    732             ? this.error.message
    733             : 'Establishing the administrative session.'
    734         }
    735         error={Boolean(this.error)}
    736         action={
    737           this.error
    738             ? { href: appUrl('/'), label: 'Return to administration' }
    739             : undefined
    740         }
    741       />
    742     );
    743   },
    744 };