import { CanActivate, ExecutionContext, HttpStatus, Inject, Injectable, } from "@nestjs/common"; import { ErrorCode } from "@drift/contracts"; import type { Request } from "express"; import { PrismaService } from "../database/prisma.service.js"; import { DomainException } from "../common/domain.exception.js"; import type { AuthenticatedRequest } from "../auth/current-user.decorator.js"; @Injectable() export class AdminGuard implements CanActivate { constructor(@Inject(PrismaService) private readonly prisma: PrismaService) {} async canActivate(ctx: ExecutionContext) { const req = ctx.switchToHttp().getRequest(); if (!req.user) throw new DomainException( ErrorCode.AUTH_UNAUTHORIZED, "Unauthorized", HttpStatus.UNAUTHORIZED, ); const account = await this.prisma.account.findUnique({ where: { id: req.user.sub }, select: { role: true }, }); if (account?.role !== "ADMIN") throw new DomainException( ErrorCode.CONVERSATION_FORBIDDEN, "Forbidden", HttpStatus.FORBIDDEN, ); return true; } }