mirror of
https://github.com/andwati/zitadel.git
synced 2026-11-17 19:05:13 +00:00
chore: reproducible pipeline with dev containers (#10305)
# Which Problems Are Solved - The previous monorepo in monorepo structure for the login app and its related packages was fragmented, complicated and buggy. - The process for building and testing the login container was inconsistent between local development and CI. - Lack of clear documentation as well as easy and reliable ways for non-frontend developers to reproduce and fix failing PR checks locally. # How the Problems Are Solved - Consolidated the login app and its related npm packages by moving the main package to `apps/login/apps/login` and merging `apps/login/packages/integration` and `apps/login/packages/acceptance` into the main `apps/login` package. - Migrated from Docker Compose-based test setups to dev container-based setups, adding support for multiple dev container configurations: - `.devcontainer/base` - `.devcontainer/turbo-lint-unit` - `.devcontainer/turbo-lint-unit-debug` - `.devcontainer/login-integration` - `.devcontainer/login-integration-debug` - Added npm scripts to run the new dev container setups, enabling exact reproduction of GitHub PR checks locally, and updated the pipeline to use these containers. - Cleaned up Dockerfiles and docker-bake.hcl files to only build the production image for the login app. - Cleaned up compose files to focus on dev environments in dev containers. - Updated `CONTRIBUTING.md` with guidance on running and debugging PR checks locally using the new dev container approach. - Introduced separate Dockerfiles for the login app to distinguish between using published client packages and building clients from local protos. - Ensured the login container is always built in the pipeline for use in integration and acceptance tests. - Updated Makefile and GitHub Actions workflows to use `--frozen-lockfile` for installing pnpm packages, ensuring reproducible installs. - Disabled GitHub release creation by the changeset action. - Refactored the `/build` directory structure for clarity and maintainability. - Added a `clean` command to `docks/package.json`. - Experimentally added `knip` to the `zitadel-client` package for improved linting of dependencies and exports. # Additional Changes - Fixed Makefile commands for consistency and reliability. - Improved the structure and clarity of the `/build` directory to support seamless integration of the login build. - Enhanced documentation and developer experience for running and debugging CI checks locally. # Additional Context - See updated `CONTRIBUTING.md` for new local development and debugging instructions. - These changes are a prerequisite for further improvements to the CI pipeline and local development workflow. - Closes #10276
This commit is contained in:
@@ -0,0 +1,302 @@
|
||||
"use server";
|
||||
|
||||
import { addSessionToCookie, updateSessionCookie } from "@/lib/cookies";
|
||||
import {
|
||||
createSessionForUserIdAndIdpIntent,
|
||||
createSessionFromChecks,
|
||||
getSecuritySettings,
|
||||
getSession,
|
||||
setSession,
|
||||
} from "@/lib/zitadel";
|
||||
import { ConnectError, Duration, timestampMs } from "@zitadel/client";
|
||||
import {
|
||||
CredentialsCheckError,
|
||||
CredentialsCheckErrorSchema,
|
||||
ErrorDetail,
|
||||
} from "@zitadel/proto/zitadel/message_pb";
|
||||
import {
|
||||
Challenges,
|
||||
RequestChallenges,
|
||||
} from "@zitadel/proto/zitadel/session/v2/challenge_pb";
|
||||
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 { getServiceUrlFromHeaders } from "../service-url";
|
||||
|
||||
type CustomCookieData = {
|
||||
id: string;
|
||||
token: string;
|
||||
loginName: string;
|
||||
organization?: string;
|
||||
creationTs: string;
|
||||
expirationTs: string;
|
||||
changeTs: string;
|
||||
requestId?: string; // if its linked to an OIDC flow
|
||||
};
|
||||
|
||||
const passwordAttemptsHandler = (error: ConnectError) => {
|
||||
const details = error.findDetails(CredentialsCheckErrorSchema);
|
||||
|
||||
if (details[0] && "failedAttempts" in details[0]) {
|
||||
const failedAttempts = details[0].failedAttempts;
|
||||
throw {
|
||||
error: `Failed to authenticate: You had ${failedAttempts} password attempts.`,
|
||||
failedAttempts: failedAttempts,
|
||||
};
|
||||
}
|
||||
throw error;
|
||||
};
|
||||
|
||||
export async function createSessionAndUpdateCookie(command: {
|
||||
checks: Checks;
|
||||
requestId: string | undefined;
|
||||
lifetime?: Duration;
|
||||
}): Promise<Session> {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
let sessionLifetime = command.lifetime;
|
||||
|
||||
if (!sessionLifetime) {
|
||||
console.warn("No session lifetime provided, using default of 24 hours.");
|
||||
|
||||
sessionLifetime = {
|
||||
seconds: BigInt(24 * 60 * 60), // 24 hours
|
||||
nanos: 0,
|
||||
} as Duration; // for usecases where the lifetime is not specified (user discovery)
|
||||
}
|
||||
|
||||
const createdSession = await createSessionFromChecks({
|
||||
serviceUrl,
|
||||
checks: command.checks,
|
||||
lifetime: sessionLifetime,
|
||||
});
|
||||
|
||||
if (createdSession) {
|
||||
return getSession({
|
||||
serviceUrl,
|
||||
sessionId: createdSession.sessionId,
|
||||
sessionToken: createdSession.sessionToken,
|
||||
}).then(async (response) => {
|
||||
if (response?.session && response.session?.factors?.user?.loginName) {
|
||||
const sessionCookie: CustomCookieData = {
|
||||
id: createdSession.sessionId,
|
||||
token: createdSession.sessionToken,
|
||||
creationTs: response.session.creationDate
|
||||
? `${timestampMs(response.session.creationDate)}`
|
||||
: "",
|
||||
expirationTs: response.session.expirationDate
|
||||
? `${timestampMs(response.session.expirationDate)}`
|
||||
: "",
|
||||
changeTs: response.session.changeDate
|
||||
? `${timestampMs(response.session.changeDate)}`
|
||||
: "",
|
||||
loginName: response.session.factors.user.loginName ?? "",
|
||||
};
|
||||
|
||||
if (command.requestId) {
|
||||
sessionCookie.requestId = command.requestId;
|
||||
}
|
||||
|
||||
if (response.session.factors.user.organizationId) {
|
||||
sessionCookie.organization =
|
||||
response.session.factors.user.organizationId;
|
||||
}
|
||||
|
||||
const securitySettings = await getSecuritySettings({ serviceUrl });
|
||||
const sameSite = securitySettings?.embeddedIframe?.enabled
|
||||
? "none"
|
||||
: true;
|
||||
|
||||
await addSessionToCookie({ session: sessionCookie, sameSite });
|
||||
|
||||
return response.session as Session;
|
||||
} else {
|
||||
throw "could not get session or session does not have loginName";
|
||||
}
|
||||
});
|
||||
} else {
|
||||
throw "Could not create session";
|
||||
}
|
||||
}
|
||||
|
||||
export async function createSessionForIdpAndUpdateCookie({
|
||||
userId,
|
||||
idpIntent,
|
||||
requestId,
|
||||
lifetime,
|
||||
}: {
|
||||
userId: string;
|
||||
idpIntent: {
|
||||
idpIntentId?: string | undefined;
|
||||
idpIntentToken?: string | undefined;
|
||||
};
|
||||
requestId: string | undefined;
|
||||
lifetime?: Duration;
|
||||
}): Promise<Session> {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
let sessionLifetime = lifetime;
|
||||
|
||||
if (!sessionLifetime) {
|
||||
console.warn(
|
||||
"No IDP session lifetime provided, using default of 24 hours.",
|
||||
);
|
||||
|
||||
sessionLifetime = {
|
||||
seconds: BigInt(24 * 60 * 60), // 24 hours
|
||||
nanos: 0,
|
||||
} as Duration;
|
||||
}
|
||||
|
||||
const createdSession = await createSessionForUserIdAndIdpIntent({
|
||||
serviceUrl,
|
||||
userId,
|
||||
idpIntent,
|
||||
lifetime: sessionLifetime,
|
||||
}).catch((error: ErrorDetail | CredentialsCheckError) => {
|
||||
console.error("Could not set session", error);
|
||||
if ("failedAttempts" in error && error.failedAttempts) {
|
||||
throw {
|
||||
error: `Failed to authenticate: You had ${error.failedAttempts} password attempts.`,
|
||||
failedAttempts: error.failedAttempts,
|
||||
};
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
|
||||
if (!createdSession) {
|
||||
throw "Could not create session";
|
||||
}
|
||||
|
||||
const { session } = await getSession({
|
||||
serviceUrl,
|
||||
sessionId: createdSession.sessionId,
|
||||
sessionToken: createdSession.sessionToken,
|
||||
});
|
||||
|
||||
if (!session || !session.factors?.user?.loginName) {
|
||||
throw "Could not retrieve session";
|
||||
}
|
||||
|
||||
const sessionCookie: CustomCookieData = {
|
||||
id: createdSession.sessionId,
|
||||
token: createdSession.sessionToken,
|
||||
creationTs: session.creationDate
|
||||
? `${timestampMs(session.creationDate)}`
|
||||
: "",
|
||||
expirationTs: session.expirationDate
|
||||
? `${timestampMs(session.expirationDate)}`
|
||||
: "",
|
||||
changeTs: session.changeDate ? `${timestampMs(session.changeDate)}` : "",
|
||||
loginName: session.factors.user.loginName ?? "",
|
||||
organization: session.factors.user.organizationId ?? "",
|
||||
};
|
||||
|
||||
if (requestId) {
|
||||
sessionCookie.requestId = requestId;
|
||||
}
|
||||
|
||||
if (session.factors.user.organizationId) {
|
||||
sessionCookie.organization = session.factors.user.organizationId;
|
||||
}
|
||||
|
||||
const securitySettings = await getSecuritySettings({ serviceUrl });
|
||||
const sameSite = securitySettings?.embeddedIframe?.enabled ? "none" : true;
|
||||
|
||||
return addSessionToCookie({ session: sessionCookie, sameSite }).then(() => {
|
||||
return session as Session;
|
||||
});
|
||||
}
|
||||
|
||||
export type SessionWithChallenges = Session & {
|
||||
challenges: Challenges | undefined;
|
||||
};
|
||||
|
||||
export async function setSessionAndUpdateCookie(command: {
|
||||
recentCookie: CustomCookieData;
|
||||
checks?: Checks;
|
||||
challenges?: RequestChallenges;
|
||||
requestId?: string;
|
||||
lifetime: Duration;
|
||||
}) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
return setSession({
|
||||
serviceUrl,
|
||||
sessionId: command.recentCookie.id,
|
||||
sessionToken: command.recentCookie.token,
|
||||
challenges: command.challenges,
|
||||
checks: command.checks,
|
||||
lifetime: command.lifetime,
|
||||
})
|
||||
.then((updatedSession) => {
|
||||
if (updatedSession) {
|
||||
const sessionCookie: CustomCookieData = {
|
||||
id: command.recentCookie.id,
|
||||
token: updatedSession.sessionToken,
|
||||
creationTs: command.recentCookie.creationTs,
|
||||
expirationTs: command.recentCookie.expirationTs,
|
||||
// just overwrite the changeDate with the new one
|
||||
changeTs: updatedSession.details?.changeDate
|
||||
? `${timestampMs(updatedSession.details.changeDate)}`
|
||||
: "",
|
||||
loginName: command.recentCookie.loginName,
|
||||
organization: command.recentCookie.organization,
|
||||
};
|
||||
|
||||
if (command.requestId) {
|
||||
sessionCookie.requestId = command.requestId;
|
||||
}
|
||||
|
||||
return getSession({
|
||||
serviceUrl,
|
||||
sessionId: sessionCookie.id,
|
||||
sessionToken: sessionCookie.token,
|
||||
}).then(async (response) => {
|
||||
if (
|
||||
!response?.session ||
|
||||
!response.session.factors?.user?.loginName
|
||||
) {
|
||||
throw "could not get session or session does not have loginName";
|
||||
}
|
||||
|
||||
const { session } = response;
|
||||
const newCookie: CustomCookieData = {
|
||||
id: sessionCookie.id,
|
||||
token: updatedSession.sessionToken,
|
||||
creationTs: sessionCookie.creationTs,
|
||||
expirationTs: sessionCookie.expirationTs,
|
||||
// just overwrite the changeDate with the new one
|
||||
changeTs: updatedSession.details?.changeDate
|
||||
? `${timestampMs(updatedSession.details.changeDate)}`
|
||||
: "",
|
||||
loginName: session.factors?.user?.loginName ?? "",
|
||||
organization: session.factors?.user?.organizationId ?? "",
|
||||
};
|
||||
|
||||
if (sessionCookie.requestId) {
|
||||
newCookie.requestId = sessionCookie.requestId;
|
||||
}
|
||||
|
||||
const securitySettings = await getSecuritySettings({ serviceUrl });
|
||||
const sameSite = securitySettings?.embeddedIframe?.enabled
|
||||
? "none"
|
||||
: true;
|
||||
|
||||
return updateSessionCookie({
|
||||
id: sessionCookie.id,
|
||||
session: newCookie,
|
||||
sameSite,
|
||||
}).then(() => {
|
||||
return { challenges: updatedSession.challenges, ...session };
|
||||
});
|
||||
});
|
||||
} else {
|
||||
throw "Session not be set";
|
||||
}
|
||||
})
|
||||
.catch(passwordAttemptsHandler);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
"use server";
|
||||
|
||||
import { authorizeOrDenyDeviceAuthorization } from "@/lib/zitadel";
|
||||
import { headers } from "next/headers";
|
||||
import { getServiceUrlFromHeaders } from "../service-url";
|
||||
|
||||
export async function completeDeviceAuthorization(
|
||||
deviceAuthorizationId: string,
|
||||
session?: { sessionId: string; sessionToken: string },
|
||||
) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
// without the session, device auth request is denied
|
||||
return authorizeOrDenyDeviceAuthorization({
|
||||
serviceUrl,
|
||||
deviceAuthorizationId,
|
||||
session,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
"use server";
|
||||
|
||||
import {
|
||||
getLoginSettings,
|
||||
getUserByID,
|
||||
startIdentityProviderFlow,
|
||||
startLDAPIdentityProviderFlow,
|
||||
} from "@/lib/zitadel";
|
||||
import { headers } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getNextUrl } from "../client";
|
||||
import { getServiceUrlFromHeaders } from "../service-url";
|
||||
import { checkEmailVerification } from "../verify-helper";
|
||||
import { createSessionForIdpAndUpdateCookie } from "./cookie";
|
||||
|
||||
export type RedirectToIdpState = { error?: string | null } | undefined;
|
||||
|
||||
export async function redirectToIdp(
|
||||
prevState: RedirectToIdpState,
|
||||
formData: FormData,
|
||||
): Promise<RedirectToIdpState> {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
const host = _headers.get("host");
|
||||
if (!host) {
|
||||
return { error: "Could not get host" };
|
||||
}
|
||||
|
||||
const params = new URLSearchParams();
|
||||
|
||||
const linkOnly = formData.get("linkOnly") === "true";
|
||||
const requestId = formData.get("requestId") as string;
|
||||
const organization = formData.get("organization") as string;
|
||||
const idpId = formData.get("id") as string;
|
||||
const provider = formData.get("provider") as string;
|
||||
|
||||
if (linkOnly) params.set("link", "true");
|
||||
if (requestId) params.set("requestId", requestId);
|
||||
if (organization) params.set("organization", organization);
|
||||
|
||||
// redirect to LDAP page where username and password is requested
|
||||
if (provider === "ldap") {
|
||||
params.set("idpId", idpId);
|
||||
redirect(`/idp/ldap?` + params.toString());
|
||||
}
|
||||
|
||||
const response = await startIDPFlow({
|
||||
serviceUrl,
|
||||
host,
|
||||
idpId,
|
||||
successUrl: `/idp/${provider}/success?` + params.toString(),
|
||||
failureUrl: `/idp/${provider}/failure?` + params.toString(),
|
||||
});
|
||||
|
||||
if (!response) {
|
||||
return { error: "Could not start IDP flow" };
|
||||
}
|
||||
|
||||
if (response && "redirect" in response && response?.redirect) {
|
||||
redirect(response.redirect);
|
||||
}
|
||||
|
||||
return { error: "Unexpected response from IDP flow" };
|
||||
}
|
||||
|
||||
export type StartIDPFlowCommand = {
|
||||
serviceUrl: string;
|
||||
host: string;
|
||||
idpId: string;
|
||||
successUrl: string;
|
||||
failureUrl: string;
|
||||
};
|
||||
|
||||
async function startIDPFlow(command: StartIDPFlowCommand) {
|
||||
const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? "";
|
||||
|
||||
const url = await startIdentityProviderFlow({
|
||||
serviceUrl: command.serviceUrl,
|
||||
idpId: command.idpId,
|
||||
urls: {
|
||||
successUrl: `${command.host.includes("localhost") ? "http://" : "https://"}${command.host}${basePath}${command.successUrl}`,
|
||||
failureUrl: `${command.host.includes("localhost") ? "http://" : "https://"}${command.host}${basePath}${command.failureUrl}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!url) {
|
||||
return { error: "Could not start IDP flow" };
|
||||
}
|
||||
|
||||
return { redirect: url };
|
||||
}
|
||||
|
||||
type CreateNewSessionCommand = {
|
||||
userId: string;
|
||||
idpIntent: {
|
||||
idpIntentId: string;
|
||||
idpIntentToken: string;
|
||||
};
|
||||
loginName?: string;
|
||||
password?: string;
|
||||
organization?: string;
|
||||
requestId?: string;
|
||||
};
|
||||
|
||||
export async function createNewSessionFromIdpIntent(
|
||||
command: CreateNewSessionCommand,
|
||||
) {
|
||||
const _headers = await headers();
|
||||
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
const host = _headers.get("host");
|
||||
|
||||
if (!host) {
|
||||
return { error: "Could not get domain" };
|
||||
}
|
||||
|
||||
if (!command.userId || !command.idpIntent) {
|
||||
throw new Error("No userId or loginName provided");
|
||||
}
|
||||
|
||||
const userResponse = await getUserByID({
|
||||
serviceUrl,
|
||||
userId: command.userId,
|
||||
});
|
||||
|
||||
if (!userResponse || !userResponse.user) {
|
||||
return { error: "User not found in the system" };
|
||||
}
|
||||
|
||||
const loginSettings = await getLoginSettings({
|
||||
serviceUrl,
|
||||
organization: userResponse.user.details?.resourceOwner,
|
||||
});
|
||||
|
||||
const session = await createSessionForIdpAndUpdateCookie({
|
||||
userId: command.userId,
|
||||
idpIntent: command.idpIntent,
|
||||
requestId: command.requestId,
|
||||
lifetime: loginSettings?.externalLoginCheckLifetime,
|
||||
});
|
||||
|
||||
if (!session || !session.factors?.user) {
|
||||
return { error: "Could not create session" };
|
||||
}
|
||||
|
||||
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,
|
||||
);
|
||||
|
||||
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;
|
||||
// }
|
||||
|
||||
const url = await getNextUrl(
|
||||
command.requestId && session.id
|
||||
? {
|
||||
sessionId: session.id,
|
||||
requestId: command.requestId,
|
||||
organization: session.factors.user.organizationId,
|
||||
}
|
||||
: {
|
||||
loginName: session.factors.user.loginName,
|
||||
organization: session.factors.user.organizationId,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
|
||||
if (url) {
|
||||
return { redirect: url };
|
||||
}
|
||||
}
|
||||
|
||||
type createNewSessionForLDAPCommand = {
|
||||
username: string;
|
||||
password: string;
|
||||
idpId: string;
|
||||
link: boolean;
|
||||
};
|
||||
|
||||
export async function createNewSessionForLDAP(
|
||||
command: createNewSessionForLDAPCommand,
|
||||
) {
|
||||
const _headers = await headers();
|
||||
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
const host = _headers.get("host");
|
||||
|
||||
if (!host) {
|
||||
return { error: "Could not get domain" };
|
||||
}
|
||||
|
||||
if (!command.username || !command.password) {
|
||||
return { error: "No username or password provided" };
|
||||
}
|
||||
|
||||
const response = await startLDAPIdentityProviderFlow({
|
||||
serviceUrl,
|
||||
idpId: command.idpId,
|
||||
username: command.username,
|
||||
password: command.password,
|
||||
});
|
||||
|
||||
if (
|
||||
!response ||
|
||||
response.nextStep.case !== "idpIntent" ||
|
||||
!response.nextStep.value
|
||||
) {
|
||||
return { error: "Could not start LDAP identity provider flow" };
|
||||
}
|
||||
|
||||
const { userId, idpIntentId, idpIntentToken } = response.nextStep.value;
|
||||
|
||||
const params = new URLSearchParams({
|
||||
userId,
|
||||
id: idpIntentId,
|
||||
token: idpIntentToken,
|
||||
});
|
||||
|
||||
if (command.link) {
|
||||
params.set("link", "true");
|
||||
}
|
||||
|
||||
return {
|
||||
redirect: `/idp/ldap/success?` + params.toString(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,466 @@
|
||||
"use server";
|
||||
|
||||
import { create } from "@zitadel/client";
|
||||
import { ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
|
||||
import { AuthenticationMethodType } from "@zitadel/proto/zitadel/user/v2/user_service_pb";
|
||||
import { headers } from "next/headers";
|
||||
import { idpTypeToIdentityProviderType, idpTypeToSlug } from "../idp";
|
||||
|
||||
import { PasskeysType } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb";
|
||||
import { UserState } from "@zitadel/proto/zitadel/user/v2/user_pb";
|
||||
import { getServiceUrlFromHeaders } from "../service-url";
|
||||
import {
|
||||
getActiveIdentityProviders,
|
||||
getIDPByID,
|
||||
getLoginSettings,
|
||||
getOrgsByDomain,
|
||||
listAuthenticationMethodTypes,
|
||||
listIDPLinks,
|
||||
searchUsers,
|
||||
SearchUsersCommand,
|
||||
startIdentityProviderFlow,
|
||||
} from "../zitadel";
|
||||
import { createSessionAndUpdateCookie } from "./cookie";
|
||||
|
||||
export type SendLoginnameCommand = {
|
||||
loginName: string;
|
||||
requestId?: string;
|
||||
organization?: string;
|
||||
suffix?: string;
|
||||
};
|
||||
|
||||
const ORG_SUFFIX_REGEX = /(?<=@)(.+)/;
|
||||
|
||||
export async function sendLoginname(command: SendLoginnameCommand) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
const host = _headers.get("host");
|
||||
|
||||
if (!host) {
|
||||
throw new Error("Could not get domain");
|
||||
}
|
||||
|
||||
const loginSettingsByContext = await getLoginSettings({
|
||||
serviceUrl,
|
||||
organization: command.organization,
|
||||
});
|
||||
|
||||
if (!loginSettingsByContext) {
|
||||
return { error: "Could not get login settings" };
|
||||
}
|
||||
|
||||
let searchUsersRequest: SearchUsersCommand = {
|
||||
serviceUrl,
|
||||
searchValue: command.loginName,
|
||||
organizationId: command.organization,
|
||||
loginSettings: loginSettingsByContext,
|
||||
suffix: command.suffix,
|
||||
};
|
||||
|
||||
const searchResult = await searchUsers(searchUsersRequest);
|
||||
|
||||
if ("error" in searchResult && searchResult.error) {
|
||||
return searchResult;
|
||||
}
|
||||
|
||||
if (!("result" in searchResult)) {
|
||||
return { error: "Could not search users" };
|
||||
}
|
||||
|
||||
const { result: potentialUsers } = searchResult;
|
||||
|
||||
const redirectUserToSingleIDPIfAvailable = async () => {
|
||||
const identityProviders = await getActiveIdentityProviders({
|
||||
serviceUrl,
|
||||
orgId: command.organization,
|
||||
}).then((resp) => {
|
||||
return resp.identityProviders;
|
||||
});
|
||||
|
||||
if (identityProviders.length === 1) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
const host = _headers.get("host");
|
||||
|
||||
if (!host) {
|
||||
return { error: "Could not get host" };
|
||||
}
|
||||
|
||||
const identityProviderType = identityProviders[0].type;
|
||||
|
||||
const provider = idpTypeToSlug(identityProviderType);
|
||||
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (command.requestId) {
|
||||
params.set("requestId", command.requestId);
|
||||
}
|
||||
|
||||
if (command.organization) {
|
||||
params.set("organization", command.organization);
|
||||
}
|
||||
|
||||
const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? "";
|
||||
|
||||
const url = await startIdentityProviderFlow({
|
||||
serviceUrl,
|
||||
idpId: identityProviders[0].id,
|
||||
urls: {
|
||||
successUrl:
|
||||
`${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/idp/${provider}/success?` +
|
||||
new URLSearchParams(params),
|
||||
failureUrl:
|
||||
`${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/idp/${provider}/failure?` +
|
||||
new URLSearchParams(params),
|
||||
},
|
||||
});
|
||||
|
||||
if (!url) {
|
||||
return { error: "Could not start IDP flow" };
|
||||
}
|
||||
|
||||
return { redirect: url };
|
||||
}
|
||||
};
|
||||
|
||||
const redirectUserToIDP = async (userId: string) => {
|
||||
const identityProviders = await listIDPLinks({
|
||||
serviceUrl,
|
||||
userId,
|
||||
}).then((resp) => {
|
||||
return resp.result;
|
||||
});
|
||||
|
||||
if (identityProviders.length === 1) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
const host = _headers.get("host");
|
||||
|
||||
if (!host) {
|
||||
return { error: "Could not get host" };
|
||||
}
|
||||
|
||||
const identityProviderId = identityProviders[0].idpId;
|
||||
|
||||
const idp = await getIDPByID({
|
||||
serviceUrl,
|
||||
id: identityProviderId,
|
||||
});
|
||||
|
||||
const idpType = idp?.type;
|
||||
|
||||
if (!idp || !idpType) {
|
||||
throw new Error("Could not find identity provider");
|
||||
}
|
||||
|
||||
const identityProviderType = idpTypeToIdentityProviderType(idpType);
|
||||
const provider = idpTypeToSlug(identityProviderType);
|
||||
|
||||
const params = new URLSearchParams({ userId });
|
||||
|
||||
if (command.requestId) {
|
||||
params.set("requestId", command.requestId);
|
||||
}
|
||||
|
||||
if (command.organization) {
|
||||
params.set("organization", command.organization);
|
||||
}
|
||||
|
||||
const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? "";
|
||||
|
||||
const url = await startIdentityProviderFlow({
|
||||
serviceUrl,
|
||||
idpId: idp.id,
|
||||
urls: {
|
||||
successUrl:
|
||||
`${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/idp/${provider}/success?` +
|
||||
new URLSearchParams(params),
|
||||
failureUrl:
|
||||
`${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/idp/${provider}/failure?` +
|
||||
new URLSearchParams(params),
|
||||
},
|
||||
});
|
||||
|
||||
if (!url) {
|
||||
return { error: "Could not start IDP flow" };
|
||||
}
|
||||
|
||||
return { redirect: url };
|
||||
}
|
||||
};
|
||||
|
||||
if (potentialUsers.length > 1) {
|
||||
return { error: "More than one user found. Provide a unique identifier." };
|
||||
} else if (potentialUsers.length == 1 && potentialUsers[0].userId) {
|
||||
const user = potentialUsers[0];
|
||||
const userId = potentialUsers[0].userId;
|
||||
|
||||
const userLoginSettings = await getLoginSettings({
|
||||
serviceUrl,
|
||||
organization: user.details?.resourceOwner,
|
||||
});
|
||||
|
||||
// compare with the concatenated suffix when set
|
||||
const concatLoginname = command.suffix
|
||||
? `${command.loginName}@${command.suffix}`
|
||||
: command.loginName;
|
||||
|
||||
const humanUser =
|
||||
potentialUsers[0].type.case === "human"
|
||||
? potentialUsers[0].type.value
|
||||
: undefined;
|
||||
|
||||
// recheck login settings after user discovery, as the search might have been done without org scope
|
||||
if (
|
||||
userLoginSettings?.disableLoginWithEmail &&
|
||||
userLoginSettings?.disableLoginWithPhone
|
||||
) {
|
||||
if (user.preferredLoginName !== concatLoginname) {
|
||||
return { error: "User not found in the system!" };
|
||||
}
|
||||
} else if (userLoginSettings?.disableLoginWithEmail) {
|
||||
if (
|
||||
user.preferredLoginName !== concatLoginname ||
|
||||
humanUser?.phone?.phone !== command.loginName
|
||||
) {
|
||||
return { error: "User not found in the system!" };
|
||||
}
|
||||
} else if (userLoginSettings?.disableLoginWithPhone) {
|
||||
if (
|
||||
user.preferredLoginName !== concatLoginname ||
|
||||
humanUser?.email?.email !== command.loginName
|
||||
) {
|
||||
return { error: "User not found in the system!" };
|
||||
}
|
||||
}
|
||||
|
||||
const checks = create(ChecksSchema, {
|
||||
user: { search: { case: "userId", value: userId } },
|
||||
});
|
||||
|
||||
const session = await createSessionAndUpdateCookie({
|
||||
checks,
|
||||
requestId: command.requestId,
|
||||
});
|
||||
|
||||
if (!session.factors?.user?.id) {
|
||||
return { error: "Could not create session for user" };
|
||||
}
|
||||
|
||||
// TODO: check if handling of userstate INITIAL is needed
|
||||
if (user.state === UserState.INITIAL) {
|
||||
return { error: "Initial User not supported" };
|
||||
}
|
||||
|
||||
const methods = await listAuthenticationMethodTypes({
|
||||
serviceUrl,
|
||||
userId: session.factors?.user?.id,
|
||||
});
|
||||
|
||||
// always resend invite if user has no auth method set
|
||||
if (!methods.authMethodTypes || !methods.authMethodTypes.length) {
|
||||
const params = new URLSearchParams({
|
||||
loginName: session.factors?.user?.loginName as string,
|
||||
send: "true", // set this to true to request a new code immediately
|
||||
invite: "true",
|
||||
});
|
||||
|
||||
if (command.requestId) {
|
||||
params.append("requestId", command.requestId);
|
||||
}
|
||||
|
||||
if (command.organization || session.factors?.user?.organizationId) {
|
||||
params.append(
|
||||
"organization",
|
||||
command.organization ??
|
||||
(session.factors?.user?.organizationId as string),
|
||||
);
|
||||
}
|
||||
|
||||
return { redirect: `/verify?` + params };
|
||||
}
|
||||
|
||||
if (methods.authMethodTypes.length == 1) {
|
||||
const method = methods.authMethodTypes[0];
|
||||
switch (method) {
|
||||
case AuthenticationMethodType.PASSWORD: // user has only password as auth method
|
||||
if (!userLoginSettings?.allowUsernamePassword) {
|
||||
return {
|
||||
error:
|
||||
"Username Password not allowed! Contact your administrator for more information.",
|
||||
};
|
||||
}
|
||||
|
||||
const paramsPassword = new URLSearchParams({
|
||||
loginName: session.factors?.user?.loginName,
|
||||
});
|
||||
|
||||
// TODO: does this have to be checked in loginSettings.allowDomainDiscovery
|
||||
|
||||
if (command.organization || session.factors?.user?.organizationId) {
|
||||
paramsPassword.append(
|
||||
"organization",
|
||||
command.organization ?? session.factors?.user?.organizationId,
|
||||
);
|
||||
}
|
||||
|
||||
if (command.requestId) {
|
||||
paramsPassword.append("requestId", command.requestId);
|
||||
}
|
||||
|
||||
return {
|
||||
redirect: "/password?" + paramsPassword,
|
||||
};
|
||||
|
||||
case AuthenticationMethodType.PASSKEY: // AuthenticationMethodType.AUTHENTICATION_METHOD_TYPE_PASSKEY
|
||||
if (userLoginSettings?.passkeysType === PasskeysType.NOT_ALLOWED) {
|
||||
return {
|
||||
error:
|
||||
"Passkeys not allowed! Contact your administrator for more information.",
|
||||
};
|
||||
}
|
||||
|
||||
const paramsPasskey = new URLSearchParams({
|
||||
loginName: session.factors?.user?.loginName,
|
||||
});
|
||||
if (command.requestId) {
|
||||
paramsPasskey.append("requestId", command.requestId);
|
||||
}
|
||||
|
||||
if (command.organization || session.factors?.user?.organizationId) {
|
||||
paramsPasskey.append(
|
||||
"organization",
|
||||
command.organization ?? session.factors?.user?.organizationId,
|
||||
);
|
||||
}
|
||||
|
||||
return { redirect: "/passkey?" + paramsPasskey };
|
||||
}
|
||||
} else {
|
||||
// prefer passkey in favor of other methods
|
||||
if (methods.authMethodTypes.includes(AuthenticationMethodType.PASSKEY)) {
|
||||
const passkeyParams = new URLSearchParams({
|
||||
loginName: session.factors?.user?.loginName,
|
||||
altPassword: `${methods.authMethodTypes.includes(1)}`, // show alternative password option
|
||||
});
|
||||
|
||||
if (command.requestId) {
|
||||
passkeyParams.append("requestId", command.requestId);
|
||||
}
|
||||
|
||||
if (command.organization || session.factors?.user?.organizationId) {
|
||||
passkeyParams.append(
|
||||
"organization",
|
||||
command.organization ?? session.factors?.user?.organizationId,
|
||||
);
|
||||
}
|
||||
|
||||
return { redirect: "/passkey?" + passkeyParams };
|
||||
} else if (
|
||||
methods.authMethodTypes.includes(AuthenticationMethodType.IDP)
|
||||
) {
|
||||
return redirectUserToIDP(userId);
|
||||
} else if (
|
||||
methods.authMethodTypes.includes(AuthenticationMethodType.PASSWORD)
|
||||
) {
|
||||
// user has no passkey setup and login settings allow passkeys
|
||||
const paramsPasswordDefault = new URLSearchParams({
|
||||
loginName: session.factors?.user?.loginName,
|
||||
});
|
||||
|
||||
if (command.requestId) {
|
||||
paramsPasswordDefault.append("requestId", command.requestId);
|
||||
}
|
||||
|
||||
if (command.organization || session.factors?.user?.organizationId) {
|
||||
paramsPasswordDefault.append(
|
||||
"organization",
|
||||
command.organization ?? session.factors?.user?.organizationId,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
redirect: "/password?" + paramsPasswordDefault,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// user not found, check if register is enabled on instance / organization context
|
||||
if (
|
||||
loginSettingsByContext?.allowRegister &&
|
||||
!loginSettingsByContext?.allowUsernamePassword
|
||||
) {
|
||||
const resp = await redirectUserToSingleIDPIfAvailable();
|
||||
if (resp) {
|
||||
return resp;
|
||||
}
|
||||
return { error: "User not found in the system" };
|
||||
} else if (
|
||||
loginSettingsByContext?.allowRegister &&
|
||||
loginSettingsByContext?.allowUsernamePassword
|
||||
) {
|
||||
let orgToRegisterOn: string | undefined = command.organization;
|
||||
|
||||
if (
|
||||
!loginSettingsByContext?.ignoreUnknownUsernames &&
|
||||
!orgToRegisterOn &&
|
||||
command.loginName &&
|
||||
ORG_SUFFIX_REGEX.test(command.loginName)
|
||||
) {
|
||||
const matched = ORG_SUFFIX_REGEX.exec(command.loginName);
|
||||
const suffix = matched?.[1] ?? "";
|
||||
|
||||
// this just returns orgs where the suffix is set as primary domain
|
||||
const orgs = await getOrgsByDomain({
|
||||
serviceUrl,
|
||||
domain: suffix,
|
||||
});
|
||||
const orgToCheckForDiscovery =
|
||||
orgs.result && orgs.result.length === 1 ? orgs.result[0].id : undefined;
|
||||
|
||||
const orgLoginSettings = await getLoginSettings({
|
||||
serviceUrl,
|
||||
organization: orgToCheckForDiscovery,
|
||||
});
|
||||
if (orgLoginSettings?.allowDomainDiscovery) {
|
||||
orgToRegisterOn = orgToCheckForDiscovery;
|
||||
}
|
||||
}
|
||||
|
||||
// do not register user if ignoreUnknownUsernames is set
|
||||
if (orgToRegisterOn && !loginSettingsByContext?.ignoreUnknownUsernames) {
|
||||
const params = new URLSearchParams({ organization: orgToRegisterOn });
|
||||
|
||||
if (command.requestId) {
|
||||
params.set("requestId", command.requestId);
|
||||
}
|
||||
|
||||
if (command.loginName) {
|
||||
params.set("email", command.loginName);
|
||||
}
|
||||
|
||||
return { redirect: "/register?" + params };
|
||||
}
|
||||
}
|
||||
|
||||
if (loginSettingsByContext?.ignoreUnknownUsernames) {
|
||||
const paramsPasswordDefault = new URLSearchParams({
|
||||
loginName: command.loginName,
|
||||
});
|
||||
|
||||
if (command.requestId) {
|
||||
paramsPasswordDefault.append("requestId", command.requestId);
|
||||
}
|
||||
|
||||
if (command.organization) {
|
||||
paramsPasswordDefault.append("organization", command.organization);
|
||||
}
|
||||
|
||||
return { redirect: "/password?" + paramsPasswordDefault };
|
||||
}
|
||||
|
||||
// fallbackToPassword
|
||||
|
||||
return { error: "User not found in the system" };
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
"use server";
|
||||
|
||||
import { getDeviceAuthorizationRequest as zitadelGetDeviceAuthorizationRequest } from "@/lib/zitadel";
|
||||
import { headers } from "next/headers";
|
||||
import { getServiceUrlFromHeaders } from "../service-url";
|
||||
|
||||
export async function getDeviceAuthorizationRequest(userCode: string) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
return zitadelGetDeviceAuthorizationRequest({
|
||||
serviceUrl,
|
||||
userCode,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
"use server";
|
||||
|
||||
import {
|
||||
createPasskeyRegistrationLink,
|
||||
getLoginSettings,
|
||||
getSession,
|
||||
getUserByID,
|
||||
listAuthenticationMethodTypes,
|
||||
registerPasskey,
|
||||
verifyPasskeyRegistration as zitadelVerifyPasskeyRegistration,
|
||||
} from "@/lib/zitadel";
|
||||
import { create, Duration, Timestamp, timestampDate } from "@zitadel/client";
|
||||
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
|
||||
import { Checks } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
|
||||
import {
|
||||
RegisterPasskeyResponse,
|
||||
VerifyPasskeyRegistrationRequestSchema,
|
||||
} 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 { getServiceUrlFromHeaders } from "../service-url";
|
||||
import {
|
||||
checkEmailVerification,
|
||||
checkUserVerification,
|
||||
} from "../verify-helper";
|
||||
import { setSessionAndUpdateCookie } from "./cookie";
|
||||
|
||||
type VerifyPasskeyCommand = {
|
||||
passkeyId: string;
|
||||
passkeyName?: string;
|
||||
publicKeyCredential: any;
|
||||
sessionId: string;
|
||||
};
|
||||
|
||||
type RegisterPasskeyCommand = {
|
||||
sessionId: string;
|
||||
};
|
||||
|
||||
function isSessionValid(session: Partial<Session>): {
|
||||
valid: boolean;
|
||||
verifiedAt?: Timestamp;
|
||||
} {
|
||||
const validPassword = session?.factors?.password?.verifiedAt;
|
||||
const validPasskey = session?.factors?.webAuthN?.verifiedAt;
|
||||
const stillValid = session.expirationDate
|
||||
? timestampDate(session.expirationDate) > new Date()
|
||||
: true;
|
||||
|
||||
const verifiedAt = validPassword || validPasskey;
|
||||
const valid = !!((validPassword || validPasskey) && stillValid);
|
||||
|
||||
return { valid, verifiedAt };
|
||||
}
|
||||
|
||||
export async function registerPasskeyLink(
|
||||
command: RegisterPasskeyCommand,
|
||||
): Promise<RegisterPasskeyResponse | { error: string }> {
|
||||
const { sessionId } = command;
|
||||
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
const host = _headers.get("host");
|
||||
|
||||
if (!host) {
|
||||
throw new Error("Could not get domain");
|
||||
}
|
||||
|
||||
const sessionCookie = await getSessionCookieById({ sessionId });
|
||||
const session = await getSession({
|
||||
serviceUrl,
|
||||
sessionId: sessionCookie.id,
|
||||
sessionToken: sessionCookie.token,
|
||||
});
|
||||
|
||||
if (!session?.session?.factors?.user?.id) {
|
||||
return { error: "Could not determine user from session" };
|
||||
}
|
||||
|
||||
const sessionValid = isSessionValid(session.session);
|
||||
|
||||
if (!sessionValid) {
|
||||
const authmethods = await listAuthenticationMethodTypes({
|
||||
serviceUrl,
|
||||
userId: session.session.factors.user.id,
|
||||
});
|
||||
|
||||
// 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",
|
||||
};
|
||||
}
|
||||
|
||||
// check if a verification was done earlier
|
||||
const hasValidUserVerificationCheck = await checkUserVerification(
|
||||
session.session.factors.user.id,
|
||||
);
|
||||
|
||||
if (!hasValidUserVerificationCheck) {
|
||||
return { error: "User Verification Check has to be done" };
|
||||
}
|
||||
}
|
||||
|
||||
const [hostname] = host.split(":");
|
||||
|
||||
if (!hostname) {
|
||||
throw new Error("Could not get hostname");
|
||||
}
|
||||
|
||||
const userId = session?.session?.factors?.user?.id;
|
||||
|
||||
if (!userId) {
|
||||
throw new Error("Could not get session");
|
||||
}
|
||||
// TODO: add org context
|
||||
|
||||
// use session token to add the passkey
|
||||
const registerLink = await createPasskeyRegistrationLink({
|
||||
serviceUrl,
|
||||
userId,
|
||||
});
|
||||
|
||||
if (!registerLink.code) {
|
||||
throw new Error("Missing code in response");
|
||||
}
|
||||
|
||||
return registerPasskey({
|
||||
serviceUrl,
|
||||
userId,
|
||||
code: registerLink.code,
|
||||
domain: hostname,
|
||||
});
|
||||
}
|
||||
|
||||
export async function verifyPasskeyRegistration(command: VerifyPasskeyCommand) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
// if no name is provided, try to generate one from the user agent
|
||||
let passkeyName = command.passkeyName;
|
||||
if (!passkeyName) {
|
||||
const headersList = await headers();
|
||||
const userAgentStructure = { headers: headersList };
|
||||
const { browser, device, os } = userAgent(userAgentStructure);
|
||||
|
||||
passkeyName = `${device.vendor ?? ""} ${device.model ?? ""}${
|
||||
device.vendor || device.model ? ", " : ""
|
||||
}${os.name}${os.name ? ", " : ""}${browser.name}`;
|
||||
}
|
||||
|
||||
const sessionCookie = await getSessionCookieById({
|
||||
sessionId: command.sessionId,
|
||||
});
|
||||
const session = await getSession({
|
||||
serviceUrl,
|
||||
sessionId: sessionCookie.id,
|
||||
sessionToken: sessionCookie.token,
|
||||
});
|
||||
const userId = session?.session?.factors?.user?.id;
|
||||
|
||||
if (!userId) {
|
||||
throw new Error("Could not get session");
|
||||
}
|
||||
|
||||
return zitadelVerifyPasskeyRegistration({
|
||||
serviceUrl,
|
||||
request: create(VerifyPasskeyRegistrationRequestSchema, {
|
||||
passkeyId: command.passkeyId,
|
||||
publicKeyCredential: command.publicKeyCredential,
|
||||
passkeyName,
|
||||
userId,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
type SendPasskeyCommand = {
|
||||
loginName?: string;
|
||||
sessionId?: string;
|
||||
organization?: string;
|
||||
checks?: Checks;
|
||||
requestId?: string;
|
||||
lifetime?: Duration;
|
||||
};
|
||||
|
||||
export async function sendPasskey(command: SendPasskeyCommand) {
|
||||
let { loginName, sessionId, organization, checks, requestId } = command;
|
||||
const recentSession = sessionId
|
||||
? await getSessionCookieById({ sessionId })
|
||||
: loginName
|
||||
? await getSessionCookieByLoginName({ loginName, organization })
|
||||
: await getMostRecentSessionCookie();
|
||||
|
||||
if (!recentSession) {
|
||||
return {
|
||||
error: "Could not find session",
|
||||
};
|
||||
}
|
||||
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
const loginSettings = await getLoginSettings({
|
||||
serviceUrl,
|
||||
organization,
|
||||
});
|
||||
|
||||
let lifetime = checks?.webAuthN
|
||||
? loginSettings?.multiFactorCheckLifetime // TODO different lifetime for webauthn u2f/passkey
|
||||
: checks?.otpEmail || checks?.otpSms
|
||||
? loginSettings?.secondFactorCheckLifetime
|
||||
: undefined;
|
||||
|
||||
if (!lifetime) {
|
||||
console.warn("No passkey lifetime provided, defaulting to 24 hours");
|
||||
|
||||
lifetime = {
|
||||
seconds: BigInt(60 * 60 * 24), // default to 24 hours
|
||||
nanos: 0,
|
||||
} as Duration;
|
||||
}
|
||||
|
||||
const session = await setSessionAndUpdateCookie({
|
||||
recentCookie: recentSession,
|
||||
checks,
|
||||
requestId,
|
||||
lifetime,
|
||||
});
|
||||
|
||||
if (!session || !session?.factors?.user?.id) {
|
||||
return { error: "Could not update session" };
|
||||
}
|
||||
|
||||
const userResponse = await getUserByID({
|
||||
serviceUrl,
|
||||
userId: session?.factors?.user?.id,
|
||||
});
|
||||
|
||||
if (!userResponse.user) {
|
||||
return { error: "User not found in the system" };
|
||||
}
|
||||
|
||||
const humanUser =
|
||||
userResponse.user.type.case === "human"
|
||||
? userResponse.user.type.value
|
||||
: undefined;
|
||||
|
||||
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 };
|
||||
}
|
||||
@@ -0,0 +1,478 @@
|
||||
"use server";
|
||||
|
||||
import {
|
||||
createSessionAndUpdateCookie,
|
||||
setSessionAndUpdateCookie,
|
||||
} from "@/lib/server/cookie";
|
||||
import {
|
||||
getLockoutSettings,
|
||||
getLoginSettings,
|
||||
getPasswordExpirySettings,
|
||||
getSession,
|
||||
getUserByID,
|
||||
listAuthenticationMethodTypes,
|
||||
listUsers,
|
||||
passwordReset,
|
||||
setPassword,
|
||||
setUserPassword,
|
||||
} 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 { 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 { headers } from "next/headers";
|
||||
import { getNextUrl } from "../client";
|
||||
import { getSessionCookieById, getSessionCookieByLoginName } from "../cookies";
|
||||
import { getServiceUrlFromHeaders } from "../service-url";
|
||||
import {
|
||||
checkEmailVerification,
|
||||
checkMFAFactors,
|
||||
checkPasswordChangeRequired,
|
||||
checkUserVerification,
|
||||
} from "../verify-helper";
|
||||
import { createServerTransport } from "../zitadel";
|
||||
|
||||
type ResetPasswordCommand = {
|
||||
loginName: string;
|
||||
organization?: string;
|
||||
requestId?: string;
|
||||
};
|
||||
|
||||
export async function resetPassword(command: ResetPasswordCommand) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
const host = _headers.get("host");
|
||||
|
||||
if (!host || typeof host !== "string") {
|
||||
throw new Error("No host found");
|
||||
}
|
||||
|
||||
const users = await listUsers({
|
||||
serviceUrl,
|
||||
loginName: command.loginName,
|
||||
organizationId: command.organization,
|
||||
});
|
||||
|
||||
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;
|
||||
|
||||
const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? "";
|
||||
|
||||
return passwordReset({
|
||||
serviceUrl,
|
||||
userId,
|
||||
urlTemplate:
|
||||
`${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/password/set?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}` +
|
||||
(command.requestId ? `&requestId=${command.requestId}` : ""),
|
||||
});
|
||||
}
|
||||
|
||||
export type UpdateSessionCommand = {
|
||||
loginName: string;
|
||||
organization?: string;
|
||||
checks: Checks;
|
||||
requestId?: string;
|
||||
};
|
||||
|
||||
export async function sendPassword(command: UpdateSessionCommand) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
let sessionCookie = await getSessionCookieByLoginName({
|
||||
loginName: command.loginName,
|
||||
organization: command.organization,
|
||||
}).catch((error) => {
|
||||
console.warn("Ignored error:", error);
|
||||
});
|
||||
|
||||
let session;
|
||||
let user: User;
|
||||
let loginSettings: LoginSettings | undefined;
|
||||
|
||||
if (!sessionCookie) {
|
||||
const users = await listUsers({
|
||||
serviceUrl,
|
||||
loginName: command.loginName,
|
||||
organizationId: command.organization,
|
||||
});
|
||||
|
||||
if (users.details?.totalResult == BigInt(1) && users.result[0].userId) {
|
||||
user = users.result[0];
|
||||
|
||||
const checks = create(ChecksSchema, {
|
||||
user: { search: { case: "userId", value: users.result[0].userId } },
|
||||
password: { password: command.checks.password?.password },
|
||||
});
|
||||
|
||||
loginSettings = await getLoginSettings({
|
||||
serviceUrl,
|
||||
organization: command.organization,
|
||||
});
|
||||
|
||||
try {
|
||||
session = await createSessionAndUpdateCookie({
|
||||
checks,
|
||||
requestId: command.requestId,
|
||||
lifetime: loginSettings?.passwordCheckLifetime,
|
||||
});
|
||||
} catch (error: any) {
|
||||
if ("failedAttempts" in error && error.failedAttempts) {
|
||||
const lockoutSettings = await getLockoutSettings({
|
||||
serviceUrl,
|
||||
orgId: command.organization,
|
||||
});
|
||||
|
||||
return {
|
||||
error:
|
||||
`Failed to authenticate. You had ${error.failedAttempts} of ${lockoutSettings?.maxPasswordAttempts} password attempts.` +
|
||||
(lockoutSettings?.maxPasswordAttempts &&
|
||||
error.failedAttempts >= lockoutSettings?.maxPasswordAttempts
|
||||
? "Contact your administrator to unlock your account"
|
||||
: ""),
|
||||
};
|
||||
}
|
||||
return { error: "Could not create session for user" };
|
||||
}
|
||||
}
|
||||
|
||||
// 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,
|
||||
organization: sessionCookie.organization,
|
||||
});
|
||||
|
||||
if (!loginSettings) {
|
||||
return { error: "Could not load login settings" };
|
||||
}
|
||||
|
||||
let lifetime = loginSettings.passwordCheckLifetime;
|
||||
|
||||
if (!lifetime) {
|
||||
console.warn("No password lifetime provided, defaulting to 24 hours");
|
||||
lifetime = {
|
||||
seconds: BigInt(60 * 60 * 24), // default to 24 hours
|
||||
nanos: 0,
|
||||
} as Duration;
|
||||
}
|
||||
|
||||
try {
|
||||
session = await setSessionAndUpdateCookie({
|
||||
recentCookie: sessionCookie,
|
||||
checks: command.checks,
|
||||
requestId: command.requestId,
|
||||
lifetime,
|
||||
});
|
||||
} catch (error: any) {
|
||||
if ("failedAttempts" in error && error.failedAttempts) {
|
||||
const lockoutSettings = await getLockoutSettings({
|
||||
serviceUrl,
|
||||
orgId: command.organization,
|
||||
});
|
||||
|
||||
return {
|
||||
error:
|
||||
`Failed to authenticate. You had ${error.failedAttempts} of ${lockoutSettings?.maxPasswordAttempts} password attempts.` +
|
||||
(lockoutSettings?.maxPasswordAttempts &&
|
||||
error.failedAttempts >= lockoutSettings?.maxPasswordAttempts
|
||||
? " Contact your administrator to unlock your account"
|
||||
: ""),
|
||||
};
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (!session?.factors?.user?.id) {
|
||||
return { error: "Could not create session for user" };
|
||||
}
|
||||
|
||||
const userResponse = await getUserByID({
|
||||
serviceUrl,
|
||||
userId: session?.factors?.user?.id,
|
||||
});
|
||||
|
||||
if (!userResponse.user) {
|
||||
return { error: "User not found in the system" };
|
||||
}
|
||||
|
||||
user = userResponse.user;
|
||||
}
|
||||
|
||||
if (!loginSettings) {
|
||||
loginSettings = await getLoginSettings({
|
||||
serviceUrl,
|
||||
organization:
|
||||
command.organization ?? session.factors?.user?.organizationId,
|
||||
});
|
||||
}
|
||||
|
||||
if (!session?.factors?.user?.id || !sessionCookie) {
|
||||
return { error: "Could not create session for user" };
|
||||
}
|
||||
|
||||
const humanUser = user.type.case === "human" ? user.type.value : undefined;
|
||||
|
||||
const expirySettings = await getPasswordExpirySettings({
|
||||
serviceUrl,
|
||||
orgId: command.organization ?? session.factors?.user?.organizationId,
|
||||
});
|
||||
|
||||
// check if the user has to change password first
|
||||
const passwordChangedCheck = checkPasswordChangeRequired(
|
||||
expirySettings,
|
||||
session,
|
||||
humanUser,
|
||||
command.organization,
|
||||
command.requestId,
|
||||
);
|
||||
|
||||
if (passwordChangedCheck?.redirect) {
|
||||
return passwordChangedCheck;
|
||||
}
|
||||
|
||||
// throw error if user is in initial state here and do not continue
|
||||
if (user.state === UserState.INITIAL) {
|
||||
return { error: "Initial User not supported" };
|
||||
}
|
||||
|
||||
// check to see if user was verified
|
||||
const emailVerificationCheck = checkEmailVerification(
|
||||
session,
|
||||
humanUser,
|
||||
command.organization,
|
||||
command.requestId,
|
||||
);
|
||||
|
||||
if (emailVerificationCheck?.redirect) {
|
||||
return emailVerificationCheck;
|
||||
}
|
||||
|
||||
// if password, check if user has MFA methods
|
||||
let authMethods;
|
||||
if (command.checks && command.checks.password && session.factors?.user?.id) {
|
||||
const response = await listAuthenticationMethodTypes({
|
||||
serviceUrl,
|
||||
userId: session.factors.user.id,
|
||||
});
|
||||
if (response.authMethodTypes && response.authMethodTypes.length) {
|
||||
authMethods = response.authMethodTypes;
|
||||
}
|
||||
}
|
||||
|
||||
if (!authMethods) {
|
||||
return { error: "Could not verify password!" };
|
||||
}
|
||||
|
||||
const mfaFactorCheck = await checkMFAFactors(
|
||||
serviceUrl,
|
||||
session,
|
||||
loginSettings,
|
||||
authMethods,
|
||||
command.organization,
|
||||
command.requestId,
|
||||
);
|
||||
|
||||
if (mfaFactorCheck?.redirect) {
|
||||
return mfaFactorCheck;
|
||||
}
|
||||
|
||||
if (command.requestId && session.id) {
|
||||
const nextUrl = await getNextUrl(
|
||||
{
|
||||
sessionId: session.id,
|
||||
requestId: command.requestId,
|
||||
organization:
|
||||
command.organization ?? session.factors?.user?.organizationId,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
|
||||
return { redirect: nextUrl };
|
||||
}
|
||||
|
||||
const url = await getNextUrl(
|
||||
{
|
||||
loginName: session.factors.user.loginName,
|
||||
organization: session.factors?.user?.organizationId,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
|
||||
return { redirect: url };
|
||||
}
|
||||
|
||||
// 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;
|
||||
}) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
// check for init state
|
||||
const { user } = await getUserByID({
|
||||
serviceUrl,
|
||||
userId: command.userId,
|
||||
});
|
||||
|
||||
if (!user || user.userId !== command.userId) {
|
||||
return { error: "Could not send Password Reset Link" };
|
||||
}
|
||||
const userId = user.userId;
|
||||
|
||||
if (user.state === UserState.INITIAL) {
|
||||
return { error: "User Initial State is not supported" };
|
||||
}
|
||||
|
||||
// check if the user has no password set in order to set a password
|
||||
if (!command.code) {
|
||||
const authmethods = await listAuthenticationMethodTypes({
|
||||
serviceUrl,
|
||||
userId,
|
||||
});
|
||||
|
||||
// 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",
|
||||
};
|
||||
}
|
||||
|
||||
// check if a verification was done earlier
|
||||
const hasValidUserVerificationCheck = await checkUserVerification(
|
||||
user.userId,
|
||||
);
|
||||
|
||||
if (!hasValidUserVerificationCheck) {
|
||||
return { error: "User Verification Check has to be done" };
|
||||
}
|
||||
}
|
||||
|
||||
return setUserPassword({
|
||||
serviceUrl,
|
||||
userId,
|
||||
password: command.password,
|
||||
code: command.code,
|
||||
});
|
||||
}
|
||||
|
||||
type CheckSessionAndSetPasswordCommand = {
|
||||
sessionId: string;
|
||||
password: string;
|
||||
};
|
||||
|
||||
export async function checkSessionAndSetPassword({
|
||||
sessionId,
|
||||
password,
|
||||
}: CheckSessionAndSetPasswordCommand) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
const sessionCookie = await getSessionCookieById({ sessionId });
|
||||
|
||||
const { session } = await getSession({
|
||||
serviceUrl,
|
||||
sessionId: sessionCookie.id,
|
||||
sessionToken: sessionCookie.token,
|
||||
});
|
||||
|
||||
if (!session || !session.factors?.user?.id) {
|
||||
return { error: "Could not load session" };
|
||||
}
|
||||
|
||||
const payload = create(SetPasswordRequestSchema, {
|
||||
userId: session.factors.user.id,
|
||||
newPassword: {
|
||||
password,
|
||||
},
|
||||
});
|
||||
|
||||
// check if the user has no password set in order to set a password
|
||||
const authmethods = await listAuthenticationMethodTypes({
|
||||
serviceUrl,
|
||||
userId: session.factors.user.id,
|
||||
});
|
||||
|
||||
if (!authmethods) {
|
||||
return { error: "Could not load auth methods" };
|
||||
}
|
||||
|
||||
const requiredAuthMethodsForForceMFA = [
|
||||
AuthenticationMethodType.OTP_EMAIL,
|
||||
AuthenticationMethodType.OTP_SMS,
|
||||
AuthenticationMethodType.TOTP,
|
||||
AuthenticationMethodType.U2F,
|
||||
];
|
||||
|
||||
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
|
||||
);
|
||||
|
||||
// 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) {
|
||||
return setPassword({ serviceUrl, payload }).catch((error) => {
|
||||
// throw error if failed precondition (ex. User is not yet initialized)
|
||||
if (error.code === 9 && error.message) {
|
||||
return { error: "Failed precondition" };
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
const transport = async (serviceUrl: string, token: string) => {
|
||||
return createServerTransport(token, serviceUrl);
|
||||
};
|
||||
|
||||
const myUserService = async (serviceUrl: string, sessionToken: string) => {
|
||||
const transportPromise = await transport(serviceUrl, sessionToken);
|
||||
return createUserServiceClient(transportPromise);
|
||||
};
|
||||
|
||||
const selfService = await myUserService(
|
||||
serviceUrl,
|
||||
`${sessionCookie.token}`,
|
||||
);
|
||||
|
||||
return selfService
|
||||
.setPassword(
|
||||
{
|
||||
userId: session.factors.user.id,
|
||||
newPassword: { password, changeRequired: false },
|
||||
},
|
||||
{},
|
||||
)
|
||||
.catch((error: ConnectError) => {
|
||||
console.log(error);
|
||||
if (error.code === 7) {
|
||||
return { error: "Session is not valid." };
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
"use server";
|
||||
|
||||
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 { headers } from "next/headers";
|
||||
import { getNextUrl } from "../client";
|
||||
import { getServiceUrlFromHeaders } from "../service-url";
|
||||
import { checkEmailVerification } from "../verify-helper";
|
||||
|
||||
type RegisterUserCommand = {
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
password?: string;
|
||||
organization: string;
|
||||
requestId?: string;
|
||||
};
|
||||
|
||||
export type RegisterUserResponse = {
|
||||
userId: string;
|
||||
sessionId: string;
|
||||
factors: Factors | undefined;
|
||||
};
|
||||
export async function registerUser(command: RegisterUserCommand) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
const host = _headers.get("host");
|
||||
|
||||
if (!host || typeof host !== "string") {
|
||||
throw new Error("No host found");
|
||||
}
|
||||
|
||||
const addResponse = await addHumanUser({
|
||||
serviceUrl,
|
||||
email: command.email,
|
||||
firstName: command.firstName,
|
||||
lastName: command.lastName,
|
||||
password: command.password ? command.password : undefined,
|
||||
organization: command.organization,
|
||||
});
|
||||
|
||||
if (!addResponse) {
|
||||
return { error: "Could not create user" };
|
||||
}
|
||||
|
||||
const loginSettings = await getLoginSettings({
|
||||
serviceUrl,
|
||||
organization: command.organization,
|
||||
});
|
||||
|
||||
let checkPayload: any = {
|
||||
user: { search: { case: "userId", value: addResponse.userId } },
|
||||
};
|
||||
|
||||
if (command.password) {
|
||||
checkPayload = {
|
||||
...checkPayload,
|
||||
password: { password: command.password },
|
||||
} as ChecksJson;
|
||||
}
|
||||
|
||||
const checks = create(ChecksSchema, checkPayload);
|
||||
|
||||
const session = await createSessionAndUpdateCookie({
|
||||
checks,
|
||||
requestId: command.requestId,
|
||||
lifetime: command.password
|
||||
? loginSettings?.passwordCheckLifetime
|
||||
: undefined,
|
||||
});
|
||||
|
||||
if (!session || !session.factors?.user) {
|
||||
return { error: "Could not create session" };
|
||||
}
|
||||
|
||||
if (!command.password) {
|
||||
const params = new URLSearchParams({
|
||||
loginName: session.factors.user.loginName,
|
||||
organization: session.factors.user.organizationId,
|
||||
});
|
||||
|
||||
if (command.requestId) {
|
||||
params.append("requestId", command.requestId);
|
||||
}
|
||||
|
||||
return { redirect: "/passkey/set?" + params };
|
||||
} else {
|
||||
const userResponse = await getUserByID({
|
||||
serviceUrl,
|
||||
userId: session?.factors?.user?.id,
|
||||
});
|
||||
|
||||
if (!userResponse.user) {
|
||||
return { error: "User not found in the system" };
|
||||
}
|
||||
|
||||
const humanUser =
|
||||
userResponse.user.type.case === "human"
|
||||
? userResponse.user.type.value
|
||||
: undefined;
|
||||
|
||||
const emailVerificationCheck = checkEmailVerification(
|
||||
session,
|
||||
humanUser,
|
||||
session.factors.user.organizationId,
|
||||
command.requestId,
|
||||
);
|
||||
|
||||
if (emailVerificationCheck?.redirect) {
|
||||
return emailVerificationCheck;
|
||||
}
|
||||
|
||||
const url = await getNextUrl(
|
||||
command.requestId && session.id
|
||||
? {
|
||||
sessionId: session.id,
|
||||
requestId: command.requestId,
|
||||
organization: session.factors.user.organizationId,
|
||||
}
|
||||
: {
|
||||
loginName: session.factors.user.loginName,
|
||||
organization: session.factors.user.organizationId,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
|
||||
return { redirect: url };
|
||||
}
|
||||
}
|
||||
|
||||
type RegisterUserAndLinkToIDPommand = {
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
organization: string;
|
||||
requestId?: string;
|
||||
idpIntent: {
|
||||
idpIntentId: string;
|
||||
idpIntentToken: string;
|
||||
};
|
||||
idpUserId: string;
|
||||
idpId: string;
|
||||
idpUserName: string;
|
||||
};
|
||||
|
||||
export type registerUserAndLinkToIDPResponse = {
|
||||
userId: string;
|
||||
sessionId: string;
|
||||
factors: Factors | undefined;
|
||||
};
|
||||
export async function registerUserAndLinkToIDP(
|
||||
command: RegisterUserAndLinkToIDPommand,
|
||||
) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
const host = _headers.get("host");
|
||||
|
||||
if (!host || typeof host !== "string") {
|
||||
throw new Error("No host found");
|
||||
}
|
||||
|
||||
const addResponse = await addHumanUser({
|
||||
serviceUrl,
|
||||
email: command.email,
|
||||
firstName: command.firstName,
|
||||
lastName: command.lastName,
|
||||
organization: command.organization,
|
||||
});
|
||||
|
||||
if (!addResponse) {
|
||||
return { error: "Could not create user" };
|
||||
}
|
||||
|
||||
const loginSettings = await getLoginSettings({
|
||||
serviceUrl,
|
||||
organization: command.organization,
|
||||
});
|
||||
|
||||
const idpLink = await addIDPLink({
|
||||
serviceUrl,
|
||||
idp: {
|
||||
id: command.idpId,
|
||||
userId: command.idpUserId,
|
||||
userName: command.idpUserName,
|
||||
},
|
||||
userId: addResponse.userId,
|
||||
});
|
||||
|
||||
if (!idpLink) {
|
||||
return { error: "Could not link IDP to user" };
|
||||
}
|
||||
|
||||
const session = await createSessionForIdpAndUpdateCookie({
|
||||
requestId: command.requestId,
|
||||
userId: addResponse.userId, // the user we just created
|
||||
idpIntent: command.idpIntent,
|
||||
lifetime: loginSettings?.externalLoginCheckLifetime,
|
||||
});
|
||||
|
||||
if (!session || !session.factors?.user) {
|
||||
return { error: "Could not create session" };
|
||||
}
|
||||
|
||||
const url = await getNextUrl(
|
||||
command.requestId && session.id
|
||||
? {
|
||||
sessionId: session.id,
|
||||
requestId: command.requestId,
|
||||
organization: session.factors.user.organizationId,
|
||||
}
|
||||
: {
|
||||
loginName: session.factors.user.loginName,
|
||||
organization: session.factors.user.organizationId,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
|
||||
return { redirect: url };
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
"use server";
|
||||
|
||||
import { setSessionAndUpdateCookie } from "@/lib/server/cookie";
|
||||
import {
|
||||
deleteSession,
|
||||
getLoginSettings,
|
||||
getSecuritySettings,
|
||||
humanMFAInitSkipped,
|
||||
listAuthenticationMethodTypes,
|
||||
} from "@/lib/zitadel";
|
||||
import { Duration } from "@zitadel/client";
|
||||
import { RequestChallenges } from "@zitadel/proto/zitadel/session/v2/challenge_pb";
|
||||
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 {
|
||||
getMostRecentSessionCookie,
|
||||
getSessionCookieById,
|
||||
getSessionCookieByLoginName,
|
||||
removeSessionFromCookie,
|
||||
} from "../cookies";
|
||||
import { getServiceUrlFromHeaders } from "../service-url";
|
||||
|
||||
export async function skipMFAAndContinueWithNextUrl({
|
||||
userId,
|
||||
requestId,
|
||||
loginName,
|
||||
sessionId,
|
||||
organization,
|
||||
}: {
|
||||
userId: string;
|
||||
loginName?: string;
|
||||
sessionId?: string;
|
||||
requestId?: string;
|
||||
organization?: string;
|
||||
}) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
const loginSettings = await getLoginSettings({
|
||||
serviceUrl,
|
||||
organization: organization,
|
||||
});
|
||||
|
||||
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 };
|
||||
}
|
||||
}
|
||||
|
||||
export async function continueWithSession({
|
||||
requestId,
|
||||
...session
|
||||
}: Session & { requestId?: string }) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
const loginSettings = await getLoginSettings({
|
||||
serviceUrl,
|
||||
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 };
|
||||
}
|
||||
}
|
||||
|
||||
export type UpdateSessionCommand = {
|
||||
loginName?: string;
|
||||
sessionId?: string;
|
||||
organization?: string;
|
||||
checks?: Checks;
|
||||
requestId?: string;
|
||||
challenges?: RequestChallenges;
|
||||
lifetime?: Duration;
|
||||
};
|
||||
|
||||
export async function updateSession(options: UpdateSessionCommand) {
|
||||
let { loginName, sessionId, organization, checks, requestId, challenges } =
|
||||
options;
|
||||
const recentSession = sessionId
|
||||
? await getSessionCookieById({ sessionId })
|
||||
: loginName
|
||||
? await getSessionCookieByLoginName({ loginName, organization })
|
||||
: await getMostRecentSessionCookie();
|
||||
|
||||
if (!recentSession) {
|
||||
return {
|
||||
error: "Could not find session",
|
||||
};
|
||||
}
|
||||
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
const host = _headers.get("host");
|
||||
|
||||
if (!host) {
|
||||
return { error: "Could not get host" };
|
||||
}
|
||||
|
||||
if (
|
||||
host &&
|
||||
challenges &&
|
||||
challenges.webAuthN &&
|
||||
!challenges.webAuthN.domain
|
||||
) {
|
||||
const [hostname] = host.split(":");
|
||||
|
||||
challenges.webAuthN.domain = hostname;
|
||||
}
|
||||
|
||||
const loginSettings = await getLoginSettings({
|
||||
serviceUrl,
|
||||
organization,
|
||||
});
|
||||
|
||||
let lifetime = checks?.webAuthN
|
||||
? loginSettings?.multiFactorCheckLifetime // TODO different lifetime for webauthn u2f/passkey
|
||||
: checks?.otpEmail || checks?.otpSms
|
||||
? loginSettings?.secondFactorCheckLifetime
|
||||
: undefined;
|
||||
|
||||
if (!lifetime) {
|
||||
console.warn("No lifetime provided for session, defaulting to 24 hours");
|
||||
lifetime = {
|
||||
seconds: BigInt(60 * 60 * 24), // default to 24 hours
|
||||
nanos: 0,
|
||||
} as Duration;
|
||||
}
|
||||
|
||||
const session = await setSessionAndUpdateCookie({
|
||||
recentCookie: recentSession,
|
||||
checks,
|
||||
challenges,
|
||||
requestId,
|
||||
lifetime,
|
||||
});
|
||||
|
||||
if (!session) {
|
||||
return { error: "Could not update session" };
|
||||
}
|
||||
|
||||
// if password, check if user has MFA methods
|
||||
let authMethods;
|
||||
if (checks && checks.password && session.factors?.user?.id) {
|
||||
const response = await listAuthenticationMethodTypes({
|
||||
serviceUrl,
|
||||
userId: session.factors.user.id,
|
||||
});
|
||||
if (response.authMethodTypes && response.authMethodTypes.length) {
|
||||
authMethods = response.authMethodTypes;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
sessionId: session.id,
|
||||
factors: session.factors,
|
||||
challenges: session.challenges,
|
||||
authMethods,
|
||||
};
|
||||
}
|
||||
|
||||
type ClearSessionOptions = {
|
||||
sessionId: string;
|
||||
};
|
||||
|
||||
export async function clearSession(options: ClearSessionOptions) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
const { sessionId } = options;
|
||||
|
||||
const sessionCookie = await getSessionCookieById({ sessionId });
|
||||
|
||||
const deleteResponse = await deleteSession({
|
||||
serviceUrl,
|
||||
sessionId: sessionCookie.id,
|
||||
sessionToken: sessionCookie.token,
|
||||
});
|
||||
|
||||
const securitySettings = await getSecuritySettings({ serviceUrl });
|
||||
const sameSite = securitySettings?.embeddedIframe?.enabled ? "none" : true;
|
||||
|
||||
if (!deleteResponse) {
|
||||
throw new Error("Could not delete session");
|
||||
}
|
||||
|
||||
return removeSessionFromCookie({ session: sessionCookie, sameSite });
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
"use server";
|
||||
|
||||
import { getSession, registerU2F, verifyU2FRegistration } from "@/lib/zitadel";
|
||||
import { create } from "@zitadel/client";
|
||||
import { VerifyU2FRegistrationRequestSchema } from "@zitadel/proto/zitadel/user/v2/user_service_pb";
|
||||
import { headers } from "next/headers";
|
||||
import { userAgent } from "next/server";
|
||||
import { getSessionCookieById } from "../cookies";
|
||||
import { getServiceUrlFromHeaders } from "../service-url";
|
||||
|
||||
type RegisterU2FCommand = {
|
||||
sessionId: string;
|
||||
};
|
||||
|
||||
type VerifyU2FCommand = {
|
||||
u2fId: string;
|
||||
passkeyName?: string;
|
||||
publicKeyCredential: any;
|
||||
sessionId: string;
|
||||
};
|
||||
|
||||
export async function addU2F(command: RegisterU2FCommand) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
const host = _headers.get("host");
|
||||
|
||||
if (!host || typeof host !== "string") {
|
||||
throw new Error("No host found");
|
||||
}
|
||||
|
||||
const sessionCookie = await getSessionCookieById({
|
||||
sessionId: command.sessionId,
|
||||
});
|
||||
|
||||
if (!sessionCookie) {
|
||||
return { error: "Could not get session" };
|
||||
}
|
||||
|
||||
const session = await getSession({
|
||||
serviceUrl,
|
||||
sessionId: sessionCookie.id,
|
||||
sessionToken: sessionCookie.token,
|
||||
});
|
||||
|
||||
const [hostname] = host.split(":");
|
||||
|
||||
if (!hostname) {
|
||||
throw new Error("Could not get hostname");
|
||||
}
|
||||
|
||||
const userId = session?.session?.factors?.user?.id;
|
||||
|
||||
if (!session || !userId) {
|
||||
return { error: "Could not get session" };
|
||||
}
|
||||
|
||||
return registerU2F({ serviceUrl, userId, domain: hostname });
|
||||
}
|
||||
|
||||
export async function verifyU2F(command: VerifyU2FCommand) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
const host = _headers.get("host");
|
||||
|
||||
if (!host || typeof host !== "string") {
|
||||
throw new Error("No host found");
|
||||
}
|
||||
|
||||
let passkeyName = command.passkeyName;
|
||||
if (!passkeyName) {
|
||||
const headersList = await headers();
|
||||
const userAgentStructure = { headers: headersList };
|
||||
const { browser, device, os } = userAgent(userAgentStructure);
|
||||
|
||||
passkeyName = `${device.vendor ?? ""} ${device.model ?? ""}${
|
||||
device.vendor || device.model ? ", " : ""
|
||||
}${os.name}${os.name ? ", " : ""}${browser.name}`;
|
||||
}
|
||||
const sessionCookie = await getSessionCookieById({
|
||||
sessionId: command.sessionId,
|
||||
});
|
||||
|
||||
const session = await getSession({
|
||||
serviceUrl,
|
||||
sessionId: sessionCookie.id,
|
||||
sessionToken: sessionCookie.token,
|
||||
});
|
||||
|
||||
const userId = session?.session?.factors?.user?.id;
|
||||
|
||||
if (!userId) {
|
||||
return { error: "Could not get session" };
|
||||
}
|
||||
|
||||
const request = create(VerifyU2FRegistrationRequestSchema, {
|
||||
u2fId: command.u2fId,
|
||||
publicKeyCredential: command.publicKeyCredential,
|
||||
tokenName: passkeyName,
|
||||
userId,
|
||||
});
|
||||
|
||||
return verifyU2FRegistration({ serviceUrl, request });
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
"use server";
|
||||
|
||||
import {
|
||||
createInviteCode,
|
||||
getLoginSettings,
|
||||
getSession,
|
||||
getUserByID,
|
||||
listAuthenticationMethodTypes,
|
||||
verifyEmail,
|
||||
verifyInviteCode,
|
||||
verifyTOTPRegistration,
|
||||
sendEmailCode as zitadelSendEmailCode,
|
||||
} from "@/lib/zitadel";
|
||||
import crypto from "crypto";
|
||||
|
||||
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 { getSessionCookieByLoginName } from "../cookies";
|
||||
import { getOrSetFingerprintId } from "../fingerprint";
|
||||
import { getServiceUrlFromHeaders } from "../service-url";
|
||||
import { loadMostRecentSession } from "../session";
|
||||
import { checkMFAFactors } from "../verify-helper";
|
||||
import { createSessionAndUpdateCookie } from "./cookie";
|
||||
|
||||
export async function verifyTOTP(
|
||||
code: string,
|
||||
loginName?: string,
|
||||
organization?: string,
|
||||
) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
return loadMostRecentSession({
|
||||
serviceUrl,
|
||||
sessionParams: {
|
||||
loginName,
|
||||
organization,
|
||||
},
|
||||
}).then((session) => {
|
||||
if (session?.factors?.user?.id) {
|
||||
return verifyTOTPRegistration({
|
||||
serviceUrl,
|
||||
code,
|
||||
userId: session.factors.user.id,
|
||||
});
|
||||
} else {
|
||||
throw Error("No user id found in session.");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
type VerifyUserByEmailCommand = {
|
||||
userId: string;
|
||||
loginName?: string; // to determine already existing session
|
||||
organization?: string;
|
||||
code: string;
|
||||
isInvite: boolean;
|
||||
requestId?: string;
|
||||
};
|
||||
|
||||
export async function sendVerification(command: VerifyUserByEmailCommand) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
const verifyResponse = command.isInvite
|
||||
? await verifyInviteCode({
|
||||
serviceUrl,
|
||||
userId: command.userId,
|
||||
verificationCode: command.code,
|
||||
}).catch((error) => {
|
||||
console.warn(error);
|
||||
return { error: "Could not verify invite" };
|
||||
})
|
||||
: await verifyEmail({
|
||||
serviceUrl,
|
||||
userId: command.userId,
|
||||
verificationCode: command.code,
|
||||
}).catch((error) => {
|
||||
console.warn(error);
|
||||
return { error: "Could not verify email" };
|
||||
});
|
||||
|
||||
if ("error" in verifyResponse) {
|
||||
return verifyResponse;
|
||||
}
|
||||
|
||||
if (!verifyResponse) {
|
||||
return { error: "Could not verify" };
|
||||
}
|
||||
|
||||
let session: Session | undefined;
|
||||
const userResponse = await getUserByID({
|
||||
serviceUrl,
|
||||
userId: command.userId,
|
||||
});
|
||||
|
||||
if (!userResponse || !userResponse.user) {
|
||||
return { error: "Could not load user" };
|
||||
}
|
||||
|
||||
const user = userResponse.user;
|
||||
|
||||
const sessionCookie = await getSessionCookieByLoginName({
|
||||
loginName:
|
||||
"loginName" in command ? command.loginName : user.preferredLoginName,
|
||||
organization: command.organization,
|
||||
}).catch((error) => {
|
||||
console.warn("Ignored error:", error); // checked later
|
||||
});
|
||||
|
||||
if (sessionCookie) {
|
||||
session = await getSession({
|
||||
serviceUrl,
|
||||
sessionId: sessionCookie.id,
|
||||
sessionToken: sessionCookie.token,
|
||||
}).then((response) => {
|
||||
if (response?.session) {
|
||||
return response.session;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// load auth methods for user
|
||||
const authMethodResponse = await listAuthenticationMethodTypes({
|
||||
serviceUrl,
|
||||
userId: user.userId,
|
||||
});
|
||||
|
||||
if (!authMethodResponse || !authMethodResponse.authMethodTypes) {
|
||||
return { error: "Could not load possible authenticators" };
|
||||
}
|
||||
|
||||
// if no authmethods are found on the user, redirect to set one up
|
||||
if (
|
||||
authMethodResponse &&
|
||||
authMethodResponse.authMethodTypes &&
|
||||
authMethodResponse.authMethodTypes.length == 0
|
||||
) {
|
||||
if (!sessionCookie) {
|
||||
const checks = create(ChecksSchema, {
|
||||
user: {
|
||||
search: {
|
||||
case: "loginName",
|
||||
value: userResponse.user.preferredLoginName,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
session = await createSessionAndUpdateCookie({
|
||||
checks,
|
||||
requestId: command.requestId,
|
||||
});
|
||||
}
|
||||
|
||||
if (!session) {
|
||||
return { error: "Could not create session" };
|
||||
}
|
||||
|
||||
const params = new URLSearchParams({
|
||||
sessionId: session.id,
|
||||
});
|
||||
|
||||
if (session.factors?.user?.loginName) {
|
||||
params.set("loginName", session.factors?.user?.loginName);
|
||||
}
|
||||
|
||||
// set hash of userId and userAgentId to prevent attacks, checks are done for users with invalid sessions and invalid userAgentId
|
||||
const cookiesList = await cookies();
|
||||
const userAgentId = await getOrSetFingerprintId();
|
||||
|
||||
const verificationCheck = crypto
|
||||
.createHash("sha256")
|
||||
.update(`${user.userId}:${userAgentId}`)
|
||||
.digest("hex");
|
||||
|
||||
await cookiesList.set({
|
||||
name: "verificationCheck",
|
||||
value: verificationCheck,
|
||||
httpOnly: true,
|
||||
path: "/",
|
||||
maxAge: 300, // 5 minutes
|
||||
});
|
||||
|
||||
return { redirect: `/authenticator/set?${params}` };
|
||||
}
|
||||
|
||||
// if no session found only show success page,
|
||||
// if user is invited, recreate invite flow to not depend on session
|
||||
if (!session?.factors?.user?.id) {
|
||||
const verifySuccessParams = new URLSearchParams({});
|
||||
|
||||
if (command.userId) {
|
||||
verifySuccessParams.set("userId", command.userId);
|
||||
}
|
||||
|
||||
if (
|
||||
("loginName" in command && command.loginName) ||
|
||||
user.preferredLoginName
|
||||
) {
|
||||
verifySuccessParams.set(
|
||||
"loginName",
|
||||
"loginName" in command && command.loginName
|
||||
? command.loginName
|
||||
: user.preferredLoginName,
|
||||
);
|
||||
}
|
||||
if (command.requestId) {
|
||||
verifySuccessParams.set("requestId", command.requestId);
|
||||
}
|
||||
if (command.organization) {
|
||||
verifySuccessParams.set("organization", command.organization);
|
||||
}
|
||||
|
||||
return { redirect: `/verify/success?${verifySuccessParams}` };
|
||||
}
|
||||
|
||||
const loginSettings = await getLoginSettings({
|
||||
serviceUrl,
|
||||
organization: user.details?.resourceOwner,
|
||||
});
|
||||
|
||||
// redirect to mfa factor if user has one, or redirect to set one up
|
||||
const mfaFactorCheck = await checkMFAFactors(
|
||||
serviceUrl,
|
||||
session,
|
||||
loginSettings,
|
||||
authMethodResponse.authMethodTypes,
|
||||
command.organization,
|
||||
command.requestId,
|
||||
);
|
||||
|
||||
if (mfaFactorCheck?.redirect) {
|
||||
return mfaFactorCheck;
|
||||
}
|
||||
|
||||
// login user if no additional steps are required
|
||||
if (command.requestId && session.id) {
|
||||
const nextUrl = await getNextUrl(
|
||||
{
|
||||
sessionId: session.id,
|
||||
requestId: command.requestId,
|
||||
organization:
|
||||
command.organization ?? session.factors?.user?.organizationId,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
|
||||
return { redirect: nextUrl };
|
||||
}
|
||||
|
||||
const url = await getNextUrl(
|
||||
{
|
||||
loginName: session.factors.user.loginName,
|
||||
organization: session.factors?.user?.organizationId,
|
||||
},
|
||||
loginSettings?.defaultRedirectUri,
|
||||
);
|
||||
|
||||
return { redirect: url };
|
||||
}
|
||||
|
||||
type resendVerifyEmailCommand = {
|
||||
userId: string;
|
||||
isInvite: boolean;
|
||||
requestId?: string;
|
||||
};
|
||||
|
||||
export async function resendVerification(command: resendVerifyEmailCommand) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
const host = _headers.get("host");
|
||||
|
||||
if (!host) {
|
||||
return { error: "No host found" };
|
||||
}
|
||||
|
||||
const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? "";
|
||||
|
||||
return command.isInvite
|
||||
? createInviteCode({
|
||||
serviceUrl,
|
||||
userId: command.userId,
|
||||
urlTemplate:
|
||||
`${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}&invite=true` +
|
||||
(command.requestId ? `&requestId=${command.requestId}` : ""),
|
||||
}).catch((error) => {
|
||||
if (error.code === 9) {
|
||||
return { error: "User is already verified!" };
|
||||
}
|
||||
return { error: "Could not resend invite" };
|
||||
})
|
||||
: zitadelSendEmailCode({
|
||||
userId: command.userId,
|
||||
serviceUrl,
|
||||
urlTemplate:
|
||||
`${host.includes("localhost") ? "http://" : "https://"}${host}${basePath}/verify?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}` +
|
||||
(command.requestId ? `&requestId=${command.requestId}` : ""),
|
||||
});
|
||||
}
|
||||
|
||||
type SendEmailCommand = {
|
||||
userId: string;
|
||||
urlTemplate: string;
|
||||
};
|
||||
|
||||
export async function sendEmailCode(command: SendEmailCommand) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
return zitadelSendEmailCode({
|
||||
serviceUrl,
|
||||
userId: command.userId,
|
||||
urlTemplate: command.urlTemplate,
|
||||
});
|
||||
}
|
||||
|
||||
export async function sendInviteEmailCode(command: SendEmailCommand) {
|
||||
const _headers = await headers();
|
||||
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
|
||||
|
||||
return createInviteCode({
|
||||
serviceUrl,
|
||||
userId: command.userId,
|
||||
urlTemplate: command.urlTemplate,
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user