Files
Picsur/backend/src/managers/auth/guards/jwt.strategy.ts

40 lines
1.1 KiB
TypeScript
Raw Normal View History

2022-03-06 12:27:11 +01:00
import {
Inject,
Injectable,
Logger,
2022-03-06 12:34:33 +01:00
UnauthorizedException
2022-03-06 12:27:11 +01:00
} from '@nestjs/common';
2022-03-06 12:34:33 +01:00
import { PassportStrategy } from '@nestjs/passport';
2022-02-21 14:53:21 +01:00
import { plainToClass } from 'class-transformer';
2022-03-06 12:34:33 +01:00
import { validate } from 'class-validator';
import { ExtractJwt, Strategy } from 'passport-jwt';
2022-02-27 20:27:22 +01:00
import { JwtDataDto } from 'picsur-shared/dist/dto/auth.dto';
2022-03-03 22:48:03 +01:00
import { EUserBackend } from '../../../models/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');
2022-03-06 12:27:11 +01:00
constructor(@Inject('JWT_SECRET') private jwtSecret: string) {
2022-02-21 14:53:21 +01:00
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
2022-03-06 12:27:11 +01:00
secretOrKey: jwtSecret,
2022-02-21 14:53:21 +01:00
});
}
2022-03-01 22:05:59 +01:00
async validate(payload: any): Promise<EUserBackend> {
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;
}
}