-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-key.guard.ts
More file actions
25 lines (22 loc) · 935 Bytes
/
Copy pathapi-key.guard.ts
File metadata and controls
25 lines (22 loc) · 935 Bytes
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
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Request } from 'express';
import { AppConfigService } from '../../config/app-config.service';
import { HEADERS } from '../constants/headers';
import { InvalidApiKeyException } from '../exceptions/invalid-api-key.exception';
/**
* Guards write operations. The expected key comes from typed configuration
* (never hardcoded) and is compared against the `x-api-key` request header.
* A missing or wrong key yields a 401.
*/
@Injectable()
export class ApiKeyGuard implements CanActivate {
constructor(private readonly config: AppConfigService) {}
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest<Request>();
const provided = request.header(HEADERS.ApiKey);
if (!provided || provided !== this.config.apiKey) {
throw new InvalidApiKeyException();
}
return true;
}
}