auth

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

show.js (1849B)


      1 import { app } from '../../app.js';
      2 import { resolveHostContext } from '../../lib/host-context.js';
      3 import { HttpError } from '../../lib/http/http-error.js';
      4 import { getSystemDatabase, openRealmDatabase, realmMetadata } from '../../lib/realm.js';
      5 import { isSystemAdmin } from '../../lib/policy.js';
      6 import { authenticateRequest, listSessionAccounts } from '../../lib/session.js';
      7 
      8 export default {
      9   method: 'get',
     10   path: '/api/v1/session',
     11   name: 'session.show',
     12   async handler(req, res) {
     13     const hostContext = await resolveHostContext(req, {
     14       publicUrl: app.config.server.public_url,
     15     });
     16     const realmDb = hostContext.realm ? await openRealmDatabase(hostContext.realm) : null;
     17     const metadata = hostContext.realm ? await realmMetadata(hostContext.realm) : null;
     18     const auth = await authenticateRequest({
     19       systemDb: getSystemDatabase(),
     20       realmDb,
     21       req,
     22       res,
     23       context: hostContext,
     24     });
     25 
     26     if (!auth) {
     27       throw new HttpError(401, 'not_authenticated', 'Not signed in');
     28     }
     29     if (
     30       hostContext.mode !== 'canonical' &&
     31       !isSystemAdmin(auth.user) &&
     32       (!auth.membership || auth.membership.status !== 'active')
     33     ) {
     34       throw new HttpError(401, 'not_authenticated', 'Not signed in');
     35     }
     36 
     37     return new app.HttpOk({
     38       scope: {
     39         type: auth.session.scope_type,
     40         host: auth.session.scope_host,
     41         realm_id: auth.session.realm_id,
     42         client_id: auth.session.client_id,
     43       },
     44       realm: metadata,
     45       user: {
     46         id: auth.user.id,
     47         username: auth.user.username,
     48         display_name: auth.user.display_name,
     49       },
     50       roles: auth.roles,
     51       is_system_admin: isSystemAdmin(auth.user),
     52       expires_at: auth.session.expires_at,
     53       accounts: await listSessionAccounts(getSystemDatabase(), auth.group),
     54     });
     55   },
     56 };