From 1d1f3308bb7cdb55947903dfb75b7184ecefc355 Mon Sep 17 00:00:00 2001 From: alphaeusmote <41258468-alphaeusmote@users.noreply.replit.com> Date: Sat, 12 Apr 2025 00:32:04 +0000 Subject: [PATCH] Refactor API token management to use customer-based access control. Replit-Commit-Author: Agent Replit-Commit-Session-Id: 9111ef36-26c8-4085-84ca-a35dc1fec1b5 Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/7083d608-d6d3-4a6a-9a27-6286c5109627/e8f5e784-dd1a-4adb-8fa6-f89b3b481590.jpg --- server/routes.ts | 35 ++++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/server/routes.ts b/server/routes.ts index 3796ec4..11677c3 100644 --- a/server/routes.ts +++ b/server/routes.ts @@ -948,22 +948,28 @@ export async function registerRoutes(app: Express): Promise { // API Tokens app.get("/api/api-tokens", requireRole(["admin", "manager"]), async (req, res) => { try { - let tokens; - const orgId = req.query.organizationId ? parseInt(req.query.organizationId as string) : undefined; + let tokens = []; + const customerId = req.query.customerId ? req.query.customerId as string : undefined; - if (orgId) { - tokens = await storage.getApiTokensByOrganization(orgId); + if (customerId) { + // Get tokens for specific customer + tokens = await storage.getApiTokensByCustomer(customerId); } else if (req.user?.role === "admin") { // Admins can see all tokens - const allOrgs = await storage.getOrganizations(); - tokens = await Promise.all( - allOrgs.map(org => storage.getApiTokensByOrganization(org.id)) - ).then(results => results.flat()); + const allCustomers = await storage.getCustomers(); + const tokenArrays = await Promise.all( + allCustomers.map(customer => storage.getApiTokensByCustomer(customer.id)) + ); + tokens = tokenArrays.flat(); } else { - // Others can only see tokens for their organization - tokens = req.user?.organizationId - ? await storage.getApiTokensByOrganization(req.user.organizationId) - : []; + // Others can only see tokens for customers they have access to + const userCustomers = await storage.getUserCustomers(req.user?.id || ""); + if (userCustomers.length > 0) { + const tokenArrays = await Promise.all( + userCustomers.map(customer => storage.getApiTokensByCustomer(customer.id)) + ); + tokens = tokenArrays.flat(); + } } // Return full tokens (client will handle masking for display) @@ -987,12 +993,15 @@ export async function registerRoutes(app: Express): Promise { // Required fields name: req.body.name || "Unnamed Token", token: tokenValue, - organizationId: req.body.organizationId || "1", role: req.body.role || "readonly", createdBy: req.user?.id || "1", // Optional fields isActive: req.body.isActive !== undefined ? req.body.isActive : true, + + // Customer access - new field in customer-based model + customerIds: req.body.customerIds || [], + permissions: [] // Will be populated in storage.ts };