(req: Request, res: Response, next: NextFunction)
| 1167 | * Or checks if user's email is in ADMIN_EMAILS list |
| 1168 | */ |
| 1169 | export async function requireAdmin(req: Request, res: Response, next: NextFunction) { |
| 1170 | const isHtmlRequest = req.accepts('html') && !req.originalUrl.startsWith('/api/'); |
| 1171 | |
| 1172 | // Check for static admin API key (set by requireAuth) |
| 1173 | if ((req as Request & { isStaticAdminApiKey?: boolean }).isStaticAdminApiKey) { |
| 1174 | logger.debug({ path: req.path, method: req.method }, 'Admin access via static admin API key'); |
| 1175 | return next(); |
| 1176 | } |
| 1177 | |
| 1178 | // Check for WorkOS API key with admin permission |
| 1179 | const apiKey = (req as Request & { apiKey?: ValidatedApiKey }).apiKey; |
| 1180 | if (apiKey) { |
| 1181 | const isReadOnlyRequest = req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS'; |
| 1182 | |
| 1183 | // admin:* grants full access (read and write) |
| 1184 | if (apiKeyHasPermission(apiKey, 'admin:*')) { |
| 1185 | logger.debug({ path: req.path, method: req.method, apiKeyId: apiKey.id }, 'Full admin access via WorkOS API key'); |
| 1186 | return next(); |
| 1187 | } |
| 1188 | |
| 1189 | // admin:read only grants access to read operations |
| 1190 | if (apiKeyHasPermission(apiKey, 'admin:read') && isReadOnlyRequest) { |
| 1191 | logger.debug({ path: req.path, method: req.method, apiKeyId: apiKey.id }, 'Read-only admin access via WorkOS API key'); |
| 1192 | return next(); |
| 1193 | } |
| 1194 | |
| 1195 | // API key exists but doesn't have sufficient permission |
| 1196 | return res.status(403).json({ |
| 1197 | error: 'Insufficient permissions', |
| 1198 | message: isReadOnlyRequest |
| 1199 | ? 'This API key does not have admin access. Required permission: admin:* or admin:read' |
| 1200 | : 'This API key does not have write access. Required permission: admin:*', |
| 1201 | api_key_permissions: apiKey.permissions, |
| 1202 | }); |
| 1203 | } |
| 1204 | |
| 1205 | // Dev mode: check if dev user has admin flag |
| 1206 | if (DEV_MODE_ENABLED) { |
| 1207 | const devUser = getDevUser(req); |
| 1208 | if (!devUser) { |
| 1209 | // Not logged in |
| 1210 | if (isHtmlRequest) { |
| 1211 | return res.redirect(`/auth/login?return_to=${encodeURIComponent(req.originalUrl)}`); |
| 1212 | } |
| 1213 | return res.status(401).json({ |
| 1214 | error: 'Authentication required', |
| 1215 | message: 'Please log in to access this resource', |
| 1216 | login_url: '/auth/login', |
| 1217 | }); |
| 1218 | } |
| 1219 | |
| 1220 | // Set user on request if not already set |
| 1221 | if (!req.user) { |
| 1222 | const mockUser = createDevUser(req); |
| 1223 | if (mockUser) { |
| 1224 | req.user = mockUser; |
| 1225 | req.accessToken = 'dev-mode-token'; |
| 1226 | } |
nothing calls this directly
no test coverage detected