Compare commits

..

2 Commits

Author SHA1 Message Date
nicekid1 eecf60bef4 Create role guard to check admin role 4 months ago
nicekid1 13ee297d06 Fix issue with auth guard functionality 4 months ago
  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 { try {
const decoded = this.jwtService.verify(token); const decoded = this.jwtService.verify(token,{secret:process.env.JWT_SECRET});
request.user = decoded; request.user = decoded;
return true; return true;
} catch (error) { } catch (error) {

@ -0,0 +1,9 @@
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 {}

@ -0,0 +1,25 @@
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