auth

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

system-clients.js (1709B)


      1 import { isRealmOwner, isSystemAdmin } from './policy.js';
      2 import { openRealmDatabase, realmMetadata } from './realm.js';
      3 import { getMembership, getUserRoles } from './users.js';
      4 
      5 export async function listAdminRealms(systemDb, user) {
      6   if (!user || user.status !== 'active') return [];
      7 
      8   const realms = await systemDb.all(
      9     'SELECT id, slug, db_file, owner_user_id, created_at FROM realms ORDER BY slug ASC'
     10   );
     11   if (isSystemAdmin(user)) return realms;
     12 
     13   const accessible = [];
     14   for (const realm of realms) {
     15     if (isRealmOwner(user, realm)) {
     16       accessible.push(realm);
     17       continue;
     18     }
     19 
     20     try {
     21       const db = await openRealmDatabase(realm);
     22       const membership = await getMembership(db, user.id);
     23       if (membership?.status !== 'active') continue;
     24       const roles = await getUserRoles(db, user.id);
     25       if (roles.includes('realm-admin')) accessible.push(realm);
     26     } catch {
     27       continue;
     28     }
     29   }
     30   return accessible;
     31 }
     32 
     33 export async function listAdminRealmOptions(systemDb, user) {
     34   const realms = await listAdminRealms(systemDb, user);
     35   const options = [];
     36   for (const realm of realms) {
     37     try {
     38       const metadata = await realmMetadata(realm);
     39       options.push({
     40         slug: realm.slug,
     41         display_name: metadata.display_name,
     42       });
     43     } catch {
     44       continue;
     45     }
     46   }
     47   return options;
     48 }
     49 
     50 export async function canUseSystemClient(systemDb, { user, client }) {
     51   if (!user || user.status !== 'active' || !client?.enabled) return false;
     52   if (client.client_id === 'account') return true;
     53   if (client.client_id !== 'admin') return false;
     54   if (isSystemAdmin(user)) return true;
     55   return (await listAdminRealms(systemDb, user)).length > 0;
     56 }