-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin-auth.guard.ts
More file actions
40 lines (33 loc) · 1.2 KB
/
admin-auth.guard.ts
File metadata and controls
40 lines (33 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import {
Injectable,
CanActivate,
ExecutionContext,
UnauthorizedException,
Logger,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Request } from 'express';
@Injectable()
export class AdminAuthGuard implements CanActivate {
private readonly logger = new Logger(AdminAuthGuard.name);
constructor(private configService: ConfigService) {}
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest<Request>();
const adminKey = request.headers['x-admin-api-key'];
const expectedKey = this.configService.get<string>('ADMIN_API_KEY');
if (!expectedKey) {
this.logger.error('ADMIN_API_KEY is not configured in environment');
throw new UnauthorizedException('Admin API is not configured');
}
if (!adminKey) {
this.logger.warn('Admin request without x-admin-api-key header');
throw new UnauthorizedException('Missing admin API key');
}
if (adminKey !== expectedKey) {
this.logger.warn('Admin request with invalid API key');
throw new UnauthorizedException('Invalid admin API key');
}
this.logger.debug('Admin authentication successful');
return true;
}
}