-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession-manager.guard.ts
More file actions
63 lines (55 loc) · 1.92 KB
/
Copy pathsession-manager.guard.ts
File metadata and controls
63 lines (55 loc) · 1.92 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
53
54
55
56
57
58
59
60
61
62
63
import {
Injectable,
CanActivate,
ExecutionContext,
UnauthorizedException,
ForbiddenException,
} from '@nestjs/common';
import { SessionManagerService } from './session-manager.service';
/**
* SessionManagerGuard - Protects routes that require authentication
*
* This guard validates session tokens from the Authorization header.
* It uses the same JWT secret configured in the ApiModule.
*
* Usage:
* ```typescript
* @UseGuards(SessionManagerGuard)
* @Post('protected-route')
* async myRoute(@AuthenticatedUser() user: AuthenticatedUserData) {
* // user.identifier is available
* }
* ```
*
* The guard also validates that if a request body contains an `identifier`,
* it matches the authenticated user's identifier (prevents impersonation).
*/
@Injectable()
export class SessionManagerGuard implements CanActivate {
constructor(private readonly sessionManagerService: SessionManagerService) {}
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 token = authHeader.replace('Bearer ', '');
const result = this.sessionManagerService.verifySessionToken(token);
if (!result.valid || !result.payload) {
throw new UnauthorizedException(result.error || 'Invalid session token');
}
request.authenticatedUser = {
identifier: result.payload.identifier,
};
// If the request body contains an identifier, verify it matches the token
const bodyIdentifier = request.body?.identifier;
if (bodyIdentifier && bodyIdentifier !== result.payload.identifier) {
throw new ForbiddenException(
'Request identifier does not match authenticated user',
);
}
return true;
}
}