Spaces:
Sleeping
Sleeping
Download src/modules/auth/admin-key.guard.ts from mahrooshishaq/SmartfolioBackend: direct link, hf CLI and curl.
- Browser
- Download file 1.86 kB
-
https://huggingface.co/spaces/mahrooshishaq/SmartfolioBackend/resolve/main/src/modules/auth/admin-key.guard.ts
- Command line
-
hf download hf://spaces/mahrooshishaq/SmartfolioBackend/src/modules/auth/admin-key.guard.ts
-
curl -L -o admin-key.guard.ts https://huggingface.co/spaces/mahrooshishaq/SmartfolioBackend/resolve/main/src/modules/auth/admin-key.guard.ts
1.86 kB
| import { | |
| CanActivate, | |
| ExecutionContext, | |
| ForbiddenException, | |
| Injectable, | |
| Logger, | |
| } from '@nestjs/common'; | |
| import { ConfigService } from '@nestjs/config'; | |
| import { timingSafeEqual } from 'crypto'; | |
| /** | |
| * Guards operator-only endpoints (scraper maintenance, cross-user reads) with a | |
| * shared secret sent as `x-admin-key`. | |
| * | |
| * This is deliberately not a role on the User entity: there is no admin UI and | |
| * no self-serve path to becoming an admin, so a role column would be schema | |
| * surface with no reader. If an admin dashboard is built later, replace this | |
| * with a proper role guard. | |
| * | |
| * Fails closed — if ADMIN_API_KEY is unset the endpoint is unreachable rather | |
| * than open, so a missing env var can never silently expose these routes. | |
| */ | |
| () | |
| export class AdminKeyGuard implements CanActivate { | |
| private readonly logger = new Logger(AdminKeyGuard.name); | |
| constructor(private readonly config: ConfigService) {} | |
| canActivate(context: ExecutionContext): boolean { | |
| const expected = this.config.get<string>('ADMIN_API_KEY'); | |
| if (!expected) { | |
| this.logger.error( | |
| 'ADMIN_API_KEY is not configured: refusing admin request (failing closed).', | |
| ); | |
| throw new ForbiddenException('Admin access is not configured.'); | |
| } | |
| const request = context.switchToHttp().getRequest(); | |
| const provided = request.headers?.['x-admin-key']; | |
| if (typeof provided !== 'string' || !this.matches(provided, expected)) { | |
| throw new ForbiddenException('Admin access denied.'); | |
| } | |
| return true; | |
| } | |
| /** Constant-time compare so a wrong key can't be recovered by timing. */ | |
| private matches(provided: string, expected: string): boolean { | |
| const a = Buffer.from(provided); | |
| const b = Buffer.from(expected); | |
| if (a.length !== b.length) return false; | |
| return timingSafeEqual(a, b); | |
| } | |
| } | |