1
18import { Controller, Get, Inject, Param, Query, Req, Res } from "@nestjs/common";
19import type { Request, Response } from "express";
20import { PrismaService } from "../../common/prisma.service.js";
21import { loadEnv } from "../../config/env.js";
22import { OidcService } from "./oidc.service.js";
23
24@Controller("sso")
25export class OidcController {
26 constructor(
27 @Inject(PrismaService) private readonly prisma: PrismaService,
28 @Inject(OidcService) private readonly oidc: OidcService
29 ) {}
30
31
37 private origin(): string {
38 const env = loadEnv();
39 return (env.SSO_ORIGIN || env.WEB_ORIGIN).replace(/\/$/, "");
40 }
41
42
43 @Get("oidc/:orgId/authorize")
44 async authorize(@Param("orgId") orgId: string, @Res() res: Response): Promise<void> {
45 const { url } = await this.oidc.authorize(orgId);
46 res.status(302).header("location", url).end();
47 }
48
49
50 @Get("oidc/:orgId/callback")
51 async callback(
52 @Param("orgId") orgId: string,
53 @Query() query: { code?: string; state?: string },
54 @Req() req: Request,
55 @Res() res: Response
56 ): Promise<void> {
57 await this.oidc.callback(orgId, { code: query.code, state: query.state }, req, res);
58 }
59
60
68 @Get("start/:orgSlug")
69 async start(@Param("orgSlug") orgSlug: string, @Res() res: Response): Promise<void> {
70 const org = await this.prisma.organization.findUnique({
71 where: { slug: orgSlug },
72 select: { id: true, slug: true }
73 });
74 if (!org) {
75 res.status(404).json({ error: { code: "NOT_FOUND", message: "Unknown organization." } });
76 return;
77 }
78 const provider = await this.prisma.ssoProvider.findUnique({
79 where: { organizationId: org.id },
80 select: { type: true }
81 });
82 if (!provider) {
83 res.status(404).json({ error: { code: "NOT_FOUND", message: "Organization has no SSO provider." } });
84 return;
85 }
86 const location =
87 provider.type === "SAML"
88 ? `${this.origin()}/saml/start/${org.slug}`
89 : `${this.origin()}/sso/oidc/${org.id}/authorize`;
90 res.status(302).header("location", location).end();
91 }
92}
93