2022-02-21 14:53:21 +01:00
|
|
|
import { ExtractJwt, Strategy } from 'passport-jwt';
|
|
|
|
|
import { PassportStrategy } from '@nestjs/passport';
|
|
|
|
|
import { Injectable, Logger, UnauthorizedException } from '@nestjs/common';
|
|
|
|
|
import Config from 'src/env';
|
|
|
|
|
import { validate } from 'class-validator';
|
|
|
|
|
import { JwtDataDto } from './auth.dto';
|
|
|
|
|
import { plainToClass } from 'class-transformer';
|
2022-02-21 22:36:47 +01:00
|
|
|
import { User } from 'src/collections/userdb/user.dto';
|
2022-02-21 14:53:21 +01:00
|
|
|
|
|
|
|
|
@Injectable()
|
2022-02-23 11:10:25 +01:00
|
|
|
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
|
2022-02-21 14:53:21 +01:00
|
|
|
private readonly logger = new Logger('JwtStrategy');
|
|
|
|
|
|
|
|
|
|
constructor() {
|
|
|
|
|
super({
|
|
|
|
|
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
|
|
|
|
ignoreExpiration: false,
|
|
|
|
|
secretOrKey: Config.jwt.secret,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async validate(payload: any): Promise<User> {
|
|
|
|
|
const jwt = plainToClass(JwtDataDto, payload);
|
|
|
|
|
|
|
|
|
|
const errors = await validate(jwt);
|
|
|
|
|
if (errors.length > 0) {
|
|
|
|
|
this.logger.warn(`Invalid JWT payload: ${JSON.stringify(payload)}`);
|
|
|
|
|
throw new UnauthorizedException();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return jwt.user;
|
|
|
|
|
}
|
|
|
|
|
}
|