mirror of
https://github.com/andwati/zitadel.git
synced 2026-11-18 19:25:13 +00:00
chore(login): Extract auth flow utilities and eliminate RSC request interference (#10644)
The /login route was experiencing issues with React Server Component
(RSC) requests interfering with one-time authentication callbacks. When
users navigated to /login via client-side routing (router.push()),
Next.js automatically triggered _rsc requests that could consume
single-use createCallback tokens, breaking OIDC and SAML authentication
flows.
# Which Problems Are Solved
When users attempt to log in, Next.js automatically makes requests with
the `_rsc=1` query parameter for React Server Components. The current
implementation treats these as server errors:
```typescript
// Before
if (_rsc) {
return NextResponse.json({ error: "No _rsc supported" }, { status: 500 });
}
```
This results in:
- Spurious 500 error logs polluting monitoring systems
- False alerts for server failures
- Difficulty distinguishing real issues from benign RSC requests
# How the Problems Are Solved
This PR implements a comprehensive refactoring that:
- Eliminates RSC interference by providing server actions for internal
auth flow completion
- Separates concerns between external flow initiation and internal flow
completion
- Extracts shared utilities to improve code maintainability and
reusability
- Maintains full backward compatibility for external applications
# Additional Context
## New Architecture
- auth-flow.ts: Shared utilities for auth flow completion with RSC
protection
- flow-initiation.ts: Extracted OIDC/SAML flow initiation logic (~400
lines)
- auth.ts: Server actions for internal components
## Route Handler Simplification
- route.ts: Reduced from ~350 lines to ~75 lines
- External-only focus: Now handles only flow initiation for external
applications
- Removed completion logic: External apps use their own callback URLs
- Enhanced validation: Early RSC blocking and parameter validation
## Flow Logic Improvements
- Early return patterns: Guard clauses eliminate deep nesting
- Better error handling: Specific error messages for different failure
modes
- Fixed SAML flow: Addressed incomplete logic
- Consistent session handling: Unified approach across OIDC and SAML
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
"use server";
|
||||
|
||||
import { getAllSessions } from "@/lib/cookies";
|
||||
import { loginWithOIDCAndSession } from "@/lib/oidc";
|
||||
import { loginWithSAMLAndSession } from "@/lib/saml";
|
||||
import { getServiceUrlFromHeaders } from "@/lib/service-url";
|
||||
import { listSessions } from "@/lib/zitadel";
|
||||
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
export interface AuthFlowParams {
|
||||
sessionId: string;
|
||||
requestId: string;
|
||||
organization?: string;
|
||||
}
|
||||
|
||||
async function loadSessions({ serviceUrl, ids }: { serviceUrl: string; ids: string[] }): Promise<Session[]> {
|
||||
const response = await listSessions({
|
||||
serviceUrl,
|
||||
ids: ids.filter((id: string | undefined) => !!id),
|
||||
});
|
||||
|
||||
return response?.sessions ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Server Action to complete authentication flow
|
||||
* Complete OIDC/SAML authentication flow with session
|
||||
* This is the shared logic for flow completion
|
||||
* Returns either an error or a redirect URL for client-side navigation
|
||||
*/
|
||||
export async function completeAuthFlow(command: AuthFlowParams): Promise<{ error: string } | { redirect: string }> {
|
||||
const { sessionId, requestId } = command;
|
||||
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
const sessionCookies = await getAllSessions();
|
||||
const ids = sessionCookies.map((s) => s.id);
|
||||
let sessions: Session[] = [];
|
||||
|
||||
if (ids && ids.length) {
|
||||
sessions = await loadSessions({ serviceUrl, ids });
|
||||
}
|
||||
|
||||
if (requestId.startsWith("oidc_")) {
|
||||
// Complete OIDC flow
|
||||
const result = await loginWithOIDCAndSession({
|
||||
serviceUrl,
|
||||
authRequest: requestId.replace("oidc_", ""),
|
||||
sessionId,
|
||||
sessions,
|
||||
sessionCookies,
|
||||
});
|
||||
|
||||
// Safety net - ensure we always return a valid object
|
||||
if (!result || typeof result !== "object" || (!("redirect" in result) && !("error" in result))) {
|
||||
console.error("Auth flow: Invalid result from loginWithOIDCAndSession:", result);
|
||||
return { error: "Authentication completed but navigation failed" };
|
||||
}
|
||||
|
||||
return result;
|
||||
} else if (requestId.startsWith("saml_")) {
|
||||
// Complete SAML flow
|
||||
const result = await loginWithSAMLAndSession({
|
||||
serviceUrl,
|
||||
samlRequest: requestId.replace("saml_", ""),
|
||||
sessionId,
|
||||
sessions,
|
||||
sessionCookies,
|
||||
});
|
||||
|
||||
// Safety net - ensure we always return a valid object
|
||||
if (!result || typeof result !== "object" || (!("redirect" in result) && !("error" in result))) {
|
||||
console.error("Auth flow: Invalid result from loginWithSAMLAndSession:", result);
|
||||
return { error: "Authentication completed but navigation failed" };
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
return { error: "Invalid request ID format" };
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
import { constructUrl } from "@/lib/service-url";
|
||||
import { findValidSession } from "@/lib/session";
|
||||
import {
|
||||
createCallback,
|
||||
createResponse,
|
||||
getActiveIdentityProviders,
|
||||
getAuthRequest,
|
||||
getOrgsByDomain,
|
||||
getSAMLRequest,
|
||||
getSecuritySettings,
|
||||
startIdentityProviderFlow,
|
||||
} from "@/lib/zitadel";
|
||||
import { sendLoginname, SendLoginnameCommand } from "@/lib/server/loginname";
|
||||
import { idpTypeToSlug } from "@/lib/idp";
|
||||
import { create } from "@zitadel/client";
|
||||
import { Prompt } from "@zitadel/proto/zitadel/oidc/v2/authorization_pb";
|
||||
import {
|
||||
CreateCallbackRequestSchema,
|
||||
SessionSchema,
|
||||
} from "@zitadel/proto/zitadel/oidc/v2/oidc_service_pb";
|
||||
import { CreateResponseRequestSchema } from "@zitadel/proto/zitadel/saml/v2/saml_service_pb";
|
||||
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
|
||||
import { IdentityProviderType } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { DEFAULT_CSP } from "../../../constants/csp";
|
||||
|
||||
const ORG_SCOPE_REGEX = /urn:zitadel:iam:org:id:([0-9]+)/;
|
||||
const ORG_DOMAIN_SCOPE_REGEX = /urn:zitadel:iam:org:domain:primary:(.+)/;
|
||||
const IDP_SCOPE_REGEX = /urn:zitadel:iam:org:idp:id:(.+)/;
|
||||
|
||||
const gotoAccounts = ({
|
||||
request,
|
||||
requestId,
|
||||
organization,
|
||||
}: {
|
||||
request: NextRequest;
|
||||
requestId: string;
|
||||
organization?: string;
|
||||
}): NextResponse<unknown> => {
|
||||
const accountsUrl = constructUrl(request, "/accounts");
|
||||
|
||||
if (requestId) {
|
||||
accountsUrl.searchParams.set("requestId", requestId);
|
||||
}
|
||||
if (organization) {
|
||||
accountsUrl.searchParams.set("organization", organization);
|
||||
}
|
||||
|
||||
return NextResponse.redirect(accountsUrl);
|
||||
};
|
||||
|
||||
export interface FlowInitiationParams {
|
||||
serviceUrl: string;
|
||||
requestId: string;
|
||||
sessions: Session[];
|
||||
sessionCookies: any[];
|
||||
request: NextRequest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle OIDC flow initiation
|
||||
*/
|
||||
export async function handleOIDCFlowInitiation(params: FlowInitiationParams): Promise<NextResponse> {
|
||||
const { serviceUrl, requestId, sessions, sessionCookies, request } = params;
|
||||
|
||||
const { authRequest } = await getAuthRequest({
|
||||
serviceUrl,
|
||||
authRequestId: requestId.replace("oidc_", ""),
|
||||
});
|
||||
|
||||
let organization = "";
|
||||
let suffix = "";
|
||||
let idpId = "";
|
||||
|
||||
if (authRequest?.scope) {
|
||||
const orgScope = authRequest.scope.find((s: string) => ORG_SCOPE_REGEX.test(s));
|
||||
const idpScope = authRequest.scope.find((s: string) => IDP_SCOPE_REGEX.test(s));
|
||||
|
||||
if (orgScope) {
|
||||
const matched = ORG_SCOPE_REGEX.exec(orgScope);
|
||||
organization = matched?.[1] ?? "";
|
||||
} else {
|
||||
const orgDomainScope = authRequest.scope.find((s: string) => ORG_DOMAIN_SCOPE_REGEX.test(s));
|
||||
|
||||
if (orgDomainScope) {
|
||||
const matched = ORG_DOMAIN_SCOPE_REGEX.exec(orgDomainScope);
|
||||
const orgDomain = matched?.[1] ?? "";
|
||||
if (orgDomain) {
|
||||
const orgs = await getOrgsByDomain({
|
||||
serviceUrl,
|
||||
domain: orgDomain,
|
||||
});
|
||||
if (orgs.result && orgs.result.length === 1) {
|
||||
organization = orgs.result[0].id ?? "";
|
||||
suffix = orgDomain;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (idpScope) {
|
||||
const matched = IDP_SCOPE_REGEX.exec(idpScope);
|
||||
idpId = matched?.[1] ?? "";
|
||||
|
||||
const identityProviders = await getActiveIdentityProviders({
|
||||
serviceUrl,
|
||||
orgId: organization ? organization : undefined,
|
||||
}).then((resp) => {
|
||||
return resp.identityProviders;
|
||||
});
|
||||
|
||||
const idp = identityProviders.find((idp) => idp.id === idpId);
|
||||
|
||||
if (idp) {
|
||||
const origin = request.nextUrl.origin;
|
||||
const identityProviderType = identityProviders[0].type;
|
||||
|
||||
if (identityProviderType === IdentityProviderType.LDAP) {
|
||||
const ldapUrl = constructUrl(request, "/ldap");
|
||||
if (authRequest.id) {
|
||||
ldapUrl.searchParams.set("requestId", `oidc_${authRequest.id}`);
|
||||
}
|
||||
if (organization) {
|
||||
ldapUrl.searchParams.set("organization", organization);
|
||||
}
|
||||
|
||||
return NextResponse.redirect(ldapUrl);
|
||||
}
|
||||
|
||||
let provider = idpTypeToSlug(identityProviderType);
|
||||
|
||||
const params = new URLSearchParams({
|
||||
requestId: requestId,
|
||||
});
|
||||
|
||||
if (organization) {
|
||||
params.set("organization", organization);
|
||||
}
|
||||
|
||||
let url: string | null = await startIdentityProviderFlow({
|
||||
serviceUrl,
|
||||
idpId,
|
||||
urls: {
|
||||
successUrl: `${origin}/idp/${provider}/success?` + new URLSearchParams(params),
|
||||
failureUrl: `${origin}/idp/${provider}/failure?` + new URLSearchParams(params),
|
||||
},
|
||||
});
|
||||
|
||||
if (!url) {
|
||||
return NextResponse.json({ error: "Could not start IDP flow" }, { status: 500 });
|
||||
}
|
||||
|
||||
if (url.startsWith("/")) {
|
||||
url = constructUrl(request, url).toString();
|
||||
}
|
||||
|
||||
return NextResponse.redirect(url);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (authRequest && authRequest.prompt.includes(Prompt.CREATE)) {
|
||||
const registerUrl = constructUrl(request, "/register");
|
||||
registerUrl.searchParams.set("requestId", requestId);
|
||||
|
||||
if (organization) {
|
||||
registerUrl.searchParams.set("organization", organization);
|
||||
}
|
||||
|
||||
return NextResponse.redirect(registerUrl);
|
||||
}
|
||||
|
||||
// use existing session and hydrate it for oidc
|
||||
if (authRequest && sessions.length) {
|
||||
if (authRequest.prompt.includes(Prompt.SELECT_ACCOUNT)) {
|
||||
return gotoAccounts({
|
||||
request,
|
||||
requestId: `oidc_${authRequest.id}`,
|
||||
organization,
|
||||
});
|
||||
} else if (authRequest.prompt.includes(Prompt.LOGIN)) {
|
||||
if (authRequest.loginHint) {
|
||||
try {
|
||||
let command: SendLoginnameCommand = {
|
||||
loginName: authRequest.loginHint,
|
||||
requestId: authRequest.id,
|
||||
};
|
||||
|
||||
if (organization) {
|
||||
command = { ...command, organization };
|
||||
}
|
||||
|
||||
const res = await sendLoginname(command);
|
||||
|
||||
if (res && "redirect" in res && res?.redirect) {
|
||||
const absoluteUrl = constructUrl(request, res.redirect);
|
||||
return NextResponse.redirect(absoluteUrl.toString());
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to execute sendLoginname:", error);
|
||||
}
|
||||
}
|
||||
|
||||
const loginNameUrl = constructUrl(request, "/loginname");
|
||||
loginNameUrl.searchParams.set("requestId", requestId);
|
||||
|
||||
if (authRequest.loginHint) {
|
||||
loginNameUrl.searchParams.set("loginName", authRequest.loginHint);
|
||||
}
|
||||
if (organization) {
|
||||
loginNameUrl.searchParams.set("organization", organization);
|
||||
}
|
||||
if (suffix) {
|
||||
loginNameUrl.searchParams.set("suffix", suffix);
|
||||
}
|
||||
return NextResponse.redirect(loginNameUrl);
|
||||
} else if (authRequest.prompt.includes(Prompt.NONE)) {
|
||||
const securitySettings = await getSecuritySettings({
|
||||
serviceUrl,
|
||||
});
|
||||
|
||||
const selectedSession = await findValidSession({
|
||||
serviceUrl,
|
||||
sessions,
|
||||
authRequest,
|
||||
});
|
||||
|
||||
const noSessionResponse = NextResponse.json({ error: "No active session found" }, { status: 400 });
|
||||
|
||||
if (securitySettings?.embeddedIframe?.enabled) {
|
||||
securitySettings.embeddedIframe.allowedOrigins;
|
||||
noSessionResponse.headers.set(
|
||||
"Content-Security-Policy",
|
||||
`${DEFAULT_CSP} frame-ancestors ${securitySettings.embeddedIframe.allowedOrigins.join(" ")};`,
|
||||
);
|
||||
noSessionResponse.headers.delete("X-Frame-Options");
|
||||
}
|
||||
|
||||
if (!selectedSession || !selectedSession.id) {
|
||||
return noSessionResponse;
|
||||
}
|
||||
|
||||
const cookie = sessionCookies.find((cookie) => cookie.id === selectedSession.id);
|
||||
|
||||
if (!cookie || !cookie.id || !cookie.token) {
|
||||
return noSessionResponse;
|
||||
}
|
||||
|
||||
const session = {
|
||||
sessionId: cookie.id,
|
||||
sessionToken: cookie.token,
|
||||
};
|
||||
|
||||
const { callbackUrl } = await createCallback({
|
||||
serviceUrl,
|
||||
req: create(CreateCallbackRequestSchema, {
|
||||
authRequestId: requestId.replace("oidc_", ""),
|
||||
callbackKind: {
|
||||
case: "session",
|
||||
value: create(SessionSchema, session),
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const callbackResponse = NextResponse.redirect(callbackUrl);
|
||||
|
||||
if (securitySettings?.embeddedIframe?.enabled) {
|
||||
securitySettings.embeddedIframe.allowedOrigins;
|
||||
callbackResponse.headers.set(
|
||||
"Content-Security-Policy",
|
||||
`${DEFAULT_CSP} frame-ancestors ${securitySettings.embeddedIframe.allowedOrigins.join(" ")};`,
|
||||
);
|
||||
callbackResponse.headers.delete("X-Frame-Options");
|
||||
}
|
||||
|
||||
return callbackResponse;
|
||||
} else {
|
||||
let selectedSession = await findValidSession({
|
||||
serviceUrl,
|
||||
sessions,
|
||||
authRequest,
|
||||
});
|
||||
|
||||
if (!selectedSession || !selectedSession.id) {
|
||||
return gotoAccounts({
|
||||
request,
|
||||
requestId: `oidc_${authRequest.id}`,
|
||||
organization,
|
||||
});
|
||||
}
|
||||
|
||||
const cookie = sessionCookies.find((cookie) => cookie.id === selectedSession.id);
|
||||
|
||||
if (!cookie || !cookie.id || !cookie.token) {
|
||||
return gotoAccounts({
|
||||
request,
|
||||
requestId: `oidc_${authRequest.id}`,
|
||||
organization,
|
||||
});
|
||||
}
|
||||
|
||||
const session = {
|
||||
sessionId: cookie.id,
|
||||
sessionToken: cookie.token,
|
||||
};
|
||||
|
||||
try {
|
||||
const { callbackUrl } = await createCallback({
|
||||
serviceUrl,
|
||||
req: create(CreateCallbackRequestSchema, {
|
||||
authRequestId: requestId.replace("oidc_", ""),
|
||||
callbackKind: {
|
||||
case: "session",
|
||||
value: create(SessionSchema, session),
|
||||
},
|
||||
}),
|
||||
});
|
||||
if (callbackUrl) {
|
||||
return NextResponse.redirect(callbackUrl);
|
||||
} else {
|
||||
console.log("could not create callback, redirect user to choose other account");
|
||||
return gotoAccounts({
|
||||
request,
|
||||
organization,
|
||||
requestId,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return gotoAccounts({
|
||||
request,
|
||||
requestId,
|
||||
organization,
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const loginNameUrl = constructUrl(request, "/loginname");
|
||||
loginNameUrl.searchParams.set("requestId", requestId);
|
||||
|
||||
if (authRequest?.loginHint) {
|
||||
loginNameUrl.searchParams.set("loginName", authRequest.loginHint);
|
||||
loginNameUrl.searchParams.set("submit", "true");
|
||||
}
|
||||
|
||||
if (organization) {
|
||||
loginNameUrl.searchParams.append("organization", organization);
|
||||
}
|
||||
|
||||
return NextResponse.redirect(loginNameUrl);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle SAML flow initiation
|
||||
*/
|
||||
export async function handleSAMLFlowInitiation(params: FlowInitiationParams): Promise<NextResponse> {
|
||||
const { serviceUrl, requestId, sessions, sessionCookies, request } = params;
|
||||
|
||||
const { samlRequest } = await getSAMLRequest({
|
||||
serviceUrl,
|
||||
samlRequestId: requestId.replace("saml_", ""),
|
||||
});
|
||||
|
||||
if (!samlRequest) {
|
||||
return NextResponse.json({ error: "No samlRequest found" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Early return: No sessions available - redirect to login
|
||||
if (sessions.length === 0) {
|
||||
const loginNameUrl = constructUrl(request, "/loginname");
|
||||
loginNameUrl.searchParams.set("requestId", requestId);
|
||||
return NextResponse.redirect(loginNameUrl);
|
||||
}
|
||||
|
||||
// Try to find a valid session
|
||||
let selectedSession = await findValidSession({
|
||||
serviceUrl,
|
||||
sessions,
|
||||
samlRequest,
|
||||
});
|
||||
|
||||
// Early return: No valid session found - show account selection
|
||||
if (!selectedSession || !selectedSession.id) {
|
||||
return gotoAccounts({
|
||||
request,
|
||||
requestId,
|
||||
});
|
||||
}
|
||||
|
||||
const cookie = sessionCookies.find((cookie) => cookie.id === selectedSession.id);
|
||||
|
||||
// Early return: No valid cookie/token found - show account selection
|
||||
// Note: We need the session token from the cookie to authenticate API calls
|
||||
if (!cookie || !cookie.id || !cookie.token) {
|
||||
return gotoAccounts({
|
||||
request,
|
||||
requestId,
|
||||
});
|
||||
}
|
||||
|
||||
// Valid session and cookie found - attempt to complete SAML flow
|
||||
const session = {
|
||||
sessionId: cookie.id,
|
||||
sessionToken: cookie.token,
|
||||
};
|
||||
|
||||
try {
|
||||
const { url, binding } = await createResponse({
|
||||
serviceUrl,
|
||||
req: create(CreateResponseRequestSchema, {
|
||||
samlRequestId: requestId.replace("saml_", ""),
|
||||
responseKind: {
|
||||
case: "session",
|
||||
value: session,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
if (url && binding.case === "redirect") {
|
||||
return NextResponse.redirect(url);
|
||||
} else if (url && binding.case === "post") {
|
||||
const html = `
|
||||
<html>
|
||||
<body onload="document.forms[0].submit()">
|
||||
<form action="${url}" method="post">
|
||||
<input type="hidden" name="RelayState" value="${binding.value.relayState}" />
|
||||
<input type="hidden" name="SAMLResponse" value="${binding.value.samlResponse}" />
|
||||
<noscript>
|
||||
<button type="submit">Continue</button>
|
||||
</noscript>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
|
||||
return new NextResponse(html, {
|
||||
headers: { "Content-Type": "text/html" },
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("SAML createResponse failed:", error);
|
||||
}
|
||||
|
||||
// Final fallback: SAML response creation failed - show account selection
|
||||
return gotoAccounts({
|
||||
request,
|
||||
requestId,
|
||||
});
|
||||
}
|
||||
@@ -3,22 +3,20 @@
|
||||
import {
|
||||
getLoginSettings,
|
||||
getUserByID,
|
||||
listAuthenticationMethodTypes,
|
||||
startIdentityProviderFlow,
|
||||
startLDAPIdentityProviderFlow,
|
||||
} from "@/lib/zitadel";
|
||||
import { headers } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getNextUrl } from "../client";
|
||||
import { completeFlowOrGetUrl } from "../client";
|
||||
import { getServiceUrlFromHeaders } from "../service-url";
|
||||
import { checkEmailVerification } from "../verify-helper";
|
||||
import { checkEmailVerification, checkMFAFactors } from "../verify-helper";
|
||||
import { createSessionForIdpAndUpdateCookie } from "./cookie";
|
||||
|
||||
export type RedirectToIdpState = { error?: string | null } | undefined;
|
||||
|
||||
export async function redirectToIdp(
|
||||
prevState: RedirectToIdpState,
|
||||
formData: FormData,
|
||||
): Promise<RedirectToIdpState> {
|
||||
export async function redirectToIdp(prevState: RedirectToIdpState, formData: FormData): Promise<RedirectToIdpState> {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
const host = _headers.get("host");
|
||||
@@ -102,9 +100,7 @@ type CreateNewSessionCommand = {
|
||||
requestId?: string;
|
||||
};
|
||||
|
||||
export async function createNewSessionFromIdpIntent(
|
||||
command: CreateNewSessionCommand,
|
||||
) {
|
||||
export async function createNewSessionFromIdpIntent(command: CreateNewSessionCommand) {
|
||||
const _headers = await headers();
|
||||
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
@@ -143,30 +139,43 @@ export async function createNewSessionFromIdpIntent(
|
||||
return { error: "Could not create session" };
|
||||
}
|
||||
|
||||
const humanUser =
|
||||
userResponse.user.type.case === "human"
|
||||
? userResponse.user.type.value
|
||||
: undefined;
|
||||
const humanUser = userResponse.user.type.case === "human" ? userResponse.user.type.value : undefined;
|
||||
|
||||
// check to see if user was verified
|
||||
const emailVerificationCheck = checkEmailVerification(
|
||||
session,
|
||||
humanUser,
|
||||
command.organization,
|
||||
command.requestId,
|
||||
);
|
||||
const emailVerificationCheck = checkEmailVerification(session, humanUser, command.organization, command.requestId);
|
||||
|
||||
if (emailVerificationCheck?.redirect) {
|
||||
return emailVerificationCheck;
|
||||
}
|
||||
|
||||
// TODO: check if user has MFA methods
|
||||
// const mfaFactorCheck = checkMFAFactors(session, loginSettings, authMethods, organization, requestId);
|
||||
// if (mfaFactorCheck?.redirect) {
|
||||
// return mfaFactorCheck;
|
||||
// }
|
||||
// check if user has MFA methods
|
||||
let authMethods;
|
||||
if (session.factors?.user?.id) {
|
||||
const response = await listAuthenticationMethodTypes({
|
||||
serviceUrl,
|
||||
userId: session.factors.user.id,
|
||||
});
|
||||
if (response.authMethodTypes && response.authMethodTypes.length) {
|
||||
authMethods = response.authMethodTypes;
|
||||
}
|
||||
}
|
||||
|
||||
const url = await getNextUrl(
|
||||
if (authMethods) {
|
||||
const mfaFactorCheck = await checkMFAFactors(
|
||||
serviceUrl,
|
||||
session,
|
||||
loginSettings,
|
||||
authMethods,
|
||||
command.organization,
|
||||
command.requestId,
|
||||
);
|
||||
|
||||
if (mfaFactorCheck?.redirect) {
|
||||
return mfaFactorCheck;
|
||||
}
|
||||
}
|
||||
|
||||
return completeFlowOrGetUrl(
|
||||
command.requestId && session.id
|
||||
? {
|
||||
sessionId: session.id,
|
||||
@@ -179,10 +188,6 @@ export async function createNewSessionFromIdpIntent(
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
|
||||
if (url) {
|
||||
return { redirect: url };
|
||||
}
|
||||
}
|
||||
|
||||
type createNewSessionForLDAPCommand = {
|
||||
@@ -192,9 +197,7 @@ type createNewSessionForLDAPCommand = {
|
||||
link: boolean;
|
||||
};
|
||||
|
||||
export async function createNewSessionForLDAP(
|
||||
command: createNewSessionForLDAPCommand,
|
||||
) {
|
||||
export async function createNewSessionForLDAP(command: createNewSessionForLDAPCommand) {
|
||||
const _headers = await headers();
|
||||
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
@@ -215,11 +218,7 @@ export async function createNewSessionForLDAP(
|
||||
password: command.password,
|
||||
});
|
||||
|
||||
if (
|
||||
!response ||
|
||||
response.nextStep.case !== "idpIntent" ||
|
||||
!response.nextStep.value
|
||||
) {
|
||||
if (!response || response.nextStep.case !== "idpIntent" || !response.nextStep.value) {
|
||||
return { error: "Could not start LDAP identity provider flow" };
|
||||
}
|
||||
|
||||
|
||||
@@ -18,17 +18,10 @@ import {
|
||||
} from "@zitadel/proto/zitadel/user/v2/user_service_pb";
|
||||
import { headers } from "next/headers";
|
||||
import { userAgent } from "next/server";
|
||||
import { getNextUrl } from "../client";
|
||||
import {
|
||||
getMostRecentSessionCookie,
|
||||
getSessionCookieById,
|
||||
getSessionCookieByLoginName,
|
||||
} from "../cookies";
|
||||
import { completeFlowOrGetUrl } from "../client";
|
||||
import { getMostRecentSessionCookie, getSessionCookieById, getSessionCookieByLoginName } from "../cookies";
|
||||
import { getServiceUrlFromHeaders } from "../service-url";
|
||||
import {
|
||||
checkEmailVerification,
|
||||
checkUserVerification,
|
||||
} from "../verify-helper";
|
||||
import { checkEmailVerification, checkUserVerification } from "../verify-helper";
|
||||
import { setSessionAndUpdateCookie } from "./cookie";
|
||||
|
||||
type VerifyPasskeyCommand = {
|
||||
@@ -48,9 +41,7 @@ function isSessionValid(session: Partial<Session>): {
|
||||
} {
|
||||
const validPassword = session?.factors?.password?.verifiedAt;
|
||||
const validPasskey = session?.factors?.webAuthN?.verifiedAt;
|
||||
const stillValid = session.expirationDate
|
||||
? timestampDate(session.expirationDate) > new Date()
|
||||
: true;
|
||||
const stillValid = session.expirationDate ? timestampDate(session.expirationDate) > new Date() : true;
|
||||
|
||||
const verifiedAt = validPassword || validPasskey;
|
||||
const valid = !!((validPassword || validPasskey) && stillValid);
|
||||
@@ -93,15 +84,12 @@ export async function registerPasskeyLink(
|
||||
// if the user has no authmethods set, we need to check if the user was verified
|
||||
if (authmethods.authMethodTypes.length !== 0) {
|
||||
return {
|
||||
error:
|
||||
"You have to authenticate or have a valid User Verification Check",
|
||||
error: "You have to authenticate or have a valid User Verification Check",
|
||||
};
|
||||
}
|
||||
|
||||
// check if a verification was done earlier
|
||||
const hasValidUserVerificationCheck = await checkUserVerification(
|
||||
session.session.factors.user.id,
|
||||
);
|
||||
const hasValidUserVerificationCheck = await checkUserVerification(session.session.factors.user.id);
|
||||
|
||||
if (!hasValidUserVerificationCheck) {
|
||||
return { error: "User Verification Check has to be done" };
|
||||
@@ -246,41 +234,30 @@ export async function sendPasskey(command: SendPasskeyCommand) {
|
||||
return { error: "User not found in the system" };
|
||||
}
|
||||
|
||||
const humanUser =
|
||||
userResponse.user.type.case === "human"
|
||||
? userResponse.user.type.value
|
||||
: undefined;
|
||||
const humanUser = userResponse.user.type.case === "human" ? userResponse.user.type.value : undefined;
|
||||
|
||||
const emailVerificationCheck = checkEmailVerification(
|
||||
session,
|
||||
humanUser,
|
||||
organization,
|
||||
requestId,
|
||||
);
|
||||
const emailVerificationCheck = checkEmailVerification(session, humanUser, organization, requestId);
|
||||
|
||||
if (emailVerificationCheck?.redirect) {
|
||||
return emailVerificationCheck;
|
||||
}
|
||||
|
||||
const url =
|
||||
requestId && session.id
|
||||
? await getNextUrl(
|
||||
{
|
||||
sessionId: session.id,
|
||||
requestId: requestId,
|
||||
organization: organization,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
)
|
||||
: session?.factors?.user?.loginName
|
||||
? await getNextUrl(
|
||||
{
|
||||
loginName: session.factors.user.loginName,
|
||||
organization: organization,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
)
|
||||
: null;
|
||||
|
||||
return { redirect: url };
|
||||
if (requestId && session.id) {
|
||||
return completeFlowOrGetUrl(
|
||||
{
|
||||
sessionId: session.id,
|
||||
requestId: requestId,
|
||||
organization: organization,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
} else if (session?.factors?.user?.loginName) {
|
||||
return completeFlowOrGetUrl(
|
||||
{
|
||||
loginName: session.factors.user.loginName,
|
||||
organization: organization,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
"use server";
|
||||
|
||||
import {
|
||||
createSessionAndUpdateCookie,
|
||||
setSessionAndUpdateCookie,
|
||||
} from "@/lib/server/cookie";
|
||||
import { createSessionAndUpdateCookie, setSessionAndUpdateCookie } from "@/lib/server/cookie";
|
||||
import {
|
||||
getLockoutSettings,
|
||||
getLoginSettings,
|
||||
@@ -18,18 +15,12 @@ import {
|
||||
} from "@/lib/zitadel";
|
||||
import { ConnectError, create, Duration } from "@zitadel/client";
|
||||
import { createUserServiceClient } from "@zitadel/client/v2";
|
||||
import {
|
||||
Checks,
|
||||
ChecksSchema,
|
||||
} from "@zitadel/proto/zitadel/session/v2/session_service_pb";
|
||||
import { Checks, ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
|
||||
import { LoginSettings } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb";
|
||||
import { User, UserState } from "@zitadel/proto/zitadel/user/v2/user_pb";
|
||||
import {
|
||||
AuthenticationMethodType,
|
||||
SetPasswordRequestSchema,
|
||||
} from "@zitadel/proto/zitadel/user/v2/user_service_pb";
|
||||
import { AuthenticationMethodType, SetPasswordRequestSchema } from "@zitadel/proto/zitadel/user/v2/user_service_pb";
|
||||
import { headers } from "next/headers";
|
||||
import { getNextUrl } from "../client";
|
||||
import { completeFlowOrGetUrl } from "../client";
|
||||
import { getSessionCookieById, getSessionCookieByLoginName } from "../cookies";
|
||||
import { getServiceUrlFromHeaders } from "../service-url";
|
||||
import {
|
||||
@@ -61,11 +52,7 @@ export async function resetPassword(command: ResetPasswordCommand) {
|
||||
organizationId: command.organization,
|
||||
});
|
||||
|
||||
if (
|
||||
!users.details ||
|
||||
users.details.totalResult !== BigInt(1) ||
|
||||
!users.result[0].userId
|
||||
) {
|
||||
if (!users.details || users.details.totalResult !== BigInt(1) || !users.result[0].userId) {
|
||||
return { error: "Could not send Password Reset Link" };
|
||||
}
|
||||
const userId = users.result[0].userId;
|
||||
@@ -88,7 +75,7 @@ export type UpdateSessionCommand = {
|
||||
requestId?: string;
|
||||
};
|
||||
|
||||
export async function sendPassword(command: UpdateSessionCommand) {
|
||||
export async function sendPassword(command: UpdateSessionCommand): Promise<{ error: string } | { redirect: string }> {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
@@ -139,18 +126,17 @@ export async function sendPassword(command: UpdateSessionCommand) {
|
||||
return {
|
||||
error:
|
||||
`Failed to authenticate. You had ${error.failedAttempts} of ${lockoutSettings?.maxPasswordAttempts} password attempts.` +
|
||||
(lockoutSettings?.maxPasswordAttempts &&
|
||||
error.failedAttempts >= lockoutSettings?.maxPasswordAttempts
|
||||
(lockoutSettings?.maxPasswordAttempts && error.failedAttempts >= lockoutSettings?.maxPasswordAttempts
|
||||
? "Contact your administrator to unlock your account"
|
||||
: ""),
|
||||
};
|
||||
}
|
||||
return { error: "Could not create session for user" };
|
||||
}
|
||||
} else {
|
||||
// this is a fake error message to hide that the user does not even exist
|
||||
return { error: "Could not verify password" };
|
||||
}
|
||||
|
||||
// this is a fake error message to hide that the user does not even exist
|
||||
return { error: "Could not verify password" };
|
||||
} else {
|
||||
loginSettings = await getLoginSettings({
|
||||
serviceUrl,
|
||||
@@ -188,8 +174,7 @@ export async function sendPassword(command: UpdateSessionCommand) {
|
||||
return {
|
||||
error:
|
||||
`Failed to authenticate. You had ${error.failedAttempts} of ${lockoutSettings?.maxPasswordAttempts} password attempts.` +
|
||||
(lockoutSettings?.maxPasswordAttempts &&
|
||||
error.failedAttempts >= lockoutSettings?.maxPasswordAttempts
|
||||
(lockoutSettings?.maxPasswordAttempts && error.failedAttempts >= lockoutSettings?.maxPasswordAttempts
|
||||
? " Contact your administrator to unlock your account"
|
||||
: ""),
|
||||
};
|
||||
@@ -216,12 +201,11 @@ export async function sendPassword(command: UpdateSessionCommand) {
|
||||
if (!loginSettings) {
|
||||
loginSettings = await getLoginSettings({
|
||||
serviceUrl,
|
||||
organization:
|
||||
command.organization ?? session.factors?.user?.organizationId,
|
||||
organization: command.organization ?? session.factors?.user?.organizationId,
|
||||
});
|
||||
}
|
||||
|
||||
if (!session?.factors?.user?.id || !sessionCookie) {
|
||||
if (!session?.factors?.user?.id) {
|
||||
return { error: "Could not create session for user" };
|
||||
}
|
||||
|
||||
@@ -251,12 +235,7 @@ export async function sendPassword(command: UpdateSessionCommand) {
|
||||
}
|
||||
|
||||
// check to see if user was verified
|
||||
const emailVerificationCheck = checkEmailVerification(
|
||||
session,
|
||||
humanUser,
|
||||
command.organization,
|
||||
command.requestId,
|
||||
);
|
||||
const emailVerificationCheck = checkEmailVerification(session, humanUser, command.organization, command.requestId);
|
||||
|
||||
if (emailVerificationCheck?.redirect) {
|
||||
return emailVerificationCheck;
|
||||
@@ -292,36 +271,49 @@ export async function sendPassword(command: UpdateSessionCommand) {
|
||||
}
|
||||
|
||||
if (command.requestId && session.id) {
|
||||
const nextUrl = await getNextUrl(
|
||||
// OIDC/SAML flow - use completeFlowOrGetUrl for proper handling
|
||||
console.log("Password auth: OIDC/SAML flow with requestId:", command.requestId, "sessionId:", session.id);
|
||||
const result = await completeFlowOrGetUrl(
|
||||
{
|
||||
sessionId: session.id,
|
||||
requestId: command.requestId,
|
||||
organization:
|
||||
command.organization ?? session.factors?.user?.organizationId,
|
||||
organization: command.organization ?? session.factors?.user?.organizationId,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
console.log("Password auth: OIDC/SAML flow result:", result);
|
||||
|
||||
return { redirect: nextUrl };
|
||||
// Safety net - ensure we always return a valid object
|
||||
if (!result || typeof result !== "object" || (!("redirect" in result) && !("error" in result))) {
|
||||
console.error("Password auth: Invalid result from completeFlowOrGetUrl (OIDC/SAML):", result);
|
||||
return { error: "Authentication completed but navigation failed" };
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
const url = await getNextUrl(
|
||||
// Regular flow (no requestId) - return URL for client-side navigation
|
||||
console.log("Password auth: Regular flow with loginName:", session.factors.user.loginName);
|
||||
const result = await completeFlowOrGetUrl(
|
||||
{
|
||||
loginName: session.factors.user.loginName,
|
||||
organization: session.factors?.user?.organizationId,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
console.log("Password auth: Regular flow result:", result);
|
||||
|
||||
return { redirect: url };
|
||||
// Safety net - ensure we always return a valid object
|
||||
if (!result || typeof result !== "object" || (!("redirect" in result) && !("error" in result))) {
|
||||
console.error("Password auth: Invalid result from completeFlowOrGetUrl:", result);
|
||||
return { error: "Authentication completed but navigation failed" };
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// this function lets users with code set a password or users with valid User Verification Check
|
||||
export async function changePassword(command: {
|
||||
code?: string;
|
||||
userId: string;
|
||||
password: string;
|
||||
}) {
|
||||
export async function changePassword(command: { code?: string; userId: string; password: string }) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
@@ -350,15 +342,12 @@ export async function changePassword(command: {
|
||||
// if the user has no authmethods set, we need to check if the user was verified
|
||||
if (authmethods.authMethodTypes.length !== 0) {
|
||||
return {
|
||||
error:
|
||||
"You have to provide a code or have a valid User Verification Check",
|
||||
error: "You have to provide a code or have a valid User Verification Check",
|
||||
};
|
||||
}
|
||||
|
||||
// check if a verification was done earlier
|
||||
const hasValidUserVerificationCheck = await checkUserVerification(
|
||||
user.userId,
|
||||
);
|
||||
const hasValidUserVerificationCheck = await checkUserVerification(user.userId);
|
||||
|
||||
if (!hasValidUserVerificationCheck) {
|
||||
return { error: "User Verification Check has to be done" };
|
||||
@@ -378,10 +367,7 @@ type CheckSessionAndSetPasswordCommand = {
|
||||
password: string;
|
||||
};
|
||||
|
||||
export async function checkSessionAndSetPassword({
|
||||
sessionId,
|
||||
password,
|
||||
}: CheckSessionAndSetPasswordCommand) {
|
||||
export async function checkSessionAndSetPassword({ sessionId, password }: CheckSessionAndSetPasswordCommand) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
@@ -421,18 +407,14 @@ export async function checkSessionAndSetPassword({
|
||||
AuthenticationMethodType.U2F,
|
||||
];
|
||||
|
||||
const hasNoMFAMethods = requiredAuthMethodsForForceMFA.every(
|
||||
(method) => !authmethods.authMethodTypes.includes(method),
|
||||
);
|
||||
const hasNoMFAMethods = requiredAuthMethodsForForceMFA.every((method) => !authmethods.authMethodTypes.includes(method));
|
||||
|
||||
const loginSettings = await getLoginSettings({
|
||||
serviceUrl,
|
||||
organization: session.factors.user.organizationId,
|
||||
});
|
||||
|
||||
const forceMfa = !!(
|
||||
loginSettings?.forceMfa || loginSettings?.forceMfaLocalOnly
|
||||
);
|
||||
const forceMfa = !!(loginSettings?.forceMfa || loginSettings?.forceMfaLocalOnly);
|
||||
|
||||
// if the user has no MFA but MFA is enforced, we can set a password otherwise we use the token of the user
|
||||
if (forceMfa && hasNoMFAMethods) {
|
||||
@@ -454,10 +436,7 @@ export async function checkSessionAndSetPassword({
|
||||
return createUserServiceClient(transportPromise);
|
||||
};
|
||||
|
||||
const selfService = await myUserService(
|
||||
serviceUrl,
|
||||
`${sessionCookie.token}`,
|
||||
);
|
||||
const selfService = await myUserService(serviceUrl, `${sessionCookie.token}`);
|
||||
|
||||
return selfService
|
||||
.setPassword(
|
||||
|
||||
@@ -1,23 +1,12 @@
|
||||
"use server";
|
||||
|
||||
import {
|
||||
createSessionAndUpdateCookie,
|
||||
createSessionForIdpAndUpdateCookie,
|
||||
} from "@/lib/server/cookie";
|
||||
import {
|
||||
addHumanUser,
|
||||
addIDPLink,
|
||||
getLoginSettings,
|
||||
getUserByID,
|
||||
} from "@/lib/zitadel";
|
||||
import { createSessionAndUpdateCookie, createSessionForIdpAndUpdateCookie } from "@/lib/server/cookie";
|
||||
import { addHumanUser, addIDPLink, getLoginSettings, getUserByID } from "@/lib/zitadel";
|
||||
import { create } from "@zitadel/client";
|
||||
import { Factors } from "@zitadel/proto/zitadel/session/v2/session_pb";
|
||||
import {
|
||||
ChecksJson,
|
||||
ChecksSchema,
|
||||
} from "@zitadel/proto/zitadel/session/v2/session_service_pb";
|
||||
import { ChecksJson, ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
|
||||
import { headers } from "next/headers";
|
||||
import { getNextUrl } from "../client";
|
||||
import { completeFlowOrGetUrl } from "../client";
|
||||
import { getServiceUrlFromHeaders } from "../service-url";
|
||||
import { checkEmailVerification } from "../verify-helper";
|
||||
|
||||
@@ -78,9 +67,7 @@ export async function registerUser(command: RegisterUserCommand) {
|
||||
const session = await createSessionAndUpdateCookie({
|
||||
checks,
|
||||
requestId: command.requestId,
|
||||
lifetime: command.password
|
||||
? loginSettings?.passwordCheckLifetime
|
||||
: undefined,
|
||||
lifetime: command.password ? loginSettings?.passwordCheckLifetime : undefined,
|
||||
});
|
||||
|
||||
if (!session || !session.factors?.user) {
|
||||
@@ -108,10 +95,7 @@ export async function registerUser(command: RegisterUserCommand) {
|
||||
return { error: "User not found in the system" };
|
||||
}
|
||||
|
||||
const humanUser =
|
||||
userResponse.user.type.case === "human"
|
||||
? userResponse.user.type.value
|
||||
: undefined;
|
||||
const humanUser = userResponse.user.type.case === "human" ? userResponse.user.type.value : undefined;
|
||||
|
||||
const emailVerificationCheck = checkEmailVerification(
|
||||
session,
|
||||
@@ -124,7 +108,7 @@ export async function registerUser(command: RegisterUserCommand) {
|
||||
return emailVerificationCheck;
|
||||
}
|
||||
|
||||
const url = await getNextUrl(
|
||||
return completeFlowOrGetUrl(
|
||||
command.requestId && session.id
|
||||
? {
|
||||
sessionId: session.id,
|
||||
@@ -137,8 +121,6 @@ export async function registerUser(command: RegisterUserCommand) {
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
|
||||
return { redirect: url };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,9 +144,7 @@ export type registerUserAndLinkToIDPResponse = {
|
||||
sessionId: string;
|
||||
factors: Factors | undefined;
|
||||
};
|
||||
export async function registerUserAndLinkToIDP(
|
||||
command: RegisterUserAndLinkToIDPommand,
|
||||
) {
|
||||
export async function registerUserAndLinkToIDP(command: RegisterUserAndLinkToIDPommand) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
const host = _headers.get("host");
|
||||
@@ -215,7 +195,7 @@ export async function registerUserAndLinkToIDP(
|
||||
return { error: "Could not create session" };
|
||||
}
|
||||
|
||||
const url = await getNextUrl(
|
||||
return completeFlowOrGetUrl(
|
||||
command.requestId && session.id
|
||||
? {
|
||||
sessionId: session.id,
|
||||
@@ -228,6 +208,4 @@ export async function registerUserAndLinkToIDP(
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
|
||||
return { redirect: url };
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import { RequestChallenges } from "@zitadel/proto/zitadel/session/v2/challenge_p
|
||||
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
|
||||
import { Checks } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
|
||||
import { headers } from "next/headers";
|
||||
import { getNextUrl } from "../client";
|
||||
import { completeFlowOrGetUrl } from "../client";
|
||||
import {
|
||||
getMostRecentSessionCookie,
|
||||
getSessionCookieById,
|
||||
@@ -34,7 +34,7 @@ export async function skipMFAAndContinueWithNextUrl({
|
||||
sessionId?: string;
|
||||
requestId?: string;
|
||||
organization?: string;
|
||||
}) {
|
||||
}): Promise<{ redirect: string } | { error: string }> {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
@@ -45,28 +45,26 @@ export async function skipMFAAndContinueWithNextUrl({
|
||||
|
||||
await humanMFAInitSkipped({ serviceUrl, userId });
|
||||
|
||||
const url =
|
||||
requestId && sessionId
|
||||
? await getNextUrl(
|
||||
{
|
||||
sessionId: sessionId,
|
||||
requestId: requestId,
|
||||
organization: organization,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
)
|
||||
: loginName
|
||||
? await getNextUrl(
|
||||
{
|
||||
loginName: loginName,
|
||||
organization: organization,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
)
|
||||
: null;
|
||||
if (url) {
|
||||
return { redirect: url };
|
||||
if (requestId && sessionId) {
|
||||
return completeFlowOrGetUrl(
|
||||
{
|
||||
sessionId: sessionId,
|
||||
requestId: requestId,
|
||||
organization: organization,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
} else if (loginName) {
|
||||
return completeFlowOrGetUrl(
|
||||
{
|
||||
loginName: loginName,
|
||||
organization: organization,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
}
|
||||
|
||||
return { error: "Could not skip MFA and continue" };
|
||||
}
|
||||
|
||||
export async function continueWithSession({ requestId, ...session }: Session & { requestId?: string }) {
|
||||
@@ -78,27 +76,23 @@ export async function continueWithSession({ requestId, ...session }: Session & {
|
||||
organization: session.factors?.user?.organizationId,
|
||||
});
|
||||
|
||||
const url =
|
||||
requestId && session.id && session.factors?.user
|
||||
? await getNextUrl(
|
||||
{
|
||||
sessionId: session.id,
|
||||
requestId: requestId,
|
||||
organization: session.factors.user.organizationId,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
)
|
||||
: session.factors?.user
|
||||
? await getNextUrl(
|
||||
{
|
||||
loginName: session.factors.user.loginName,
|
||||
organization: session.factors.user.organizationId,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
)
|
||||
: null;
|
||||
if (url) {
|
||||
return { redirect: url };
|
||||
if (requestId && session.id && session.factors?.user) {
|
||||
return completeFlowOrGetUrl(
|
||||
{
|
||||
sessionId: session.id,
|
||||
requestId: requestId,
|
||||
organization: session.factors.user.organizationId,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
} else if (session.factors?.user) {
|
||||
return completeFlowOrGetUrl(
|
||||
{
|
||||
loginName: session.factors.user.loginName,
|
||||
organization: session.factors.user.organizationId,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ import { create } from "@zitadel/client";
|
||||
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
|
||||
import { ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
|
||||
import { cookies, headers } from "next/headers";
|
||||
import { getNextUrl } from "../client";
|
||||
import { completeFlowOrGetUrl } from "../client";
|
||||
import { getSessionCookieByLoginName } from "../cookies";
|
||||
import { getOrSetFingerprintId } from "../fingerprint";
|
||||
import { getServiceUrlFromHeaders } from "../service-url";
|
||||
@@ -25,11 +25,7 @@ import { loadMostRecentSession } from "../session";
|
||||
import { checkMFAFactors } from "../verify-helper";
|
||||
import { createSessionAndUpdateCookie } from "./cookie";
|
||||
|
||||
export async function verifyTOTP(
|
||||
code: string,
|
||||
loginName?: string,
|
||||
organization?: string,
|
||||
) {
|
||||
export async function verifyTOTP(code: string, loginName?: string, organization?: string) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
@@ -104,8 +100,7 @@ export async function sendVerification(command: VerifyUserByEmailCommand) {
|
||||
const user = userResponse.user;
|
||||
|
||||
const sessionCookie = await getSessionCookieByLoginName({
|
||||
loginName:
|
||||
"loginName" in command ? command.loginName : user.preferredLoginName,
|
||||
loginName: "loginName" in command ? command.loginName : user.preferredLoginName,
|
||||
organization: command.organization,
|
||||
}).catch((error) => {
|
||||
console.warn("Ignored error:", error); // checked later
|
||||
@@ -134,11 +129,7 @@ export async function sendVerification(command: VerifyUserByEmailCommand) {
|
||||
}
|
||||
|
||||
// if no authmethods are found on the user, redirect to set one up
|
||||
if (
|
||||
authMethodResponse &&
|
||||
authMethodResponse.authMethodTypes &&
|
||||
authMethodResponse.authMethodTypes.length == 0
|
||||
) {
|
||||
if (authMethodResponse && authMethodResponse.authMethodTypes && authMethodResponse.authMethodTypes.length == 0) {
|
||||
if (!sessionCookie) {
|
||||
const checks = create(ChecksSchema, {
|
||||
user: {
|
||||
@@ -171,10 +162,7 @@ export async function sendVerification(command: VerifyUserByEmailCommand) {
|
||||
const cookiesList = await cookies();
|
||||
const userAgentId = await getOrSetFingerprintId();
|
||||
|
||||
const verificationCheck = crypto
|
||||
.createHash("sha256")
|
||||
.update(`${user.userId}:${userAgentId}`)
|
||||
.digest("hex");
|
||||
const verificationCheck = crypto.createHash("sha256").update(`${user.userId}:${userAgentId}`).digest("hex");
|
||||
|
||||
await cookiesList.set({
|
||||
name: "verificationCheck",
|
||||
@@ -196,15 +184,10 @@ export async function sendVerification(command: VerifyUserByEmailCommand) {
|
||||
verifySuccessParams.set("userId", command.userId);
|
||||
}
|
||||
|
||||
if (
|
||||
("loginName" in command && command.loginName) ||
|
||||
user.preferredLoginName
|
||||
) {
|
||||
if (("loginName" in command && command.loginName) || user.preferredLoginName) {
|
||||
verifySuccessParams.set(
|
||||
"loginName",
|
||||
"loginName" in command && command.loginName
|
||||
? command.loginName
|
||||
: user.preferredLoginName,
|
||||
"loginName" in command && command.loginName ? command.loginName : user.preferredLoginName,
|
||||
);
|
||||
}
|
||||
if (command.requestId) {
|
||||
@@ -238,28 +221,24 @@ export async function sendVerification(command: VerifyUserByEmailCommand) {
|
||||
|
||||
// login user if no additional steps are required
|
||||
if (command.requestId && session.id) {
|
||||
const nextUrl = await getNextUrl(
|
||||
return completeFlowOrGetUrl(
|
||||
{
|
||||
sessionId: session.id,
|
||||
requestId: command.requestId,
|
||||
organization:
|
||||
command.organization ?? session.factors?.user?.organizationId,
|
||||
organization: command.organization ?? session.factors?.user?.organizationId,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
|
||||
return { redirect: nextUrl };
|
||||
}
|
||||
|
||||
const url = await getNextUrl(
|
||||
// Regular flow - return URL for client-side navigation
|
||||
return completeFlowOrGetUrl(
|
||||
{
|
||||
loginName: session.factors.user.loginName,
|
||||
organization: session.factors?.user?.organizationId,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
|
||||
return { redirect: url };
|
||||
}
|
||||
|
||||
type resendVerifyEmailCommand = {
|
||||
|
||||
Reference in New Issue
Block a user