implement jwt auth

This commit is contained in:
Philipinho
2023-08-05 16:58:34 +01:00
parent cebad0e0a5
commit 6e3ba20fcf
21 changed files with 744 additions and 46 deletions
@@ -0,0 +1,33 @@
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { EnvironmentService } from '../../../environment/environment.service';
import { User } from '../../user/entities/user.entity';
import { FastifyRequest } from 'fastify';
@Injectable()
export class TokenService {
constructor(
private jwtService: JwtService,
private environmentService: EnvironmentService,
) {}
async generateJwt(user: User): Promise<string> {
const payload = {
sub: user.id,
email: user.email,
};
return await this.jwtService.signAsync(payload);
}
async verifyJwt(token: string) {
return await this.jwtService.verifyAsync(token, {
secret: this.environmentService.getJwtSecret(),
});
}
async extractTokenFromHeader(
request: FastifyRequest,
): Promise<string | undefined> {
const [type, token] = request.headers.authorization?.split(' ') ?? [];
return type === 'Bearer' ? token : undefined;
}
}