fix(login): Prevent double execution of IDP callback token and improve architecture (#10948)

Closes #10828 

# Which Problems Are Solved

The IDP callback flow was calling retrieveIDPIntent() twice, causing
single-use token failures with error: "Intent Token is invalid". This
occurred due to Next.js 15's dynamicIO feature triggering double renders

# How the Problems Are Solved

Completely refactored the IDP callback architecture to ensure single-use
tokens are consumed exactly once:

- Centralized Business Logic: Moved all IDP callback logic into a single
server action (processIDPCallback) that:
   - Consumes the token once
- Handles all 6 business scenarios (login, linking, auto-linking,
auto-creation, manual registration, account not found)
   - Integrates session creation in the same action
- Returns `{ redirect?: string; error?: string }` for client-side
navigation
- Client Component Invocation: Created `IdpProcessHandler` client
component that:
- Calls the server action from browser context (enables cookie
modification)
   - Prevents double execution with useRef
   - Handles loading states and error display
- Clean Architecture:
   - Removed 403-line success page with complex logic
   - Removed component files from `/components/idps/pages/` folder
   - Moved all UI directly into server pages
   - Created dedicated result pages with minimal params

# Additional Changes

- Added translations to all 8 supported languages

---------

Co-authored-by: Ramon <[email protected]>
This commit is contained in:
Max Peintner
2025-10-27 14:34:39 +01:00
committed by GitHub
co-authored by Ramon
parent 5d75e41d00
commit 9dc127ddb5
23 changed files with 1589 additions and 652 deletions
+1 -1
View File
@@ -141,7 +141,7 @@ export async function handleOIDCFlowInitiation(params: FlowInitiationParams): Pr
serviceUrl,
idpId,
urls: {
successUrl: `${origin}/idp/${provider}/success?` + new URLSearchParams(params),
successUrl: `${origin}/idp/${provider}/process?` + new URLSearchParams(params),
failureUrl: `${origin}/idp/${provider}/failure?` + new URLSearchParams(params),
},
});
@@ -0,0 +1,779 @@
import { describe, expect, test, vi, beforeEach, afterEach } from "vitest";
import { processIDPCallback } from "./idp-intent";
import { AutoLinkingOption } from "@zitadel/proto/zitadel/idp/v2/idp_pb";
// Mock all the dependencies
vi.mock("next/headers", () => ({
headers: vi.fn(),
}));
vi.mock("@zitadel/client", () => ({
create: vi.fn((schema: any, data: any) => data),
}));
vi.mock("../service-url", () => ({
getServiceUrlFromHeaders: vi.fn(),
}));
vi.mock("../zitadel", () => ({
retrieveIDPIntent: vi.fn(),
getIDPByID: vi.fn(),
updateHuman: vi.fn(),
addIDPLink: vi.fn(),
listUsers: vi.fn(),
addHuman: vi.fn(),
getLoginSettings: vi.fn(),
getOrgsByDomain: vi.fn(),
}));
vi.mock("./idp", () => ({
createNewSessionFromIdpIntent: vi.fn(),
}));
vi.mock("next-intl/server", () => ({
getTranslations: vi.fn(() => (key: string) => key),
}));
describe("processIDPCallback", () => {
// Mock modules
let mockHeaders: any;
let mockGetServiceUrlFromHeaders: any;
let mockRetrieveIDPIntent: any;
let mockGetIDPByID: any;
let mockUpdateHuman: any;
let mockAddIDPLink: any;
let mockListUsers: any;
let mockAddHuman: any;
let mockGetLoginSettings: any;
let mockGetOrgsByDomain: any;
let mockCreateNewSessionFromIdpIntent: any;
const defaultParams = {
provider: "google",
id: "intent123",
token: "token123",
requestId: "req123",
organization: "org123",
};
const defaultIntent = {
idpInformation: {
idpId: "idp123",
userId: "user123",
userName: "testuser",
},
userId: "user123",
addHumanUser: {
username: "testuser",
profile: {
givenName: "Test",
familyName: "User",
displayName: "Test User",
},
email: {
email: "[email protected]",
},
},
};
const defaultIdp = {
id: "idp123",
config: {
options: {
isAutoUpdate: false,
isLinkingAllowed: false,
isCreationAllowed: false,
isAutoCreation: false,
autoLinking: undefined,
},
},
};
beforeEach(async () => {
vi.clearAllMocks();
// Import mocked modules
const { headers } = await import("next/headers");
const { getServiceUrlFromHeaders } = await import("../service-url");
const {
retrieveIDPIntent,
getIDPByID,
updateHuman,
addIDPLink,
listUsers,
addHuman,
getLoginSettings,
getOrgsByDomain,
} = await import("../zitadel");
const { createNewSessionFromIdpIntent } = await import("./idp");
// Setup mocks
mockHeaders = vi.mocked(headers);
mockGetServiceUrlFromHeaders = vi.mocked(getServiceUrlFromHeaders);
mockRetrieveIDPIntent = vi.mocked(retrieveIDPIntent);
mockGetIDPByID = vi.mocked(getIDPByID);
mockUpdateHuman = vi.mocked(updateHuman);
mockAddIDPLink = vi.mocked(addIDPLink);
mockListUsers = vi.mocked(listUsers);
mockAddHuman = vi.mocked(addHuman);
mockGetLoginSettings = vi.mocked(getLoginSettings);
mockGetOrgsByDomain = vi.mocked(getOrgsByDomain);
mockCreateNewSessionFromIdpIntent = vi.mocked(createNewSessionFromIdpIntent);
// Default mock implementations
mockHeaders.mockResolvedValue({} as any);
mockGetServiceUrlFromHeaders.mockReturnValue({
serviceUrl: "https://api.example.com",
});
mockRetrieveIDPIntent.mockResolvedValue(defaultIntent);
mockGetIDPByID.mockResolvedValue(defaultIdp);
mockCreateNewSessionFromIdpIntent.mockResolvedValue({
redirect: "https://app.example.com/success",
});
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("Parameter validation", () => {
test("should return error redirect when provider is missing", async () => {
const result = await processIDPCallback({
provider: "",
id: "intent123",
token: "token123",
});
expect(result.redirect).toContain("/idp//failure");
expect(mockRetrieveIDPIntent).not.toHaveBeenCalled();
});
test("should return error redirect when id is missing", async () => {
const result = await processIDPCallback({
provider: "google",
id: "",
token: "token123",
});
expect(result.redirect).toContain("/idp/google/failure");
expect(mockRetrieveIDPIntent).not.toHaveBeenCalled();
});
test("should return error redirect when token is missing", async () => {
const result = await processIDPCallback({
provider: "google",
id: "intent123",
token: "",
});
expect(result.redirect).toContain("/idp/google/failure");
expect(mockRetrieveIDPIntent).not.toHaveBeenCalled();
});
test("should preserve requestId and organization in error redirect", async () => {
const result = await processIDPCallback({
provider: "google",
id: "",
token: "token123",
requestId: "req123",
organization: "org123",
});
expect(result.redirect).toContain("requestId=req123");
expect(result.redirect).toContain("organization=org123");
});
});
describe("Intent retrieval errors", () => {
test("should return error redirect when IDP information is missing", async () => {
mockRetrieveIDPIntent.mockResolvedValue({
idpInformation: undefined,
userId: "user123",
});
const result = await processIDPCallback(defaultParams);
expect(result.redirect).toContain("/idp/google/failure");
expect(result.redirect).toContain("error=missing_idp_info");
});
test("should return error when IDP is not found", async () => {
mockGetIDPByID.mockResolvedValue(null);
const result = await processIDPCallback(defaultParams);
expect(result.error).toBe("errors.idpNotFound");
});
test("should handle retrieval errors gracefully", async () => {
mockRetrieveIDPIntent.mockRejectedValue(new Error("Network error"));
const result = await processIDPCallback(defaultParams);
expect(result.redirect).toContain("/idp/google/failure");
expect(result.redirect).toContain("error=Network+error");
});
});
describe("CASE 1: User exists and should sign in", () => {
test("should create session for existing user without auto-update", async () => {
const result = await processIDPCallback(defaultParams);
expect(mockRetrieveIDPIntent).toHaveBeenCalledWith({
serviceUrl: "https://api.example.com",
id: "intent123",
token: "token123",
});
expect(mockCreateNewSessionFromIdpIntent).toHaveBeenCalledWith({
userId: "user123",
idpIntent: {
idpIntentId: "intent123",
idpIntentToken: "token123",
},
requestId: "req123",
organization: "org123",
});
expect(result.redirect).toBe("https://app.example.com/success");
});
test("should auto-update user profile when enabled", async () => {
mockGetIDPByID.mockResolvedValue({
...defaultIdp,
config: {
options: {
...defaultIdp.config.options,
isAutoUpdate: true,
},
},
});
await processIDPCallback(defaultParams);
expect(mockUpdateHuman).toHaveBeenCalledWith({
serviceUrl: "https://api.example.com",
request: expect.objectContaining({
userId: "user123",
profile: defaultIntent.addHumanUser.profile,
email: defaultIntent.addHumanUser.email,
}),
});
});
test("should continue session creation even if auto-update fails", async () => {
mockGetIDPByID.mockResolvedValue({
...defaultIdp,
config: {
options: {
...defaultIdp.config.options,
isAutoUpdate: true,
},
},
});
mockUpdateHuman.mockRejectedValue(new Error("Update failed"));
const result = await processIDPCallback(defaultParams);
expect(mockCreateNewSessionFromIdpIntent).toHaveBeenCalled();
expect(result.redirect).toBe("https://app.example.com/success");
});
test("should return error when session creation fails", async () => {
mockCreateNewSessionFromIdpIntent.mockResolvedValue({
error: "Session creation error",
});
const result = await processIDPCallback(defaultParams);
expect(result.error).toBe("Session creation error");
});
test("should return error when session creation returns neither redirect nor error", async () => {
mockCreateNewSessionFromIdpIntent.mockResolvedValue({});
const result = await processIDPCallback(defaultParams);
expect(result.error).toBe("errors.sessionCreationFailed");
});
});
describe("CASE 2: Link IDP to existing user", () => {
const linkParams = {
...defaultParams,
link: "true",
};
test("should link IDP and create session when linking is allowed", async () => {
mockGetIDPByID.mockResolvedValue({
...defaultIdp,
config: {
options: {
...defaultIdp.config.options,
isLinkingAllowed: true,
},
},
});
const result = await processIDPCallback(linkParams);
expect(mockAddIDPLink).toHaveBeenCalledWith({
serviceUrl: "https://api.example.com",
idp: {
id: "idp123",
userId: "user123",
userName: "testuser",
},
userId: "user123",
});
expect(mockCreateNewSessionFromIdpIntent).toHaveBeenCalled();
expect(result.redirect).toBe("https://app.example.com/success");
});
test("should return error redirect when linking is not allowed", async () => {
const result = await processIDPCallback(linkParams);
expect(result.redirect).toContain("/idp/google/linking-failed");
expect(result.redirect).toContain("error=linking_not_allowed");
expect(mockAddIDPLink).not.toHaveBeenCalled();
});
test("should return error redirect when linking fails", async () => {
mockGetIDPByID.mockResolvedValue({
...defaultIdp,
config: {
options: {
...defaultIdp.config.options,
isLinkingAllowed: true,
},
},
});
mockAddIDPLink.mockRejectedValue(new Error("Linking failed"));
const result = await processIDPCallback(linkParams);
expect(result.redirect).toContain("/idp/google/linking-failed");
});
test("should return error when session creation fails after linking", async () => {
mockGetIDPByID.mockResolvedValue({
...defaultIdp,
config: {
options: {
...defaultIdp.config.options,
isLinkingAllowed: true,
},
},
});
mockCreateNewSessionFromIdpIntent.mockResolvedValue({
error: "Session error",
});
const result = await processIDPCallback(linkParams);
expect(result.error).toBe("Session error");
});
});
describe("CASE 3: Auto-linking by email", () => {
beforeEach(() => {
mockRetrieveIDPIntent.mockResolvedValue({
...defaultIntent,
userId: undefined, // No existing userId
});
mockGetIDPByID.mockResolvedValue({
...defaultIdp,
config: {
options: {
...defaultIdp.config.options,
autoLinking: AutoLinkingOption.EMAIL,
},
},
});
});
test("should auto-link user by email and create session", async () => {
const foundUser = { userId: "found123" };
mockListUsers.mockResolvedValue({
result: [foundUser],
});
const result = await processIDPCallback(defaultParams);
expect(mockListUsers).toHaveBeenCalledWith({
serviceUrl: "https://api.example.com",
email: "[email protected]",
organizationId: "org123",
});
expect(mockAddIDPLink).toHaveBeenCalledWith({
serviceUrl: "https://api.example.com",
idp: {
id: "idp123",
userId: "user123",
userName: "testuser",
},
userId: "found123",
});
expect(mockCreateNewSessionFromIdpIntent).toHaveBeenCalledWith({
userId: "found123",
idpIntent: {
idpIntentId: "intent123",
idpIntentToken: "token123",
},
requestId: "req123",
organization: "org123",
});
expect(result.redirect).toBe("https://app.example.com/success");
});
test("should continue to next case when no user found by email", async () => {
mockListUsers.mockResolvedValue({
result: [],
});
const result = await processIDPCallback(defaultParams);
expect(mockAddIDPLink).not.toHaveBeenCalled();
expect(result.redirect).toContain("/idp/google/account-not-found");
});
test("should return error redirect when auto-linking fails", async () => {
mockListUsers.mockResolvedValue({
result: [{ userId: "found123" }],
});
mockAddIDPLink.mockRejectedValue(new Error("Linking failed"));
const result = await processIDPCallback(defaultParams);
expect(result.redirect).toContain("/idp/google/linking-failed");
});
});
describe("CASE 3: Auto-linking by username", () => {
beforeEach(() => {
mockRetrieveIDPIntent.mockResolvedValue({
...defaultIntent,
userId: undefined,
});
mockGetIDPByID.mockResolvedValue({
...defaultIdp,
config: {
options: {
...defaultIdp.config.options,
autoLinking: AutoLinkingOption.USERNAME,
},
},
});
});
test("should auto-link user by username", async () => {
mockListUsers.mockResolvedValue({
result: [{ userId: "found123" }],
});
const result = await processIDPCallback(defaultParams);
expect(mockListUsers).toHaveBeenCalledWith({
serviceUrl: "https://api.example.com",
userName: "testuser",
organizationId: "org123",
});
expect(mockAddIDPLink).toHaveBeenCalled();
expect(result.redirect).toBe("https://app.example.com/success");
});
});
describe("CASE 4: Auto-creation of user", () => {
beforeEach(() => {
mockRetrieveIDPIntent.mockResolvedValue({
...defaultIntent,
userId: undefined,
});
mockGetIDPByID.mockResolvedValue({
...defaultIdp,
config: {
options: {
...defaultIdp.config.options,
isAutoCreation: true,
},
},
});
});
test("should auto-create user and create session", async () => {
mockAddHuman.mockResolvedValue({
userId: "newuser123",
});
const result = await processIDPCallback(defaultParams);
expect(mockAddHuman).toHaveBeenCalledWith({
serviceUrl: "https://api.example.com",
request: expect.objectContaining({
username: "testuser",
profile: defaultIntent.addHumanUser.profile,
email: defaultIntent.addHumanUser.email,
organization: expect.objectContaining({
org: { case: "orgId", value: "org123" },
}),
}),
});
expect(mockCreateNewSessionFromIdpIntent).toHaveBeenCalledWith({
userId: "newuser123",
idpIntent: {
idpIntentId: "intent123",
idpIntentToken: "token123",
},
requestId: "req123",
organization: "org123",
});
expect(result.redirect).toBe("https://app.example.com/success");
});
test("should resolve organization from username domain", async () => {
mockRetrieveIDPIntent.mockResolvedValue({
...defaultIntent,
userId: undefined,
addHumanUser: {
...defaultIntent.addHumanUser,
username: "[email protected]",
},
});
mockGetOrgsByDomain.mockResolvedValue({
result: [{ id: "org-from-domain" }],
});
mockGetLoginSettings.mockResolvedValue({
allowDomainDiscovery: true,
});
mockAddHuman.mockResolvedValue({ userId: "newuser123" });
await processIDPCallback({
...defaultParams,
organization: undefined,
});
expect(mockGetOrgsByDomain).toHaveBeenCalledWith({
serviceUrl: "https://api.example.com",
domain: "example.com",
});
expect(mockAddHuman).toHaveBeenCalledWith({
serviceUrl: "https://api.example.com",
request: expect.objectContaining({
organization: expect.objectContaining({
org: { case: "orgId", value: "org-from-domain" },
}),
}),
});
});
test("should create user without organization when not resolved", async () => {
mockAddHuman.mockResolvedValue({ userId: "newuser123" });
await processIDPCallback({
...defaultParams,
organization: undefined,
});
expect(mockAddHuman).toHaveBeenCalledWith({
serviceUrl: "https://api.example.com",
request: expect.not.objectContaining({
organization: expect.anything(),
}),
});
});
test("should return error redirect when user creation fails", async () => {
mockAddHuman.mockRejectedValue(new Error("Creation failed"));
const result = await processIDPCallback(defaultParams);
expect(result.redirect).toContain("/idp/google/failure");
expect(result.redirect).toContain("error=user_creation_failed");
});
test("should return error when session creation fails after user creation", async () => {
mockAddHuman.mockResolvedValue({ userId: "newuser123" });
mockCreateNewSessionFromIdpIntent.mockResolvedValue({
error: "Session error",
});
const result = await processIDPCallback(defaultParams);
expect(result.error).toBe("Session error");
});
});
describe("CASE 5: Manual user creation allowed", () => {
beforeEach(() => {
mockRetrieveIDPIntent.mockResolvedValue({
...defaultIntent,
userId: undefined,
});
mockGetIDPByID.mockResolvedValue({
...defaultIdp,
config: {
options: {
...defaultIdp.config.options,
isCreationAllowed: true,
},
},
});
});
test("should redirect to complete registration page with user data", async () => {
const result = await processIDPCallback(defaultParams);
expect(result.redirect).toContain("/idp/google/complete-registration");
expect(result.redirect).toContain("id=intent123");
expect(result.redirect).toContain("token=token123");
expect(result.redirect).toContain("requestId=req123");
expect(result.redirect).toContain("organization=org123");
expect(result.redirect).toContain("idpId=idp123");
expect(result.redirect).toContain("idpUserId=user123");
expect(result.redirect).toContain("idpUserName=testuser");
expect(result.redirect).toContain("givenName=Test");
expect(result.redirect).toContain("familyName=User");
expect(result.redirect).toContain("email=test%40example.com");
});
test("should redirect to registration failed when organization cannot be resolved", async () => {
const result = await processIDPCallback({
...defaultParams,
organization: undefined,
});
expect(result.redirect).toContain("/idp/google/registration-failed");
expect(result.redirect).toContain("id=intent123");
});
test("should resolve organization from domain for registration", async () => {
mockRetrieveIDPIntent.mockResolvedValue({
...defaultIntent,
userId: undefined,
addHumanUser: {
...defaultIntent.addHumanUser,
username: "[email protected]",
},
});
mockGetOrgsByDomain.mockResolvedValue({
result: [{ id: "org-from-domain" }],
});
mockGetLoginSettings.mockResolvedValue({
allowDomainDiscovery: true,
});
const result = await processIDPCallback({
...defaultParams,
organization: undefined,
});
expect(result.redirect).toContain("organization=org-from-domain");
});
});
describe("CASE 6: No user found and creation not allowed", () => {
beforeEach(() => {
mockRetrieveIDPIntent.mockResolvedValue({
...defaultIntent,
userId: undefined,
});
});
test("should redirect to account not found page", async () => {
const result = await processIDPCallback(defaultParams);
expect(result.redirect).toContain("/idp/google/account-not-found");
expect(result.redirect).toContain("id=intent123");
expect(result.redirect).toContain("requestId=req123");
expect(result.redirect).toContain("organization=org123");
});
});
describe("Priority of cases", () => {
test("should prioritize existing user sign-in over auto-linking", async () => {
mockGetIDPByID.mockResolvedValue({
...defaultIdp,
config: {
options: {
...defaultIdp.config.options,
autoLinking: AutoLinkingOption.EMAIL,
},
},
});
await processIDPCallback(defaultParams);
// Should not search for users when userId already exists
expect(mockListUsers).not.toHaveBeenCalled();
expect(mockCreateNewSessionFromIdpIntent).toHaveBeenCalledWith(
expect.objectContaining({
userId: "user123",
}),
);
});
test("should prioritize auto-linking over auto-creation", async () => {
mockRetrieveIDPIntent.mockResolvedValue({
...defaultIntent,
userId: undefined,
});
mockGetIDPByID.mockResolvedValue({
...defaultIdp,
config: {
options: {
...defaultIdp.config.options,
autoLinking: AutoLinkingOption.EMAIL,
isAutoCreation: true,
},
},
});
mockListUsers.mockResolvedValue({
result: [{ userId: "found123" }],
});
await processIDPCallback(defaultParams);
// Should link, not create
expect(mockAddIDPLink).toHaveBeenCalled();
expect(mockAddHuman).not.toHaveBeenCalled();
});
test("should prioritize auto-creation over manual creation", async () => {
mockRetrieveIDPIntent.mockResolvedValue({
...defaultIntent,
userId: undefined,
});
mockGetIDPByID.mockResolvedValue({
...defaultIdp,
config: {
options: {
...defaultIdp.config.options,
isAutoCreation: true,
isCreationAllowed: true,
},
},
});
mockAddHuman.mockResolvedValue({ userId: "newuser123" });
const result = await processIDPCallback(defaultParams);
// Should auto-create, not redirect to manual form
expect(mockAddHuman).toHaveBeenCalled();
expect(result.redirect).toBe("https://app.example.com/success");
expect(result.redirect).not.toContain("complete-registration");
});
});
describe("postErrorRedirectUrl handling", () => {
test("should preserve postErrorRedirectUrl in all redirects", async () => {
const paramsWithError = {
...defaultParams,
postErrorRedirectUrl: "https://app.example.com/error",
};
mockRetrieveIDPIntent.mockRejectedValue(new Error("Test error"));
const result = await processIDPCallback(paramsWithError);
expect(result.redirect).toContain("postErrorRedirectUrl=https%3A%2F%2Fapp.example.com%2Ferror");
});
});
});
+438
View File
@@ -0,0 +1,438 @@
"use server";
import { getServiceUrlFromHeaders } from "@/lib/service-url";
import {
retrieveIDPIntent,
getIDPByID,
updateHuman,
addIDPLink,
listUsers,
addHuman,
getLoginSettings,
getOrgsByDomain,
} from "@/lib/zitadel";
import { headers } from "next/headers";
import { create } from "@zitadel/client";
import { AutoLinkingOption } from "@zitadel/proto/zitadel/idp/v2/idp_pb";
import { OrganizationSchema } from "@zitadel/proto/zitadel/object/v2/object_pb";
import {
AddHumanUserRequest,
AddHumanUserRequestSchema,
UpdateHumanUserRequestSchema,
} from "@zitadel/proto/zitadel/user/v2/user_service_pb";
import { createNewSessionFromIdpIntent } from "./idp";
import { getTranslations } from "next-intl/server";
const ORG_SUFFIX_REGEX = /(?<=@)(.+)/;
async function resolveOrganizationForUser({
organization,
addHumanUser,
serviceUrl,
}: {
organization?: string;
addHumanUser?: AddHumanUserRequest;
serviceUrl: string;
}): Promise<string | undefined> {
if (organization) return organization;
if (addHumanUser?.username && ORG_SUFFIX_REGEX.test(addHumanUser.username)) {
const matched = ORG_SUFFIX_REGEX.exec(addHumanUser.username);
const suffix = matched?.[1] ?? "";
const orgs = await getOrgsByDomain({
serviceUrl,
domain: suffix,
});
const orgToCheckForDiscovery = orgs.result && orgs.result.length === 1 ? orgs.result[0].id : undefined;
if (orgToCheckForDiscovery) {
const orgLoginSettings = await getLoginSettings({
serviceUrl,
organization: orgToCheckForDiscovery,
});
if (orgLoginSettings?.allowDomainDiscovery) {
return orgToCheckForDiscovery;
}
}
}
return undefined;
}
/**
* Server action to process IDP callback and handle ALL business logic.
* This action:
* 1. Consumes the single-use token once
* 2. Performs all IDP-related operations (auto-update, auto-linking, auto-creation)
* 3. Returns redirect URL or error for client-side navigation
*/
export async function processIDPCallback({
provider,
id,
token,
requestId,
organization,
link,
postErrorRedirectUrl,
}: {
provider: string;
id: string;
token: string;
requestId?: string;
organization?: string;
link?: string;
postErrorRedirectUrl?: string;
}): Promise<{ redirect?: string; error?: string }> {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
const t = await getTranslations("idp");
// Validate required parameters
if (!provider || !id || !token) {
console.error("[IDP Process] Missing required parameters:", { provider, id, hasToken: !!token });
const errorParams = new URLSearchParams();
if (requestId) errorParams.set("requestId", requestId);
if (organization) errorParams.set("organization", organization);
if (postErrorRedirectUrl) errorParams.set("postErrorRedirectUrl", postErrorRedirectUrl);
return { redirect: `/idp/${provider}/failure?${errorParams.toString()}` };
}
try {
console.log("[IDP Process] Retrieving IDP intent (single call):", {
id,
tokenPreview: token.substring(0, 10) + "...",
timestamp: new Date().toISOString(),
});
// Consume the single-use token ONCE
const intent = await retrieveIDPIntent({
serviceUrl,
id,
token,
});
console.log("[IDP Process] Intent retrieved successfully, processing business logic");
const { idpInformation, userId, addHumanUser } = intent;
if (!idpInformation) {
console.error("[IDP Process] IDP information missing");
return { redirect: `/idp/${provider}/failure?error=missing_idp_info` };
}
// Get IDP configuration
const idp = await getIDPByID({
serviceUrl,
id: idpInformation.idpId,
});
if (!idp) {
return { error: t("errors.idpNotFound") };
}
const options = idp?.config?.options;
// Build base redirect params
const buildRedirectParams = (additionalParams?: Record<string, string>, includeToken: boolean = false) => {
const params = new URLSearchParams();
params.set("id", id);
if (includeToken) params.set("token", token);
if (requestId) params.set("requestId", requestId);
if (organization) params.set("organization", organization);
if (postErrorRedirectUrl) params.set("postErrorRedirectUrl", postErrorRedirectUrl);
if (additionalParams) {
Object.entries(additionalParams).forEach(([key, value]) => {
if (value) params.set(key, value);
});
}
return params.toString();
};
// ============================================
// CASE 1: User exists and should sign in
// ============================================
if (userId && !link) {
// Auto-update user if enabled
if (options?.isAutoUpdate && addHumanUser) {
try {
await updateHuman({
serviceUrl,
request: create(UpdateHumanUserRequestSchema, {
userId: userId,
profile: addHumanUser.profile,
email: addHumanUser.email,
phone: addHumanUser.phone,
}),
});
console.log("[IDP Process] User auto-updated successfully");
} catch (error: unknown) {
console.warn("[IDP Process] Error auto-updating user:", error);
}
}
// Create session and handle redirect
console.log("[IDP Process] Creating session for existing user");
const sessionResult = await createNewSessionFromIdpIntent({
userId,
idpIntent: {
idpIntentId: id,
idpIntentToken: token,
},
requestId,
organization,
});
if ("error" in sessionResult && sessionResult.error) {
console.error("[IDP Process] Error creating session:", sessionResult.error);
return { error: sessionResult.error };
}
if ("redirect" in sessionResult && sessionResult.redirect) {
console.log("[IDP Process] Session created, redirecting to:", sessionResult.redirect);
return { redirect: sessionResult.redirect };
}
return { error: t("errors.sessionCreationFailed") };
}
// ============================================
// CASE 2: Link IDP to existing user
// ============================================
if (link && userId) {
if (!options?.isLinkingAllowed) {
console.error("[IDP Process] Linking not allowed");
const params = buildRedirectParams();
return { redirect: `/idp/${provider}/linking-failed?${params}&error=linking_not_allowed` };
}
try {
await addIDPLink({
serviceUrl,
idp: {
id: idpInformation.idpId,
userId: idpInformation.userId,
userName: idpInformation.userName,
},
userId,
});
console.log("[IDP Process] IDP linked successfully, creating session");
// Create session after linking
const sessionResult = await createNewSessionFromIdpIntent({
userId,
idpIntent: {
idpIntentId: id,
idpIntentToken: token,
},
requestId,
organization,
});
if ("error" in sessionResult && sessionResult.error) {
console.error("[IDP Process] Error creating session:", sessionResult.error);
return { error: sessionResult.error };
}
if ("redirect" in sessionResult && sessionResult.redirect) {
console.log("[IDP Process] Session created, redirecting to:", sessionResult.redirect);
return { redirect: sessionResult.redirect };
}
return { error: t("errors.sessionCreationFailed") };
} catch (error) {
console.error("[IDP Process] Error linking IDP:", error);
const params = buildRedirectParams();
return { redirect: `/idp/${provider}/linking-failed?${params}` };
}
}
// ============================================
// CASE 3: Auto-linking (search for user and link)
// ============================================
if (options?.autoLinking) {
let foundUser;
const email = addHumanUser?.email?.email;
if (options.autoLinking === AutoLinkingOption.EMAIL && email) {
foundUser = await listUsers({ serviceUrl, email, organizationId: organization }).then((response) => {
return response.result ? response.result[0] : null;
});
} else if (options.autoLinking === AutoLinkingOption.USERNAME) {
foundUser = await listUsers({
serviceUrl,
userName: idpInformation.userName,
organizationId: organization,
}).then((response) => {
return response.result ? response.result[0] : null;
});
} else {
foundUser = await listUsers({
serviceUrl,
userName: idpInformation.userName,
email,
organizationId: organization,
}).then((response) => {
return response.result ? response.result[0] : null;
});
}
if (foundUser) {
try {
await addIDPLink({
serviceUrl,
idp: {
id: idpInformation.idpId,
userId: idpInformation.userId,
userName: idpInformation.userName,
},
userId: foundUser.userId,
});
console.log("[IDP Process] User auto-linked successfully, creating session");
// Create session after auto-linking
const sessionResult = await createNewSessionFromIdpIntent({
userId: foundUser.userId,
idpIntent: {
idpIntentId: id,
idpIntentToken: token,
},
requestId,
organization,
});
if ("error" in sessionResult && sessionResult.error) {
console.error("[IDP Process] Error creating session:", sessionResult.error);
return { error: sessionResult.error };
}
if ("redirect" in sessionResult && sessionResult.redirect) {
console.log("[IDP Process] Session created, redirecting to:", sessionResult.redirect);
return { redirect: sessionResult.redirect };
}
return { error: t("errors.sessionCreationFailed") };
} catch (error) {
console.error("[IDP Process] Error auto-linking user:", error);
const params = buildRedirectParams();
return { redirect: `/idp/${provider}/linking-failed?${params}` };
}
}
}
// ============================================
// CASE 4: Auto-creation of user
// ============================================
if (options?.isAutoCreation && addHumanUser) {
const orgToRegisterOn = await resolveOrganizationForUser({
organization,
addHumanUser,
serviceUrl,
});
let addHumanUserWithOrganization: AddHumanUserRequest;
if (orgToRegisterOn) {
const organizationSchema = create(OrganizationSchema, {
org: { case: "orgId", value: orgToRegisterOn },
});
addHumanUserWithOrganization = create(AddHumanUserRequestSchema, {
...addHumanUser,
organization: organizationSchema,
});
} else {
addHumanUserWithOrganization = create(AddHumanUserRequestSchema, addHumanUser);
}
try {
const newUser = await addHuman({
serviceUrl,
request: addHumanUserWithOrganization,
});
console.log("[IDP Process] User auto-created successfully, creating session");
// Create session for newly created user
const sessionResult = await createNewSessionFromIdpIntent({
userId: newUser.userId,
idpIntent: {
idpIntentId: id,
idpIntentToken: token,
},
requestId,
organization,
});
if ("error" in sessionResult && sessionResult.error) {
console.error("[IDP Process] Error creating session:", sessionResult.error);
return { error: sessionResult.error };
}
if ("redirect" in sessionResult && sessionResult.redirect) {
console.log("[IDP Process] Session created, redirecting to:", sessionResult.redirect);
return { redirect: sessionResult.redirect };
}
return { error: t("errors.sessionCreationFailed") };
} catch (error: unknown) {
console.error("[IDP Process] Error auto-creating user:", error);
const params = buildRedirectParams();
return { redirect: `/idp/${provider}/failure?${params}&error=user_creation_failed` };
}
}
// ============================================
// CASE 5: Manual user creation allowed
// ============================================
if (options?.isCreationAllowed && addHumanUser) {
const orgToRegisterOn = await resolveOrganizationForUser({
organization,
addHumanUser,
serviceUrl,
});
if (!orgToRegisterOn) {
console.error("[IDP Process] Could not determine organization for registration");
const params = buildRedirectParams();
return { redirect: `/idp/${provider}/registration-failed?${params}` };
}
// Store user data for manual registration form
// Note: includeToken=true because the session hasn't been created yet
// The token will be needed when registerUserAndLinkToIDP creates the session
const params = buildRedirectParams(
{
organization: orgToRegisterOn,
idpId: idpInformation.idpId,
idpUserId: idpInformation.userId || "",
idpUserName: idpInformation.userName || "",
// User data for pre-filling form
givenName: addHumanUser.profile?.givenName || "",
familyName: addHumanUser.profile?.familyName || "",
email: addHumanUser.email?.email || "",
},
true,
); // includeToken=true
return { redirect: `/idp/${provider}/complete-registration?${params}` };
}
// ============================================
// CASE 6: No user found and creation not allowed
// ============================================
console.log("[IDP Process] No matching user and creation not allowed");
const params = buildRedirectParams();
return { redirect: `/idp/${provider}/account-not-found?${params}` };
} catch (error: unknown) {
console.error("[IDP Process] Error processing intent:", error);
const errorParams = new URLSearchParams();
if (requestId) errorParams.set("requestId", requestId);
if (organization) errorParams.set("organization", organization);
if (postErrorRedirectUrl) errorParams.set("postErrorRedirectUrl", postErrorRedirectUrl);
errorParams.set("error", error instanceof Error ? error.message : t("errors.unknownError"));
return { redirect: `/idp/${provider}/failure?${errorParams.toString()}` };
}
}
+1 -1
View File
@@ -46,7 +46,7 @@ export async function redirectToIdp(prevState: RedirectToIdpState, formData: For
serviceUrl,
host,
idpId,
successUrl: `/idp/${provider}/success?` + params.toString(),
successUrl: `/idp/${provider}/process?` + params.toString(),
failureUrl: `/idp/${provider}/failure?` + params.toString(),
});