auth

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

login.tsx (11042B)


      1 import m from 'mithril';
      2 import {
      3   getClientDiscovery,
      4   getSession,
      5   resolveLogin,
      6   selectSession,
      7   signInPassword,
      8   type ClientDiscovery,
      9   type LoginResolution,
     10   type PasswordLoginResult,
     11   type SessionAccount,
     12 } from '../util/api';
     13 
     14 type Step = 'accounts' | 'identifier' | 'password' | 'oidc' | 'done';
     15 
     16 interface TextFieldAttrs {
     17   id: string;
     18   label: string;
     19   type?: string;
     20   value: string;
     21   autocomplete?: string;
     22   autofocus?: boolean;
     23   disabled?: boolean;
     24   oninput: (value: string) => void;
     25 }
     26 
     27 function queryParam(name: string) {
     28   const query = (m.route.get() || '').split('?')[1] || '';
     29   return new URLSearchParams(query).get(name);
     30 }
     31 
     32 function authorizeRoute() {
     33   const path = (m.route.get() || '').split('?')[0];
     34   return path.replace(/\/login$/, '/authorize');
     35 }
     36 
     37 const TextField: m.Component<TextFieldAttrs> = {
     38   view({ attrs }) {
     39     return (
     40       <div class="auth-field">
     41         <input
     42           class="auth-input"
     43           id={attrs.id}
     44           type={attrs.type || 'text'}
     45           value={attrs.value}
     46           placeholder=" "
     47           autocomplete={attrs.autocomplete}
     48           disabled={attrs.disabled}
     49           oninput={(e: Event) => attrs.oninput((e.target as HTMLInputElement).value)}
     50           oncreate={attrs.autofocus ? ({ dom }: any) => dom.focus() : undefined}
     51         />
     52         <label for={attrs.id}>{attrs.label}</label>
     53       </div>
     54     );
     55   },
     56 };
     57 
     58 export const Login: m.Component<{ realm?: string; clientId?: string }> = {
     59   realmSlug: null as string | null,
     60   clientId: null as string | null,
     61   discovery: null as ClientDiscovery | null,
     62   step: 'identifier' as Step,
     63   accounts: [] as SessionAccount[],
     64   identifier: '',
     65   password: '',
     66   longSession: false,
     67   provider: null as LoginResolution['provider'] | null,
     68   signedIn: null as PasswordLoginResult['user'] | null,
     69   error: null as Error | null,
     70   pending: false,
     71   reauth: false,
     72 
     73   oninit(this: any, vnode: any) {
     74     this.realmSlug = vnode.attrs.realm ?? null;
     75     this.clientId = vnode.attrs.clientId ?? null;
     76     this.reauth = queryParam('reauth') === '1';
     77     this.loadClient();
     78   },
     79 
     80   async loadClient(this: any) {
     81     this.error = null;
     82     try {
     83       const discovery = await getClientDiscovery(this.clientId);
     84       this.discovery = discovery;
     85       this.realmSlug = discovery.realm;
     86       this.clientId = discovery.client_id;
     87       document.title = discovery.display_name;
     88       await this.loadAccounts();
     89     } catch (e) {
     90       this.error = e as Error;
     91     }
     92     m.redraw();
     93   },
     94 
     95   async loadAccounts(this: any) {
     96     if (this.reauth) {
     97       this.accounts = [];
     98       return;
     99     }
    100     try {
    101       const session = await getSession();
    102       if (session.accounts.length >= 2) {
    103         this.accounts = session.accounts;
    104         this.step = 'accounts';
    105       }
    106     } catch {
    107       this.accounts = [];
    108     }
    109   },
    110 
    111   async submitIdentifier(this: any) {
    112     this.pending = true;
    113     this.error = null;
    114     try {
    115       const result = await resolveLogin(this.clientId, this.identifier);
    116       if (result.next === 'oidc' && result.provider) {
    117         this.provider = result.provider;
    118         this.step = 'oidc';
    119       } else {
    120         this.step = 'password';
    121       }
    122     } catch (e) {
    123       this.error = e as Error;
    124     }
    125     this.pending = false;
    126     m.redraw();
    127   },
    128 
    129   async submitPassword(this: any) {
    130     this.pending = true;
    131     this.error = null;
    132     try {
    133       const result = await signInPassword(
    134         this.clientId,
    135         this.identifier,
    136         this.password,
    137         this.longSession
    138       );
    139 
    140       if (result.pending_auth_request) {
    141         m.route.set(authorizeRoute());
    142         return;
    143       }
    144 
    145       if (this.clientId === 'admin') {
    146         m.route.set(this.realmSlug ? `/realms/${this.realmSlug}/admin` : '/admin');
    147         return;
    148       }
    149 
    150       this.signedIn = result.user;
    151       this.step = 'done';
    152       this.pending = false;
    153       m.redraw();
    154     } catch (e) {
    155       this.error = e as Error;
    156       this.pending = false;
    157       m.redraw();
    158     }
    159   },
    160 
    161   async selectAccount(this: any, account: SessionAccount) {
    162     this.pending = true;
    163     this.error = null;
    164     try {
    165       const result = await selectSession(account.public_id, this.clientId);
    166       if (result.pending_auth_request) {
    167         m.route.set(authorizeRoute());
    168         return;
    169       }
    170 
    171       if (this.clientId === 'admin') {
    172         m.route.set(this.realmSlug ? `/realms/${this.realmSlug}/admin` : '/admin');
    173         return;
    174       }
    175 
    176       this.signedIn = result.user;
    177       this.step = 'done';
    178     } catch (e) {
    179       this.error = e as Error;
    180     }
    181     this.pending = false;
    182     m.redraw();
    183   },
    184 
    185   differentAccount(this: any) {
    186     this.step = 'identifier';
    187     this.identifier = '';
    188     this.password = '';
    189     this.longSession = false;
    190     this.provider = null;
    191     this.error = null;
    192     m.redraw();
    193   },
    194 
    195   back(this: any) {
    196     this.step = 'identifier';
    197     this.password = '';
    198     this.longSession = false;
    199     this.provider = null;
    200     this.error = null;
    201     m.redraw();
    202   },
    203 
    204   backToAccounts(this: any) {
    205     this.step = 'accounts';
    206     this.error = null;
    207     m.redraw();
    208   },
    209 
    210   view(this: any) {
    211     const branding = this.discovery?.branding || {};
    212     const primary = typeof branding.primary_color === 'string' ? branding.primary_color : '#25A';
    213     const style = { '--realm-primary': primary } as any;
    214 
    215     if (!this.discovery && this.error) {
    216       return (
    217         <div class="auth-page" style={style}>
    218           <div class="auth-card">
    219             <h1>Sign in</h1>
    220             <p class="auth-error">{this.error.message}</p>
    221           </div>
    222         </div>
    223       );
    224     }
    225 
    226     const title = this.discovery?.display_name || 'Sign in';
    227 
    228     return (
    229       <div class="auth-page" style={style}>
    230         <div class="auth-card">
    231           {typeof branding.logo_url === 'string' && branding.logo_url ? (
    232             <img class="auth-logo" src={branding.logo_url} alt={title} />
    233           ) : null}
    234           <h1>{title}</h1>
    235 
    236           {this.step === 'accounts' ? this.renderAccounts() : null}
    237           {this.step === 'identifier' ? this.renderIdentifier() : null}
    238           {this.step === 'password' ? this.renderPassword() : null}
    239           {this.step === 'oidc' ? this.renderProvider() : null}
    240           {this.step === 'done' ? this.renderDone() : null}
    241         </div>
    242       </div>
    243     );
    244   },
    245 
    246   renderAccounts(this: any) {
    247     return (
    248       <div>
    249         <p class="auth-note">Choose an account to continue.</p>
    250         <div class="auth-accounts">
    251           {this.accounts.map((account: SessionAccount) => {
    252             const name = account.user.display_name || account.user.username;
    253             const secondary =
    254               account.user.display_name && account.user.display_name !== account.user.username
    255                 ? account.user.username
    256                 : null;
    257             return (
    258               <button
    259                 class="auth-account"
    260                 type="button"
    261                 disabled={this.pending}
    262                 onclick={() => this.selectAccount(account)}
    263               >
    264                 <span class="auth-account-name">{name}</span>
    265                 {secondary ? <span class="auth-account-username">{secondary}</span> : null}
    266               </button>
    267             );
    268           })}
    269         </div>
    270         {this.error ? <p class="auth-error">{this.error.message}</p> : null}
    271         <div class="auth-actions">
    272           <button class="auth-link" type="button" onclick={() => this.differentAccount()}>
    273             Different account
    274           </button>
    275         </div>
    276       </div>
    277     );
    278   },
    279 
    280   renderIdentifier(this: any) {
    281     return (
    282       <form
    283         onsubmit={(e: Event) => {
    284           e.preventDefault();
    285           if (!this.pending && this.identifier.trim()) this.submitIdentifier();
    286         }}
    287       >
    288         {this.reauth ? (
    289           <p class="auth-note">Confirm your password to continue.</p>
    290         ) : null}
    291         <TextField
    292           id="identifier"
    293           label="Email or username"
    294           value={this.identifier}
    295           autocomplete="username"
    296           autofocus
    297           disabled={this.pending}
    298           oninput={(value: string) => {
    299             this.identifier = value;
    300           }}
    301         />
    302         {this.error ? <p class="auth-error">{this.error.message}</p> : null}
    303         <div class="auth-actions">
    304           {!this.reauth && this.accounts.length >= 2 ? (
    305             <button class="auth-link" type="button" onclick={() => this.backToAccounts()}>
    306               Back to accounts
    307             </button>
    308           ) : null}
    309           <button class="auth-button" type="submit" disabled={this.pending || !this.identifier.trim()}>
    310             {this.pending ? 'Checking' : 'Next'}
    311           </button>
    312         </div>
    313       </form>
    314     );
    315   },
    316 
    317   renderPassword(this: any) {
    318     return (
    319       <form
    320         onsubmit={(e: Event) => {
    321           e.preventDefault();
    322           if (!this.pending) this.submitPassword();
    323         }}
    324       >
    325         <p class="auth-identifier">{this.identifier}</p>
    326         <TextField
    327           id="password"
    328           label="Password"
    329           type="password"
    330           value={this.password}
    331           autocomplete="current-password"
    332           autofocus
    333           disabled={this.pending}
    334           oninput={(value: string) => {
    335             this.password = value;
    336           }}
    337         />
    338         {this.discovery?.allow_session_duration_choice !== false ? (
    339           <label class="auth-choice">
    340             <input
    341               type="checkbox"
    342               checked={this.longSession}
    343               disabled={this.pending}
    344               onchange={(e: Event) => {
    345                 this.longSession = (e.target as HTMLInputElement).checked;
    346               }}
    347             />
    348             <span>Keep me signed in</span>
    349           </label>
    350         ) : null}
    351         {this.error ? <p class="auth-error">{this.error.message}</p> : null}
    352         <div class="auth-actions">
    353           <button class="auth-link" type="button" onclick={() => this.back()}>
    354             Back
    355           </button>
    356           <button class="auth-button" type="submit" disabled={this.pending || !this.password}>
    357             {this.pending ? 'Signing in' : 'Sign in'}
    358           </button>
    359         </div>
    360       </form>
    361     );
    362   },
    363 
    364   renderProvider(this: any) {
    365     const provider = this.provider;
    366     return (
    367       <div>
    368         <p class="auth-identifier">{this.identifier}</p>
    369         <p class="auth-note">
    370           {provider
    371             ? `This account signs in with ${provider.display_name}.`
    372             : 'This account signs in with an identity provider.'}
    373         </p>
    374         <div class="auth-actions">
    375           <button class="auth-link" type="button" onclick={() => this.back()}>
    376             Back
    377           </button>
    378           <button class="auth-button" type="button" disabled>
    379             Continue
    380           </button>
    381         </div>
    382       </div>
    383     );
    384   },
    385 
    386   renderDone(this: any) {
    387     const user = this.signedIn;
    388     return (
    389       <div>
    390         <p class="auth-note">Signed in as {user?.display_name || user?.username}</p>
    391       </div>
    392     );
    393   },
    394 };