-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathjwt.strategy.ts
More file actions
36 lines (30 loc) · 1.11 KB
/
jwt.strategy.ts
File metadata and controls
36 lines (30 loc) · 1.11 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
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy, VerifiedCallback } from 'passport-jwt';
import { CustomUnauthorizedException } from 'src/common/exceptions';
import { EnvironmentVariables } from 'src/common/helper/env.validation';
import { UserService } from '../../user/user.service';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor(
private readonly userService: UserService,
private readonly configService: ConfigService<EnvironmentVariables>,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: configService.get('JWT_PUBLIC_KEY'),
});
}
async validate(payload: { id: string }, done: VerifiedCallback) {
try {
const userData = await this.userService.getOne({
where: { id: payload.id },
select: { id: true, role: true },
});
done(null, userData);
} catch (err) {
throw new CustomUnauthorizedException({ message: err.message });
}
}
}