-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Expand file tree
/
Copy pathcommunity.user.auth.guard.ts
More file actions
48 lines (42 loc) · 1.72 KB
/
community.user.auth.guard.ts
File metadata and controls
48 lines (42 loc) · 1.72 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
import { ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard, IAuthModuleOptions } from '@nestjs/passport';
import { PinoLogger } from '@novu/application-generic';
import { ApiAuthSchemeEnum, NONE_AUTH_SCHEME, PassportStrategyEnum } from '@novu/shared';
@Injectable()
export class CommunityUserAuthGuard extends AuthGuard([PassportStrategyEnum.JWT, PassportStrategyEnum.HEADER_API_KEY]) {
constructor(
private readonly reflector: Reflector,
private readonly logger: PinoLogger
) {
super();
this.logger.setContext(this.constructor.name);
}
getAuthenticateOptions(context: ExecutionContext): IAuthModuleOptions {
const request = context.switchToHttp().getRequest();
const authorizationHeader = request.headers.authorization;
const authScheme = authorizationHeader?.split(' ')[0] || NONE_AUTH_SCHEME;
request.authScheme = authScheme;
this.logger.assign({ authScheme });
switch (authScheme) {
case ApiAuthSchemeEnum.BEARER: {
return {
session: false,
defaultStrategy: PassportStrategyEnum.JWT,
};
}
case ApiAuthSchemeEnum.API_KEY: {
const apiEnabled = this.reflector.get<boolean>('external_api_accessible', context.getHandler());
if (!apiEnabled) throw new UnauthorizedException('API endpoint not accessible');
return {
session: false,
defaultStrategy: PassportStrategyEnum.HEADER_API_KEY,
};
}
case NONE_AUTH_SCHEME:
throw new UnauthorizedException('Missing authorization header');
default:
throw new UnauthorizedException(`Invalid authentication scheme: "${authScheme}"`);
}
}
}