brief-20/backend/src/modules/auth/strategies/jwt-refresh.strategy.ts
Avnyr 9f99b80784 feat: implement authentication and database modules with relations and group management
Added new authentication strategies (JWT and GitHub OAuth), guards, and controllers. Implemented database module, schema with relations, and group management features, including CRD operations and person-to-group associations. Integrated validation and CORS configuration.
2025-05-15 17:09:36 +02:00

51 lines
1.6 KiB
TypeScript

import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { AuthService } from '../services/auth.service';
import { JwtPayload } from '../interfaces/jwt-payload.interface';
@Injectable()
export class JwtRefreshStrategy extends PassportStrategy(Strategy, 'jwt-refresh') {
constructor(
private readonly configService: ConfigService,
private readonly authService: AuthService,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: configService.get<string>('JWT_REFRESH_SECRET'),
passReqToCallback: true,
});
}
/**
* Validate the JWT refresh token payload and return the user
*/
async validate(req: any, payload: JwtPayload) {
try {
// Check if this is a refresh token
if (!payload.isRefreshToken) {
throw new UnauthorizedException('Invalid token type');
}
// Extract the refresh token from the request
const refreshToken = ExtractJwt.fromAuthHeaderAsBearerToken()(req);
if (!refreshToken) {
throw new UnauthorizedException('Refresh token not found');
}
// Validate the user
const user = await this.authService.validateJwtUser(payload);
// Attach the refresh token to the user object for later use
return {
...user,
refreshToken,
};
} catch (error) {
throw new UnauthorizedException('Invalid refresh token');
}
}
}