forked from PinSpace-Org/GistPin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-key.guard.ts
More file actions
52 lines (41 loc) 路 1.62 KB
/
Copy pathapi-key.guard.ts
File metadata and controls
52 lines (41 loc) 路 1.62 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
41
42
43
44
45
46
47
48
49
50
51
52
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException, Logger } from '@nestjs/common';
import { ApiKeyService } from './api-key.service';
import { createHash } from 'crypto';
@Injectable()
export class ApiKeyGuard implements CanActivate {
private readonly logger = new Logger(ApiKeyGuard.name);
constructor(private readonly apiKeyService: ApiKeyService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const authHeader = request.headers['authorization'];
if (!authHeader || !authHeader.startsWith('Bearer ')) {
throw new UnauthorizedException('Missing or invalid Authorization header');
}
const plainKey = authHeader.slice(7).trim();
if (!plainKey) {
throw new UnauthorizedException('Empty API key');
}
const keyHash = createHash('sha256').update(plainKey).digest('hex');
try {
const apiKey = await this.apiKeyService.validate(keyHash);
const withinLimit = await this.apiKeyService.checkRateLimit(apiKey);
if (!withinLimit) {
throw new UnauthorizedException('Rate limit exceeded');
}
await this.apiKeyService.recordUsage(apiKey);
request.apiKey = {
id: apiKey.id,
name: apiKey.name,
ownerAddress: apiKey.ownerAddress,
scopes: apiKey.scopes,
};
return true;
} catch (err) {
if (err instanceof UnauthorizedException) {
throw err;
}
this.logger.error('API key validation failed', (err as Error).message);
throw new UnauthorizedException('API key validation failed');
}
}
}