/** * Members and roles (APP-1.0-PLAN §10, decision 7). Everyone who signs in is a Member; roles are the * App's own, keyed by the account's `sub` in the church's Accounts, and every one needs a 2FA * sign-in to use what it adds (§2). * * Owner everything, including who is Owner * Church admin everything but Owners (can't make one, or change or take an Owner's roles) * Others can't manage roles * * Someone who hasn't used the App yet is added by email: Accounts makes them an account if they * have none (`people.ensure`, with a "choose your password" email). Nobody changes their own * roles, so the App is never left without an Owner by accident. */ import { z } from 'zod'; import type { Ctx } from '../context.js'; import type { AppRole, Prisma } from '../generated/prisma/client.js'; import { accounts } from '../auth/accounts.js'; import { ROLES } from '../auth/sessions.js'; import { ApiError, parse } from '../http.js'; import { audit } from '../lib/audit.js'; type Who = { id: string; roles: AppRole[]; ip: string | null }; const roleList = z.array(z.enum(ROLES as [AppRole, ...AppRole[]])).max(ROLES.length).transform((r) => [...new Set(r)]); export const addBody = z.object({ name: z.string().trim().min(1).max(200), email: z.email().trim().toLowerCase().max(254), roles: roleList, }).strict(); export const rolesBody = z.object({ roles: roleList }).strict(); const PAGE = 50; /** May `by` change someone with `current` roles to `next`? Throws why not. */ function mayChange(by: Who, current: AppRole[], next: AppRole[]) { const owner = by.roles.includes('owner'); if (!owner && !by.roles.includes('church_admin')) throw new ApiError(403, 'FORBIDDEN', 'Only an Owner or Church admin can give roles.'); if (!owner && (current.includes('owner') || next.includes('owner'))) throw new ApiError(403, 'OWNERS_ONLY', 'Only an Owner can make someone an Owner, or change an Owner\'s roles.'); } /** Members, with roles first (those with one), then by name; `q` searches names and emails. */ export async function listMembers(ctx: Ctx, opts: { q?: string; role?: string; page?: number }) { const q = opts.q?.trim().slice(0, 100); const where: Prisma.MemberWhereInput = { ...(q ? { OR: [{ name: { contains: q, mode: 'insensitive' } }, { email: { contains: q, mode: 'insensitive' } }] } : {}), ...(opts.role === 'any' ? { roles: { isEmpty: false } } : opts.role && (ROLES as readonly string[]).includes(opts.role) ? { roles: { has: opts.role as AppRole } } : {}), }; const page = Math.max(1, Math.floor(opts.page ?? 1)); const [total, rows, withRoles] = await Promise.all([ ctx.db.member.count({ where }), ctx.db.member.findMany({ where, orderBy: [{ name: 'asc' }], skip: (page - 1) * PAGE, take: PAGE }), ctx.db.member.findMany({ where: { roles: { isEmpty: false } }, select: { roles: true } }), ]); return { total, page, pageSize: PAGE, /** How many hold each role (the page's header). */ roleCounts: Object.fromEntries(ROLES.map((r) => [r, withRoles.filter((m) => m.roles.includes(r)).length])), members: rows.map((m) => ({ id: m.id, name: m.name, email: m.email, roles: m.roles, hasPhone: !!m.phone, whatsappStopped: m.whatsappOptedOut, lastActiveAt: m.lastActiveAt?.toISOString() ?? null, lastSignInAt: m.lastSignInAt?.toISOString() ?? null, since: m.createdAt.toISOString(), })), }; } export async function setRoles(ctx: Ctx, id: string, body: unknown, by: Who) { const { roles } = parse(rolesBody, body); if (id === by.id) throw new ApiError(400, 'SELF', 'You can\'t change your own roles. Ask another Owner or Church admin.'); const member = await ctx.db.member.findUnique({ where: { id } }); if (!member) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such member.'); mayChange(by, member.roles, roles); const sorted = ROLES.filter((r) => roles.includes(r)); await ctx.db.member.update({ where: { id }, data: { roles: sorted } }); await audit(ctx, { actorId: by.id, actorRole: by.roles.join(','), action: 'member_roles_changed', targetType: 'member', targetId: id, metadata: { from: member.roles, to: sorted }, ip: by.ip }); return { id, roles: sorted }; } /** Adds someone by email with roles: their account at Accounts (made if they have none), then here. */ export async function addMember(ctx: Ctx, body: unknown, by: Who) { const p = parse(addBody, body); if (!p.roles.length) throw new ApiError(400, 'VALIDATION', 'Choose at least one role: everyone who signs in is a Member already.', { roles: 'Choose a role' }); const known = await ctx.db.member.findFirst({ where: { email: p.email } }); mayChange(by, known?.roles ?? [], p.roles); const reply = await (await accounts(ctx)).request<{ sub: string; created: boolean; emailSent?: boolean }>({ type: 'people.ensure', actor: by.id, name: p.name, email: p.email, phone: null, returnUrl: `${ctx.config.publicUrl}/admin`, }); if (reply.sub === by.id) throw new ApiError(400, 'SELF', 'You can\'t change your own roles. Ask another Owner or Church admin.'); const existing = await ctx.db.member.findUnique({ where: { id: reply.sub } }); if (existing) mayChange(by, existing.roles, p.roles); const roles = ROLES.filter((r) => p.roles.includes(r) || existing?.roles.includes(r)); const member = existing ? await ctx.db.member.update({ where: { id: existing.id }, data: { roles } }) : await ctx.db.member.create({ data: { id: reply.sub, name: p.name, email: p.email, roles } }); await audit(ctx, { actorId: by.id, actorRole: by.roles.join(','), action: 'member_added', targetType: 'member', targetId: member.id, metadata: { roles, newAccount: reply.created, before: existing?.roles ?? null }, ip: by.ip }); return { id: member.id, roles, newAccount: reply.created, emailSent: reply.emailSent ?? null, alreadyMember: !!existing }; }