1
11import { CanActivate, ExecutionContext, Inject, Injectable } from "@nestjs/common";
12import type { Request } from "express";
13import { ScimAuthService } from "./scim-auth.service.js";
14import { ScimError } from "./scim-errors.js";
15import { PrismaService } from "../../common/prisma.service.js";
16
17@Injectable()
18export class ScimBearerGuard implements CanActivate {
19 constructor(
20 @Inject(ScimAuthService) private readonly auth: ScimAuthService,
21 @Inject(PrismaService) private readonly prisma: PrismaService
22 ) {}
23
24 async canActivate(context: ExecutionContext): Promise<boolean> {
25 const req = context.switchToHttp().getRequest<Request & { scimOrg?: unknown }>();
26 const header = req.headers.authorization;
27 if (!header || !header.startsWith("Bearer ")) {
28 throw ScimError.unauthorized("Missing bearer token.");
29 }
30 const token = header.slice(7).trim();
31 if (!token) throw ScimError.unauthorized("Missing bearer token.");
32
33 const resolved = await this.auth.resolveOrg(token);
34 if (!resolved) throw ScimError.unauthorized();
35
36
37 const org = await this.prisma.organization.findUnique({ where: { id: resolved.orgId } });
38 if (!org || org.scimConfig == null) {
39
40 throw ScimError.unauthorized();
41 }
42 req.scimOrg = { id: org.id, scimConfig: org.scimConfig };
43 return true;
44 }
45}
46