import { Injectable } from "@nestjs/common"; import type { CanActivate, ExecutionContext } from "@nestjs/common"; import type { FastifyRequest } from "fastify"; import { AdminAccessService } from "./admin-access.service.js"; const PATH_METADATA = "path"; @Injectable() export class AdminMembershipGuard implements CanActivate { constructor(private readonly access: AdminAccessService) {} canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); const handlerPath = Reflect.getMetadata(PATH_METADATA, context.getHandler()); const controllerPath = Reflect.getMetadata(PATH_METADATA, context.getClass()); const routePath = `${controllerPath ?? ""}/${handlerPath ?? ""}`.replace(/^\/+|\/+$/g, ""); if (routePath === "admin/session/login") return Promise.resolve(true); if (routePath === "admin/session/change-password") return Promise.resolve(true); if (!routePath.startsWith("admin/")) return Promise.resolve(true); if ( /^admin\/workspace\/(install|capabilities(?:\/|$)|template(?:\/|$)|fields(?:\/|$))/.test( routePath, ) || /^admin\/config\/visual-template(?:\/|$)/.test(routePath) ) { return this.access.requireRole(request, ["owner", "admin", "platform-admin"]); } return this.access.requireBrand(request).then(() => true); } }