Spaces:
Running
Running
Z User
feat(admin): one-shot bulk approve/reject + professional acceptance notification for approved users
264507b Download api/admin-users.ts from ahmdelbaz28/AHMDRTAP: direct link, hf CLI and curl.
- Browser
- Download file 21.7 kB
-
https://huggingface.co/spaces/ahmdelbaz28/AHMDRTAP/resolve/main/api/admin-users.ts
- Command line
-
hf download hf://spaces/ahmdelbaz28/AHMDRTAP/api/admin-users.ts
-
curl -L -o admin-users.ts https://huggingface.co/spaces/ahmdelbaz28/AHMDRTAP/resolve/main/api/admin-users.ts
21.7 kB
| /** | |
| * ADMIN USERS — User management endpoints | |
| * | |
| * Procedures: users (paginated list), updateUserRole, | |
| * pendingApprovals / approveUser / rejectUser / resendApprovalEmail | |
| * (the ADMIN APPROVAL GATE queue, owner directive 2026-11-24) | |
| */ | |
| import { users } from "@db/schema"; | |
| import { TRPCError } from "@trpc/server"; | |
| import { and, asc, count, desc, eq, inArray, sql } from "drizzle-orm"; | |
| import { z } from "zod"; | |
| import type { SafeUser } from "./context"; | |
| import { evictAllUserAuthCache, evictUserAuthCache } from "./context"; | |
| import { | |
| adminAlertEmail, | |
| bulkDecisionInputSchema, | |
| decideApproval, | |
| notifyAdminsOfRegistration, | |
| summarizeBulkResults, | |
| } from "./lib/approval"; | |
| import type { ApprovalAction } from "./lib/approval"; | |
| import { getApprovalGateConfig } from "./lib/approval-gate-config"; | |
| import { maybeSendWelcomeEmail } from "./lib/email-drip"; | |
| import { env } from "./lib/env"; | |
| import { logger, maskEmail } from "./lib/logger"; | |
| import { adminMutation, adminQuery } from "./middleware"; | |
| import { getDb } from "./queries/connection"; | |
| import { invalidateSettingsCache } from "./lib/cache"; | |
| /** | |
| * Shared bulk runner — one implementation behind bulkApproveUsers / | |
| * bulkRejectUsers so the two buttons stay perfectly symmetrical. | |
| * | |
| * - Duplicate ids are collapsed (the UI cannot produce them, but the API | |
| * must stay idempotent under a retrying client). | |
| * - Emails are snapshotted BEFORE deciding (approve needs them for the | |
| * deferred welcome drip, mirroring the single approveUser path). | |
| * - Per-row decisions run through decideApproval — the SAME state machine | |
| * as the single actions: approve only lifts pending rows; reject skips | |
| * admins (protected) and already-rejected rows; the acceptance notice | |
| * (email + in-app) fires per decided row from inside decideApproval. | |
| * - Independent rows: one bad row degrades to a skip entry, never aborts | |
| * the batch. | |
| */ | |
| async function runBulkDecision(action: ApprovalAction, userIds: number[], adminUserId: number) { | |
| const db = getDb(); | |
| const unique = [...new Set(userIds)]; | |
| const targets = await db | |
| .select({ id: users.id, username: users.username, name: users.name, email: users.email }) | |
| .from(users) | |
| .where(inArray(users.id, unique)); | |
| const targetById = new Map(targets.map((t) => [t.id, t])); | |
| const entries = await Promise.all( | |
| unique.map(async (userId) => ({ | |
| userId, | |
| result: await decideApproval({ userId, action, adminUserId, source: "dashboard" }), | |
| })), | |
| ); | |
| const summary = summarizeBulkResults(entries); | |
| if (action === "approve") { | |
| for (const decidedId of summary.decidedIds) { | |
| const target = targetById.get(decidedId); | |
| if (target?.email) { | |
| void maybeSendWelcomeEmail(decidedId, target.username, target.email, target.name || target.username); | |
| } | |
| } | |
| } | |
| logger.info("[Admin] bulk approval decision applied", { | |
| action, | |
| adminUserId, | |
| requested: unique.length, | |
| decided: summary.decided, | |
| skipped: summary.skipped.length, | |
| }); | |
| return summary; | |
| } | |
| export const adminUsersProcedures = { | |
| // Users list — used by Admin.tsx frontend (trpc.admin.users.useQuery) | |
| users: adminQuery | |
| .input(z.object({ page: z.number().int().min(1).default(1), limit: z.number().int().min(1).max(100).default(20) }).optional()) | |
| .query(async ({ input }) => { | |
| const db = getDb(); | |
| const page = input?.page ?? 1; | |
| const limit = input?.limit ?? 20; | |
| const offset = (page - 1) * limit; | |
| const [[{ total }], allUsers] = await Promise.all([ | |
| db.select({ total: count() }).from(users), | |
| db.select({ | |
| id: users.id, | |
| username: users.username, | |
| name: users.name, | |
| email: users.email, | |
| avatar: users.avatar, | |
| role: users.role, | |
| preferredLanguage: users.preferredLanguage, | |
| // ✅ SECURITY FIX (audit run-2): SafeUser is now a curated Pick<> that | |
| // includes emailVerifiedAt — the admin list select must carry it for | |
| // the `as SafeUser[]` cast to hold. | |
| emailVerifiedAt: users.emailVerifiedAt, | |
| // ✅ ROOT-CURE (owner report 2026-11-26, "user says the admin confirmed | |
| // his email but the site still asks him to log in every time"): the | |
| // all-users table previously had NO gate column — a pending user looked | |
| // identical to an approved one, while emailVerifiedAt ('verified ✓') | |
| // actively suggested the account was done. The owner could not see | |
| // WHO was blocked or WHY. The REAL gate state now rides with every | |
| // row so the dashboard surfaces it (see Admin.tsx status column). | |
| approvalStatus: users.approvalStatus, | |
| approvalDecidedAt: users.approvalDecidedAt, | |
| createdAt: users.createdAt, | |
| updatedAt: users.updatedAt, | |
| lastSignInAt: users.lastSignInAt, | |
| }) | |
| .from(users) | |
| .orderBy(desc(users.createdAt)) | |
| .limit(limit) | |
| .offset(offset), | |
| ]); | |
| return { items: allUsers as SafeUser[], total: total ?? 0 }; | |
| }), | |
| updateUserRole: adminMutation | |
| .input(z.object({ userId: z.number().int().positive(), role: z.enum(["user", "admin"]) })) | |
| .mutation(async ({ input }) => { | |
| const db = getDb(); | |
| const [user] = await db | |
| .select({ id: users.id, role: users.role, tokenVersion: users.tokenVersion }) | |
| .from(users) | |
| .where(eq(users.id, input.userId)) | |
| .limit(1); | |
| if (!user) throw new TRPCError({ code: "NOT_FOUND", message: "User not found" }); | |
| if (user.role === input.role) return { success: true }; // no-op | |
| if (input.role === "user" && user.role === "admin") { | |
| // ✅ SECURITY FIX (audit run-1, fp admin-users.updateUserRole | |
| // .last-admin-guard.race-to-zero-admins): the old guard was a separate | |
| // SELECT-then-act — two concurrent demotes both read "admins = 2" and | |
| // BOTH demoted, leaving zero administrators, and ADMIN_RECOVERY cannot | |
| // restore the role (it has nobody to promote). The guard now travels | |
| // WITH the write: one conditional UPDATE that only fires while more | |
| // than one admin remains. MySQL forbids selecting the target table in | |
| // a subquery (ERROR 1093) — the derived table materializes it. | |
| // Concurrent demotes serialize on the row lock: the winner affects 1 | |
| // row, the loser 0 rows → clean BAD_REQUEST, never zero admins. | |
| const [updateResult] = await db | |
| .update(users) | |
| .set({ role: input.role, tokenVersion: user.tokenVersion + 1, updatedAt: new Date() }) | |
| .where( | |
| and( | |
| eq(users.id, input.userId), | |
| eq(users.role, "admin"), | |
| sql`(SELECT adminCount FROM (SELECT COUNT(*) AS adminCount FROM users WHERE role = 'admin') AS adminGuard) > 1`, | |
| ), | |
| ); | |
| const affected = Number((updateResult as unknown as { affectedRows?: number }).affectedRows ?? 0); | |
| if (affected === 0) { | |
| // Zero rows: either a concurrent demote already removed this admin | |
| // (intent satisfied — success) or this IS the last admin (guard). | |
| const [fresh] = await db | |
| .select({ role: users.role }) | |
| .from(users) | |
| .where(eq(users.id, input.userId)) | |
| .limit(1); | |
| if (fresh && fresh.role !== "admin") { | |
| evictUserAuthCache(user.id); | |
| return { success: true }; | |
| } | |
| throw new TRPCError({ | |
| code: "BAD_REQUEST", | |
| message: "لا يمكن إزالة صلاحية المشرف الأخير — يجب أن يبقى مشرف واحد على الأقل", | |
| }); | |
| } | |
| // ✅ INSTANT EFFECT: tokenVersion bump (in the same SET) kills ALL of | |
| // the target's existing sessions immediately, and the auth cache is | |
| // evicted so even the 30s user-cache window cannot serve the old role. | |
| evictUserAuthCache(user.id); | |
| return { success: true }; | |
| } | |
| // ✅ INSTANT EFFECT (dashboard audit 2026-11-15): bump tokenVersion so a | |
| // role change kills ALL of the target's existing sessions immediately | |
| // (a demoted admin is locked out on their very next request instead of | |
| // riding a stale session for up to the token lifetime), and evict the | |
| // auth cache so even the 30s user-cache window cannot serve the old role. | |
| await db | |
| .update(users) | |
| .set({ role: input.role, tokenVersion: user.tokenVersion + 1, updatedAt: new Date() }) | |
| .where(eq(users.id, input.userId)); | |
| evictUserAuthCache(user.id); | |
| return { success: true }; | |
| }), | |
| // ─── ADMIN APPROVAL GATE (owner directive, 2026-11-24) ──────────────────── | |
| // The owner's authority over who may enter the platform: a live queue of | |
| // pending registrations + approve/reject actions. Reject also revokes any | |
| // live session (tokenVersion bump inside decideApproval) — "ألغاء دخول أي | |
| // حد في أي وقت" works even for accounts that are logged in right now. | |
| pendingApprovals: adminQuery | |
| .query(async () => { | |
| const db = getDb(); | |
| const [rows, [{ pending }]] = await Promise.all([ | |
| db | |
| .select({ | |
| id: users.id, | |
| username: users.username, | |
| name: users.name, | |
| email: users.email, | |
| role: users.role, | |
| preferredLanguage: users.preferredLanguage, | |
| createdAt: users.createdAt, | |
| // ✅ ROOT-CURE (2026-11-26): the queue shows whether the registrant | |
| // already completed THEIR part (email confirmation) — the only thing | |
| // left is the owner's decision, so "email confirmed but can't enter" | |
| // reports become one-glance diagnosable. | |
| emailVerifiedAt: users.emailVerifiedAt, | |
| }) | |
| .from(users) | |
| .where(eq(users.approvalStatus, "pending")) | |
| .orderBy(asc(users.createdAt)) | |
| .limit(200), | |
| db.select({ pending: count() }).from(users).where(eq(users.approvalStatus, "pending")), | |
| ]); | |
| return { items: rows, total: pending ?? 0 }; | |
| }), | |
| approveUser: adminMutation | |
| .input(z.object({ userId: z.number().int().positive() })) | |
| .mutation(async ({ ctx, input }) => { | |
| // Snapshot the email BEFORE the decision — approveUser also kicks off | |
| // the welcome drip (deferred from registration while the account was | |
| // locked out). | |
| const db = getDb(); | |
| const [target] = await db | |
| .select({ username: users.username, name: users.name, email: users.email, role: users.role, approvalStatus: users.approvalStatus }) | |
| .from(users) | |
| .where(eq(users.id, input.userId)) | |
| .limit(1); | |
| if (!target) throw new TRPCError({ code: "NOT_FOUND", message: "User not found" }); | |
| const result = await decideApproval({ | |
| userId: input.userId, | |
| action: "approve", | |
| adminUserId: ctx.user.id, | |
| source: "dashboard", | |
| }); | |
| if (!result.ok) { | |
| if (result.reason === "not_found") throw new TRPCError({ code: "NOT_FOUND", message: "User not found" }); | |
| throw new TRPCError({ code: "BAD_REQUEST", message: "هذا الحساب ليس في انتظار الموافقة" }); | |
| } | |
| // Deferred welcome drip (best-effort) — the account is now usable. | |
| if (target.email) { | |
| void maybeSendWelcomeEmail(input.userId, target.username, target.email, target.name || target.username); | |
| } | |
| return { success: true, status: result.status }; | |
| }), | |
| rejectUser: adminMutation | |
| .input(z.object({ userId: z.number().int().positive() })) | |
| .mutation(async ({ ctx, input }) => { | |
| const result = await decideApproval({ | |
| userId: input.userId, | |
| action: "reject", | |
| adminUserId: ctx.user.id, | |
| source: "dashboard", | |
| }); | |
| if (!result.ok) { | |
| if (result.reason === "not_found") throw new TRPCError({ code: "NOT_FOUND", message: "User not found" }); | |
| throw new TRPCError({ code: "BAD_REQUEST", message: "لا يمكن رفض هذا الحساب في حالته الحالية (حسابات المشرفين محمية)" }); | |
| } | |
| return { success: true, status: result.status }; | |
| }), | |
| // ── ✅ BULK DECISIONS (owner directive, 2026-12-01): "امكانية ان اقدر | |
| // اختار مجموعه كبيرة اللي عاوزها وعملها موافقة مرة واحدة ... واختيار كمية | |
| // كبيرة ارفضهم مرة واحدة". ONE call decides the whole batch through the | |
| // SAME decideApproval state machine per row (no duplicated security | |
| // logic): approve only moves pending rows; reject skips admins and | |
| // already-rejected rows. Decisions inside a batch are independent — one | |
| // bad row never aborts the others. The per-user acceptance notification | |
| // (email + in-app stream) rides decideApproval itself, so a 150-account | |
| // batch fans out exactly like 150 single approvals. The deferred welcome | |
| // drip mirrors the single approveUser path. | |
| bulkApproveUsers: adminMutation | |
| .input(z.object({ userIds: bulkDecisionInputSchema })) | |
| .mutation(async ({ ctx, input }) => { | |
| const summary = await runBulkDecision("approve", input.userIds, ctx.user.id); | |
| return { | |
| success: true, | |
| action: "approve" as const, | |
| total: summary.decided + summary.skipped.length, | |
| decided: summary.decided, | |
| decidedIds: summary.decidedIds, | |
| skipped: summary.skipped, | |
| }; | |
| }), | |
| bulkRejectUsers: adminMutation | |
| .input(z.object({ userIds: bulkDecisionInputSchema })) | |
| .mutation(async ({ ctx, input }) => { | |
| const summary = await runBulkDecision("reject", input.userIds, ctx.user.id); | |
| return { | |
| success: true, | |
| action: "reject" as const, | |
| total: summary.decided + summary.skipped.length, | |
| decided: summary.decided, | |
| decidedIds: summary.decidedIds, | |
| skipped: summary.skipped, | |
| }; | |
| }), | |
| resendApprovalEmail: adminMutation | |
| .input(z.object({ userId: z.number().int().positive() })) | |
| .mutation(async ({ input }) => { | |
| const to = adminAlertEmail(); | |
| if (!to) { | |
| throw new TRPCError({ code: "BAD_REQUEST", message: "لم يُضبط بريد التنبيه (ADMIN_ALERT_EMAIL) على الخادم" }); | |
| } | |
| const db = getDb(); | |
| const [target] = await db | |
| .select({ username: users.username, name: users.name, email: users.email, approvalStatus: users.approvalStatus }) | |
| .from(users) | |
| .where(eq(users.id, input.userId)) | |
| .limit(1); | |
| if (!target) throw new TRPCError({ code: "NOT_FOUND", message: "User not found" }); | |
| if (target.approvalStatus !== "pending") { | |
| throw new TRPCError({ code: "BAD_REQUEST", message: "هذا الحساب ليس في انتظار الموافقة" }); | |
| } | |
| const base = env.FRONTEND_URL; | |
| await notifyAdminsOfRegistration({ | |
| userId: input.userId, | |
| username: target.username, | |
| name: target.name, | |
| email: target.email, | |
| frontendUrl: base, | |
| }); | |
| logger.info("[Admin] approval email re-sent", { userId: input.userId, to: maskEmail(to) }); | |
| return { success: true }; | |
| }), | |
| // ✅ EMAIL DELIVERY VISIBILITY (owner report 2026-11-26): the last email | |
| // send outcomes from the bounded email_delivery_log ledger (migration | |
| // v22) — the dashboard can now answer "did the approval alert actually | |
| // go out, and if not, WHY" without any server-log access. Read-only, | |
| // best-effort: a missing table (pre-migration boot race) degrades to an | |
| // empty list instead of erroring the tab. | |
| emailDeliveryLog: adminQuery | |
| .query(async () => { | |
| const db = getDb(); | |
| try { | |
| const [rows] = await db.execute(sql` | |
| SELECT id, at, class, toMasked, ok, providerStatus, reason | |
| FROM email_delivery_log | |
| ORDER BY id DESC | |
| LIMIT 10 | |
| `) as unknown as [Array<{ | |
| id: number; at: string; class: string; toMasked: string; | |
| ok: number; providerStatus: string | null; reason: string | null; | |
| }>, unknown]; | |
| const items = (rows || []).map((r) => ({ | |
| id: r.id, | |
| at: r.at, | |
| class: r.class, | |
| toMasked: r.toMasked, | |
| ok: !!r.ok, | |
| providerStatus: r.providerStatus, | |
| reason: r.reason, | |
| })); | |
| const lastAlert = items.find((r) => r.class === "approval-alert") ?? null; | |
| return { items, lastAlert, fromEmail: env.RESEND_FROM_EMAIL }; | |
| } catch { | |
| // Ledger not created yet (boot race) — degrade to empty, never error. | |
| return { items: [], lastAlert: null, fromEmail: env.RESEND_FROM_EMAIL }; | |
| } | |
| }), | |
| // ✅ ROOT FIX (owner report 2026-11-24, "راجع المشكلة من جذورها"): the v17 | |
| // migration grandfathered every PRE-GATE account as 'approved' — the owner | |
| // signed in with his old @AHMEDBAZ account and the gate never stopped him. | |
| // The owner's authority must reach those accounts too: re-open puts ANY | |
| // non-admin account back into the pending queue (gate panel + alert email | |
| // with signed action links) and KILLS its live session (tokenVersion bump | |
| // + cache eviction — pending means no access, not just "no NEW sessions"). | |
| reopenApproval: adminMutation | |
| .input(z.object({ userId: z.number().int().positive() })) | |
| .mutation(async ({ ctx, input }) => { | |
| const db = getDb(); | |
| const [target] = await db | |
| .select({ | |
| username: users.username, | |
| name: users.name, | |
| email: users.email, | |
| role: users.role, | |
| approvalStatus: users.approvalStatus, | |
| tokenVersion: users.tokenVersion, | |
| }) | |
| .from(users) | |
| .where(eq(users.id, input.userId)) | |
| .limit(1); | |
| if (!target) throw new TRPCError({ code: "NOT_FOUND", message: "User not found" }); | |
| // The authority can never be re-gated out of its own platform. | |
| if (target.role === "admin") { | |
| throw new TRPCError({ code: "BAD_REQUEST", message: "لا يمكن إعادة فتح مراجعة حسابات المشرفين" }); | |
| } | |
| if (target.approvalStatus === "pending") { | |
| throw new TRPCError({ code: "BAD_REQUEST", message: "هذا الحساب بانتظار المراجعة بالفعل" }); | |
| } | |
| await db | |
| .update(users) | |
| .set({ | |
| approvalStatus: "pending", | |
| approvalDecidedAt: null, | |
| approvalDecidedByUserId: null, | |
| // Same semantics as reject: an account whose access the owner is | |
| // re-deciding must not keep the session it holds right now. | |
| tokenVersion: target.tokenVersion + 1, | |
| }) | |
| .where(eq(users.id, input.userId)); | |
| evictUserAuthCache(input.userId); | |
| logger.info("[Admin] approval re-opened — account re-gated to pending, live session revoked", { | |
| userId: input.userId, | |
| username: target.username, | |
| by: ctx.user.id, | |
| }); | |
| // Owner alert (best-effort): in-app stream + the approval email with | |
| // fresh signed action links — the owner decides from inbox or dashboard. | |
| void notifyAdminsOfRegistration({ | |
| userId: input.userId, | |
| username: target.username, | |
| name: target.name, | |
| email: target.email, | |
| frontendUrl: env.FRONTEND_URL, | |
| }).catch((notifyErr) => { | |
| logger.warn("[Admin] reopen alert failed (best-effort)", { | |
| userId: input.userId, | |
| error: notifyErr instanceof Error ? notifyErr.message : String(notifyErr), | |
| }); | |
| }); | |
| return { success: true, status: "pending" as const }; | |
| }), | |
| // ── ✅ OWNER SWITCH (2026-12-01): the approval-gate toggle ──────────────── | |
| // The owner's dashboard switch for the WHOLE gate. ON (default, the | |
| // 2026-11-24 contract): registrations land pending and need an explicit | |
| // approval. OFF: registrations approve themselves and already-pending | |
| // accounts pass through (rejected accounts stay blocked — a rejection is | |
| // the owner's permanent decision). State lives in the `approvalGate` | |
| // siteSettings section (cache-backed reader: lib/approval-gate-config.ts, | |
| // fails closed to ON); flipping it ALSO evicts the whole user auth cache so | |
| // cached sessions re-evaluate on the very next request. | |
| approvalGate: adminQuery | |
| .query(async () => { | |
| const cfg = await getApprovalGateConfig(); | |
| return { enabled: cfg.enabled }; | |
| }), | |
| setApprovalGate: adminMutation | |
| .input(z.object({ enabled: z.boolean() })) | |
| .mutation(async ({ ctx, input }) => { | |
| const db = getDb(); | |
| // Same single-statement UPSERT the settings router uses (the table has | |
| // a UNIQUE (section, key) contract). | |
| await db.execute( | |
| sql`INSERT INTO siteSettings (\`section\`, \`key\`, \`value\`, \`type\`, \`sortOrder\`) | |
| VALUES ('approvalGate', 'enabled', ${input.enabled ? "true" : "false"}, 'text', 0) | |
| ON DUPLICATE KEY UPDATE \`value\` = VALUES(\`value\`)`, | |
| ); | |
| // Drop BOTH caches: the settings cache (config re-read) and the user | |
| // auth cache (every session re-evaluates the gate on its next request). | |
| await invalidateSettingsCache(); | |
| evictAllUserAuthCache(); | |
| logger.info("[Admin] approval gate switched", { enabled: input.enabled, by: ctx.user.id }); | |
| return { success: true, enabled: input.enabled }; | |
| }), | |
| }; | |