From bade67265359bea992d420eb93705dd7197437a4 Mon Sep 17 00:00:00 2001 From: alphaeusmote <41258468-alphaeusmote@users.noreply.replit.com> Date: Fri, 11 Apr 2025 14:42:29 +0000 Subject: [PATCH] Add permission checking for API requests. Replit-Commit-Author: Agent Replit-Commit-Session-Id: 705f2157-ef97-4fbd-89e4-8c7f2ecaea90 Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/7ed01c5f-a82d-405a-b728-b2e3d127c60c/9f1689f9-354e-48da-9155-329f0295a865.jpg --- server/authorization.ts | 50 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/server/authorization.ts b/server/authorization.ts index 07eb575..4e9bec7 100644 --- a/server/authorization.ts +++ b/server/authorization.ts @@ -171,6 +171,56 @@ export async function getUserPermissions(userId: number): Promise { return rolePerms.map(rp => rp.permission); } +// Check if a request has a specific permission +export async function checkPermission(req: Request, permission: string): Promise { + if (!req.user) { + return false; + } + + let hasPermission = false; + + // Check for API token custom permissions first if present + if (req.user?.tokenId && Array.isArray(req.user?.customPermissions)) { + // For API tokens with custom permissions + const customPermissions = req.user.customPermissions; + if (customPermissions.includes(permission)) { + hasPermission = true; + } + } + + // If no permission yet, check role-based permissions + if (!hasPermission && req.user.roleId) { + // Get permissions assigned to the role + const rolePerms = await db.select() + .from(rolePermissions) + .where(eq(rolePermissions.roleId, req.user.roleId)); + + const userPermissions = rolePerms.map(rp => rp.permission); + + // Check for the specific permission + if (userPermissions.includes(permission)) { + hasPermission = true; + } + } + + // Check if user has the admin:system permission which grants all access + if (!hasPermission && req.user.roleId) { + const adminPerm = await db.select() + .from(rolePermissions) + .where(and( + eq(rolePermissions.roleId, req.user.roleId), + eq(rolePermissions.permission, "admin:system") + )) + .limit(1); + + if (adminPerm.length > 0) { + hasPermission = true; + } + } + + return hasPermission; +} + // Initialize on server startup to ensure default roles export async function initializeRBAC() { try {