auth

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

password.js (6119B)


      1 import { app } from '../../app.js';
      2 import { resolveClientForHost, resolveHostContext } from '../../lib/host-context.js';
      3 import { HttpError } from '../../lib/http/http-error.js';
      4 import { findManagedProviderForUser, resolveLogin } from '../../lib/login.js';
      5 import { getClient, getSystemClient } from '../../lib/oidc/clients.js';
      6 import {
      7   getAuthRequest,
      8   readAuthRequestId,
      9   selectAuthRequestAccount,
     10 } from '../../lib/oidc/requests.js';
     11 import { verifyDummyPassword, verifyPassword } from '../../lib/password.js';
     12 import { canUseClient } from '../../lib/policy.js';
     13 import { getSystemDatabase, openRealmDatabase, realmMetadata } from '../../lib/realm.js';
     14 import {
     15   LONG_SESSION_TTL,
     16   SHORT_SESSION_TTL,
     17   createHostSession,
     18   purgeExpiredSessions,
     19   reauthenticateSession,
     20   requestIp,
     21   requestToken,
     22   setSessionCookie,
     23 } from '../../lib/session.js';
     24 import { canUseSystemClient } from '../../lib/system-clients.js';
     25 import {
     26   findUserByIdentifier,
     27   getMembership,
     28   getPasswordCredential,
     29   getUserRoles,
     30   updateLastLogin,
     31 } from '../../lib/users.js';
     32 
     33 export default {
     34   method: 'post',
     35   path: '/api/v1/login/password',
     36   name: 'login.password',
     37   async handler(req, res) {
     38     const body = req.body || {};
     39     if (typeof body.identifier !== 'string') {
     40       throw new HttpError(400, 'invalid_request', 'identifier is required');
     41     }
     42     if (typeof body.password !== 'string') {
     43       throw new HttpError(400, 'invalid_request', 'password is required');
     44     }
     45     if (body.password.length > 1024) {
     46       throw new HttpError(400, 'invalid_request', 'password is too long');
     47     }
     48     if (typeof body.client_id !== 'string') {
     49       throw new HttpError(400, 'invalid_request', 'client_id is required');
     50     }
     51     if (body.long_session != null && typeof body.long_session !== 'boolean') {
     52       throw new HttpError(400, 'invalid_request', 'long_session must be a boolean');
     53     }
     54 
     55     const hostContext = await resolveHostContext(req, {
     56       publicUrl: app.config.server.public_url,
     57     });
     58     const target = await resolveClientForHost(hostContext, body.client_id);
     59     const { realm, clientId, systemClient } = target;
     60     const metadata = realm ? await realmMetadata(realm) : null;
     61     const realmDb = realm ? await openRealmDatabase(realm) : null;
     62     const systemDb = getSystemDatabase();
     63     const client = systemClient
     64       ? getSystemClient(clientId)
     65       : await getClient(realmDb, clientId);
     66     if (!client || !client.enabled) {
     67       throw new HttpError(404, 'unknown_client', 'Unknown client');
     68     }
     69 
     70     if (body.identifier.includes('@')) {
     71       const resolution = await resolveLogin({ identifier: body.identifier });
     72       if (resolution.next !== 'password') {
     73         throw new HttpError(403, 'provider_required', 'This account must sign in with its identity provider');
     74       }
     75     }
     76 
     77     const user = await findUserByIdentifier(systemDb, body.identifier);
     78     const credential = user ? await getPasswordCredential(systemDb, user.id) : null;
     79     const membership = user && realmDb ? await getMembership(realmDb, user.id) : null;
     80     const roles = user && realmDb ? await getUserRoles(realmDb, user.id) : [];
     81     const store = systemClient ? systemDb : realmDb;
     82     const pendingId = readAuthRequestId(req, target);
     83     const pending = pendingId ? await getAuthRequest(store, pendingId) : null;
     84     const pendingClient = pending && !pending.completed_at && pending.client_id === client.client_id;
     85 
     86     if (!credential) {
     87       await verifyDummyPassword(body.password);
     88       throw new HttpError(401, 'invalid_credentials', 'Invalid credentials');
     89     }
     90 
     91     const valid = await verifyPassword(body.password, credential.secret_hash);
     92     if (!valid) {
     93       throw new HttpError(401, 'invalid_credentials', 'Invalid credentials');
     94     }
     95 
     96     if (!user || user.status !== 'active') {
     97       throw new HttpError(401, 'invalid_credentials', 'Invalid credentials');
     98     }
     99 
    100     let allowed;
    101     if (systemClient) {
    102       allowed = await canUseSystemClient(systemDb, { user, client });
    103     } else {
    104       const allowedByPolicy = canUseClient({
    105         user,
    106         membership,
    107         roles,
    108         client,
    109         realm,
    110       });
    111       const member = membership && membership.status === 'active';
    112       const publicNonMember = client.access_mode === 'public' && pendingClient;
    113       allowed =
    114         allowedByPolicy &&
    115         (member || publicNonMember || user.is_system_admin);
    116     }
    117 
    118     if (!allowed) {
    119       throw new HttpError(401, 'invalid_credentials', 'Invalid credentials');
    120     }
    121 
    122     if (!body.identifier.includes('@')) {
    123       const provider = await findManagedProviderForUser(systemDb, user);
    124       if (provider && !provider.enabled) {
    125         throw new HttpError(409, 'provider_disabled', 'The identity provider for this account is unavailable');
    126       }
    127       if (provider) {
    128         throw new HttpError(403, 'provider_required', 'This account must sign in with its identity provider');
    129       }
    130     }
    131 
    132     const longSession =
    133       body.long_session === true &&
    134       (metadata?.allow_session_duration_choice ?? true);
    135     const ttl = longSession ? LONG_SESSION_TTL : SHORT_SESSION_TTL;
    136 
    137     await purgeExpiredSessions(systemDb);
    138     const { token, session } = await createHostSession(systemDb, {
    139       context: hostContext,
    140       token: requestToken(req),
    141       userId: user.id,
    142       ttl,
    143       userAgent: req.headers['user-agent'] || null,
    144       ip: requestIp(req),
    145     });
    146     const authTime = await reauthenticateSession(systemDb, {
    147       sessionId: session.id,
    148       realmId: realm?.id ?? null,
    149     });
    150     setSessionCookie(res, req, token, session.ttl);
    151     if (pendingClient && pending) {
    152       await selectAuthRequestAccount(store, pending.id, {
    153         userId: user.id,
    154         sessionId: session.id,
    155         authTime,
    156       });
    157     }
    158     await updateLastLogin(systemDb, user.id);
    159 
    160     return new app.HttpOk({
    161       realm: metadata,
    162       user: {
    163         id: user.id,
    164         username: user.username,
    165         display_name: user.display_name,
    166       },
    167       expires_at: session.expires_at,
    168       pending_auth_request: Boolean(pendingClient),
    169     });
    170   },
    171 };