33 lines
1.4 KiB
TypeScript
33 lines
1.4 KiB
TypeScript
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
|
|
import { PassportStrategy } from '@nestjs/passport';
|
|
import { FastifyRequest } from 'fastify';
|
|
import { ClsService } from 'nestjs-cls';
|
|
import { ExtractJwt, Strategy } from 'passport-jwt';
|
|
import { AppClsStore } from '../../../cls/cls.interface';
|
|
import { authConfig, type AuthConfig } from '../../auth.config';
|
|
import { TokenPayload } from '../../constants/token-payload.interface';
|
|
import { UsersAuthService } from '../../users/users-auth.service';
|
|
|
|
@Injectable()
|
|
export class JwtRefreshTokenAuthStrategy extends PassportStrategy(Strategy, 'jwt-refresh-token') {
|
|
constructor(
|
|
@Inject(authConfig.KEY) authConfig: AuthConfig,
|
|
private readonly cls: ClsService<AppClsStore>,
|
|
private readonly usersAuthService: UsersAuthService,
|
|
) {
|
|
super({
|
|
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
|
secretOrKey: authConfig.refreshToken.secret,
|
|
passReqToCallback: true,
|
|
});
|
|
}
|
|
|
|
async validate(request: FastifyRequest, payload: TokenPayload) {
|
|
const refreshToken = request.headers?.authorization?.replace('Bearer', '')?.trim() ?? '';
|
|
const account = await this.usersAuthService.getUserByIdAndRefreshTokenPair(payload.sub, refreshToken);
|
|
if (!account) throw new UnauthorizedException('Refresh Token Guard');
|
|
this.cls.set('account', account);
|
|
return account;
|
|
}
|
|
}
|