-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.strategy.ts
52 lines (49 loc) · 1.53 KB
/
jwt.strategy.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
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { ForbiddenException, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JWT_MAX_AGE } from '../constants';
import { SystemRepository } from '../persistence/interfaces/system.repository';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
private readonly JWT_SKIP_VALIDATION = process.env.JWT_SKIP_VALIDATION
? process.env.JWT_SKIP_VALIDATION === 'true'
: false;
constructor(
readonly configService: ConfigService,
private readonly systemRepository: SystemRepository,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
passReqToCallback: true,
secretOrKey: configService.get<string>('JWT_SECRET'),
jsonWebTokenOptions: {
maxAge: JWT_MAX_AGE,
},
});
}
public async validate(_req: any, payload: any) {
if (
!this.JWT_SKIP_VALIDATION &&
!(await this.systemRepository.jwtMatchesAllowed(payload))
) {
throw new ForbiddenException({
statusCode: 403,
message: 'Invalid JWT',
error: `Allow list has no match`,
});
}
if (
!this.JWT_SKIP_VALIDATION &&
(await this.systemRepository.jwtMatchesBlocked(payload))
) {
throw new ForbiddenException({
statusCode: 403,
message: 'Invalid JWT',
error: `Block list has match`,
});
}
return payload;
}
}