Files
Picsur/backend/src/routes/api/auth/jwt.strategy.ts

37 lines
1.0 KiB
TypeScript
Raw Normal View History

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 { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';
2022-02-24 22:56:27 +01:00
import Config from '../../../env';
2022-02-25 12:22:00 +01:00
import { JwtDataDto } from 'imagur-shared/dist/dto/auth.dto';
import { EUser } from 'imagur-shared/dist/entities/user.entity';
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<EUser> {
2022-02-21 14:53:21 +01:00
const jwt = plainToClass(JwtDataDto, payload);
2022-02-26 18:16:28 +01:00
const errors = await validate(jwt, {
forbidUnknownValues: true,
});
2022-02-21 14:53:21 +01:00
if (errors.length > 0) {
2022-02-24 11:22:28 +01:00
this.logger.warn(errors);
2022-02-21 14:53:21 +01:00
throw new UnauthorizedException();
}
return jwt.user;
}
}