-
Notifications
You must be signed in to change notification settings - Fork 0
/
refresh-token.strategy.ts
44 lines (40 loc) · 1.4 KB
/
refresh-token.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
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { Request } from 'express';
import * as fs from 'fs';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { UserValidationService } from '../user-validation.service';
@Injectable()
export class RefreshTokenStrategy extends PassportStrategy(
Strategy,
'jwt-refresh',
) {
constructor(
private authService: UserValidationService,
configService: ConfigService,
) {
const publicKeyFile = configService.get<string>('PUBLIC_KEY_FILE');
const publicKey = fs.readFileSync(publicKeyFile, 'utf8');
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: publicKey,
passReqToCallback: true,
});
}
async validate(req: Request, payload: any) {
const refreshToken = req
.get('Authorization')
.replace('Bearer', '')
.trim();
if (payload.role === 'Owner') return { ...payload, refreshToken };
const validUser = await this.authService.validateRefreshToken(
payload.userId,
refreshToken,
);
if (!validUser) {
throw new UnauthorizedException('Invalid User');
}
return { ...payload, refreshToken };
}
}