Compare commits

..

No commits in common. 'eecf60bef46010735312e3329fb22540ed19987e' and '4a2c479879c503493b7a6c64d3b089a3bc829885' have entirely different histories.

  1. 2
      src/guard/auth.guard.ts
  2. 9
      src/guard/auth.module.ts
  3. 25
      src/guard/role.guard.ts

@ -16,7 +16,7 @@ export class JwtAuthGuard implements CanActivate {
}
try {
const decoded = this.jwtService.verify(token,{secret:process.env.JWT_SECRET});
const decoded = this.jwtService.verify(token);
request.user = decoded;
return true;
} catch (error) {

@ -1,9 +0,0 @@
import { Module } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { JwtAuthGuard } from './auth.guard';
@Module({
providers: [JwtService, JwtAuthGuard],
exports: [JwtService, JwtAuthGuard],
})
export class AuthModule {}

@ -1,25 +0,0 @@
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
@Injectable()
export class RoleGuard implements CanActivate {
constructor(
private jwtService: JwtService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const token = request.headers["authorization"]?.split(" ")[1];
if (!token) throw new UnauthorizedException("Authorization token is missing");
try {
const decoded = this.jwtService.verify(token, { secret: process.env.JWT_SECRET });
const userRole = decoded.role;
if (userRole !== "admin") {
throw new UnauthorizedException("You do not have the required role");
}
request.user = decoded;
return true;
} catch (error) {
throw new UnauthorizedException("Invalid or expired token");
}
}
}
Loading…
Cancel
Save