-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
74 lines (65 loc) · 1.97 KB
/
index.ts
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
64
65
66
67
68
69
70
71
72
73
74
import {
CanActivate,
createParamDecorator,
ExecutionContext,
HttpException,
HttpStatus,
} from '@nestjs/common';
import jwtDecode from 'jwt-decode';
interface IJwtDecodeOptions {
authorizationHeader?: string;
authScheme?: string;
}
export const JwtDecode = createParamDecorator(
(options: IJwtDecodeOptions, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
const extractToken = new ExtractToken(request.headers, options);
const token = extractToken.token();
if (!token) return null;
try {
return jwtDecode(token);
} catch (e) {
throw new HttpException('Bad jwt token format', HttpStatus.BAD_REQUEST);
}
},
);
export class JwtGuard implements CanActivate {
constructor(
private callback: (jwtDecoded: any, jwt: string) => boolean,
private decodeOptions?: IJwtDecodeOptions,
) {}
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
const extractToken = new ExtractToken(request.headers, this.decodeOptions);
const token = extractToken.token();
return this.callback(jwtDecode(token), token);
}
}
export class JwtScopesGuard extends JwtGuard {
constructor(scopes: string[], decodeOptions?: IJwtDecodeOptions) {
const checkIncludeScope = (jwtDecode) =>
scopes.some((scope) => jwtDecode['scopes'].includes(scope));
super(checkIncludeScope, decodeOptions);
}
}
export class ExtractToken {
authHeader: string;
authScheme: string;
SPLIT_REGEXP = /(\S+)\s+(\S+)/;
constructor(
private headers: any,
{
authorizationHeader = 'authorization',
authScheme = 'Bearer',
}: IJwtDecodeOptions = {},
) {
this.authHeader = this.headers[authorizationHeader];
this.authScheme = authScheme;
}
token() {
if (!this.authHeader) return null;
const [_, scheme, value] = this.authHeader.match(this.SPLIT_REGEXP);
if (this.authScheme == scheme.toLowerCase()) return null;
return value;
}
}