26 lines
937 B
TypeScript
Executable File
26 lines
937 B
TypeScript
Executable File
import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from "@nestjs/common";
|
|
import { Reflector } from "@nestjs/core";
|
|
import { FastifyRequest } from "fastify";
|
|
|
|
import { ADMIN_ROUTE } from "../../../common/decorators/admin.decorator";
|
|
import { AuthMessage } from "../../../common/enums/message.enum";
|
|
|
|
@Injectable()
|
|
export class AdminRouteGuard implements CanActivate {
|
|
constructor(private reflector: Reflector) {}
|
|
|
|
canActivate(context: ExecutionContext): boolean {
|
|
const requiredAdmin = this.reflector.getAllAndOverride<boolean>(ADMIN_ROUTE, [context.getHandler(), context.getClass()]);
|
|
if (!requiredAdmin) return true;
|
|
|
|
const req = context.switchToHttp().getRequest<FastifyRequest>();
|
|
const user = req.user;
|
|
|
|
if (!user) throw new ForbiddenException(AuthMessage.UNAUTHORIZED_ACCESS);
|
|
|
|
if (!user.role) throw new ForbiddenException(AuthMessage.UNAUTHORIZED_ACCESS);
|
|
|
|
return true;
|
|
}
|
|
}
|