forked from Ynov/ptitspas-ynov-back
auth guards added
This commit is contained in:
parent
5387d67162
commit
6eab2613e4
29
src/common/guards/auth.guard.ts
Normal file
29
src/common/guards/auth.guard.ts
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from "@nestjs/common";
|
||||||
|
import { JwtService } from "@nestjs/jwt";
|
||||||
|
import { Request } from 'express';
|
||||||
|
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AuthGuard implements CanActivate {
|
||||||
|
constructor(private readonly jwtService: JwtService) {}
|
||||||
|
|
||||||
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||||
|
const request = context.switchToHttp().getRequest<Request>();
|
||||||
|
const authHeader = request.headers['authorization'] as string | undefined;
|
||||||
|
|
||||||
|
if (!authHeader || !authHeader.startsWith('Bearer')) {
|
||||||
|
throw new UnauthorizedException('Token manquant ou invalide');
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = authHeader.split(' ')[1];
|
||||||
|
try {
|
||||||
|
const payload = await this.jwtService.verifyAsync(token,
|
||||||
|
{ secret: process.env.JWT_SECRET },
|
||||||
|
);
|
||||||
|
request.user = payload;
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
throw new UnauthorizedException('Token invalide ou expire');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
7
src/types/express/index.d.ts
vendored
Normal file
7
src/types/express/index.d.ts
vendored
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
import { Users } from 'src/entities/users.entity';
|
||||||
|
|
||||||
|
declare module 'express-serve-static-core' {
|
||||||
|
interface Request {
|
||||||
|
user?: Users | any;
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user