-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathjwt-access.strategy.ts
More file actions
45 lines (40 loc) · 1.37 KB
/
jwt-access.strategy.ts
File metadata and controls
45 lines (40 loc) · 1.37 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
import { ConfigService } from '@nestjs/config';
import {
BadRequestException,
UnauthorizedException,
} from '@nestjs/common/exceptions';
import { Inject, Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { CACHE_SERVICE, CacheService } from "@common/cache/cache.service";
import { UserDto } from '../presentation/user.dto';
@Injectable()
export class JwtAccessStrategy extends PassportStrategy(Strategy, 'access') {
constructor(
@Inject(CACHE_SERVICE)
private readonly cacheService: CacheService,
private readonly configService: ConfigService,
) {
super({
secretOrKey: configService.get<string>('jwt/access/secret'),
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
passReqToCallback: true,
});
}
async validate(
req: Request & { headers: { authorization?: string } },
payload: any,
): Promise<UserDto> {
if (!payload) {
throw new UnauthorizedException();
}
if (payload.tokenType !== 'access') {
throw new BadRequestException();
}
const token = req.headers.authorization?.replace('Bearer ', '');
if (!token) {
throw new UnauthorizedException('Authorization 헤더에 토큰이 없습니다.');
}
return JSON.parse(<string>await this.cacheService.get(token)) as UserDto;
}
}