diff --git a/app/server/lib/auth/middlewares/require-sso-invitation.ts b/app/server/lib/auth/middlewares/require-sso-invitation.ts index 81da17e3..fef083f7 100644 --- a/app/server/lib/auth/middlewares/require-sso-invitation.ts +++ b/app/server/lib/auth/middlewares/require-sso-invitation.ts @@ -2,14 +2,14 @@ import { APIError } from "better-auth/api"; import type { GenericEndpointContext } from "@better-auth/core"; import { db } from "~/server/db/db"; import { logger } from "~/server/utils/logger"; -import { extractProviderIdFromContext, normalizeEmail } from "../utils/sso-context"; +import { extractProviderIdFromContext, extractProviderIdFromUrl, normalizeEmail } from "../utils/sso-context"; export function isSsoCallbackRequest(ctx: GenericEndpointContext | null) { - if (!ctx) { + if (!ctx?.request?.url) { return false; } - return extractProviderIdFromContext(ctx) !== null; + return extractProviderIdFromUrl(ctx.request.url) !== null; } export const requireSsoInvitation = async (userEmail: string, ctx: GenericEndpointContext | null) => { diff --git a/app/server/lib/auth/utils/sso-context.ts b/app/server/lib/auth/utils/sso-context.ts index b691d8b6..ab36b14a 100644 --- a/app/server/lib/auth/utils/sso-context.ts +++ b/app/server/lib/auth/utils/sso-context.ts @@ -4,6 +4,16 @@ export function normalizeEmail(email: string): string { return email.trim().toLowerCase(); } +export function extractProviderIdFromUrl(url: string): string | null { + try { + const pathname = new URL(url, "http://localhost").pathname; + const match = pathname.match(/\/sso\/(?:saml2\/)?callback\/([^/]+)$/); + return match?.[1] ?? null; + } catch { + return null; + } +} + export function extractProviderIdFromContext(ctx?: GenericEndpointContext | null) { if (!ctx) { return null; @@ -14,15 +24,7 @@ export function extractProviderIdFromContext(ctx?: GenericEndpointContext | null } if (ctx.request?.url) { - try { - const pathname = new URL(ctx.request.url, "http://localhost").pathname; - const ssoCallbackMatch = pathname.match(/\/sso\/(?:saml2\/)?callback\/([^/]+)$/); - if (ssoCallbackMatch) { - return ssoCallbackMatch[1]; - } - } catch { - return null; - } + return extractProviderIdFromUrl(ctx.request.url); } return null;