This commit is contained in:
SepehrYahyaee
2026-07-11 17:51:14 +03:30
parent 0dcb2cf2ca
commit a7fe04c032
15 changed files with 581 additions and 8 deletions

View File

@@ -0,0 +1,49 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { Request } from "express";
import { RoleEnum } from "src/Types&Enums/role.enum";
/**
* Verifies a Bearer JWT and restricts access to `super_admin` role only.
* Use this guard on all endpoints that should be reachable only by the
* super-admin panel.
*/
@Injectable()
export class SuperAdminGuard implements CanActivate {
constructor(private readonly jwtService: JwtService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>();
const token = this.extractTokenFromHeader(request);
if (!token) {
throw new UnauthorizedException("Token not found");
}
let payload: any;
try {
payload = await this.jwtService.verifyAsync(token, {
secret: `${process.env.JWT_SECRET}`,
});
} catch {
throw new UnauthorizedException("Invalid or expired token");
}
if (payload?.role !== RoleEnum.SUPER_ADMIN) {
throw new UnauthorizedException("Super-admin access required");
}
(request as any).user = payload;
(request as any).identity = payload;
return true;
}
private extractTokenFromHeader(request: Request): string | undefined {
const [type, token] = request.headers.authorization?.split(" ") ?? [];
return type === "Bearer" ? token : undefined;
}
}