Merge branch 'main' into main

This commit is contained in:
Stefan Benz
2024-12-05 11:29:34 +01:00
committed by GitHub
17 changed files with 359 additions and 242 deletions

View File

@@ -49,6 +49,7 @@ describe("login", () => {
data: {
settings: {
passkeysType: 1,
allowUsernamePassword: true,
},
},
});

View File

@@ -389,7 +389,8 @@ In future, self service options to jump to are shown below, like:
## Currently NOT Supported
- loginSettings.disableLoginWithEmail
- loginSettings.disableLoginWithPhone
- loginSettings.allowExternalIdp - this will be deprecated with the new login as it can be determined by the available IDPs
- loginSettings.forceMfaLocalOnly
Timebased features like the multifactor init prompt or password expiry, are not supported due to a current limitation in the API. Lockout settings which keeps track of the password retries, will also be implemented in a later stage.
- Lockout Settings
- Password Expiry Settings
- Login Settings: multifactor init prompt

View File

@@ -74,6 +74,10 @@ export default async function Page(props: {
});
}
if (!sessionWithData) {
return <Alert>{tError("unknownContext")}</Alert>;
}
const branding = await getBrandingSettings(
sessionWithData.factors?.user?.organizationId,
);
@@ -82,22 +86,34 @@ export default async function Page(props: {
sessionWithData.factors?.user?.organizationId,
);
/* - TODO: Implement after https://github.com/zitadel/zitadel/issues/8981 */
// const identityProviders = await getActiveIdentityProviders(
// sessionWithData.factors?.user?.organizationId,
// ).then((resp) => {
// return resp.identityProviders;
// });
const params = new URLSearchParams({
initial: "true", // defines that a code is not required and is therefore not shown in the UI
});
if (loginName) {
params.set("loginName", loginName);
if (sessionWithData.factors?.user?.loginName) {
params.set("loginName", sessionWithData.factors?.user?.loginName);
}
if (organization) {
params.set("organization", organization);
if (sessionWithData.factors?.user?.organizationId) {
params.set("organization", sessionWithData.factors?.user?.organizationId);
}
if (authRequestId) {
params.set("authRequestId", authRequestId);
}
const host = process.env.VERCEL_URL
? `https://${process.env.VERCEL_URL}`
: "http://localhost:3000";
return (
<DynamicTheme branding={branding}>
<div className="flex flex-col items-center space-y-4">
@@ -105,18 +121,14 @@ export default async function Page(props: {
<p className="ztdl-p">{t("description")}</p>
{sessionWithData && (
<UserAvatar
loginName={loginName ?? sessionWithData.factors?.user?.loginName}
displayName={sessionWithData.factors?.user?.displayName}
showDropdown
searchParams={searchParams}
></UserAvatar>
)}
<UserAvatar
loginName={sessionWithData.factors?.user?.loginName}
displayName={sessionWithData.factors?.user?.displayName}
showDropdown
searchParams={searchParams}
></UserAvatar>
{!(loginName || sessionId) && <Alert>{tError("unknownContext")}</Alert>}
{loginSettings && sessionWithData && (
{loginSettings && (
<ChooseAuthenticatorToSetup
authMethods={sessionWithData.authMethods}
loginSettings={loginSettings}
@@ -124,6 +136,22 @@ export default async function Page(props: {
></ChooseAuthenticatorToSetup>
)}
{/* - TODO: Implement after https://github.com/zitadel/zitadel/issues/8981 */}
{/* <p className="ztdl-p text-center">
or sign in with an Identity Provider
</p>
{loginSettings?.allowExternalIdp && identityProviders && (
<SignInWithIdp
host={host}
identityProviders={identityProviders}
authRequestId={authRequestId}
organization={sessionWithData.factors?.user?.organizationId}
linkOnly={true} // tell the callback function to just link the IDP and not login, to get an error when user is already available
></SignInWithIdp>
)} */}
<div className="mt-8 flex w-full flex-row items-center">
<BackButton />
<span className="flex-grow"></span>

View File

@@ -37,7 +37,7 @@ export default async function Page(props: {
const searchParams = await props.searchParams;
const locale = getLocale();
const t = await getTranslations({ locale, namespace: "idp" });
const { id, token, authRequestId, organization } = searchParams;
const { id, token, authRequestId, organization, link } = searchParams;
const { provider } = params;
const branding = await getBrandingSettings(organization);
@@ -50,7 +50,8 @@ export default async function Page(props: {
const { idpInformation, userId } = intent;
if (userId) {
// sign in user. If user should be linked continue
if (userId && !link) {
// TODO: update user if idp.options.isAutoUpdate is true
return (

View File

@@ -24,10 +24,6 @@ export default async function Page(props: {
const identityProviders = await getIdentityProviders(organization);
const host = process.env.VERCEL_URL
? `https://${process.env.VERCEL_URL}`
: "http://localhost:3000";
const branding = await getBrandingSettings(organization);
return (
@@ -38,7 +34,6 @@ export default async function Page(props: {
{identityProviders && (
<SignInWithIdp
host={host}
identityProviders={identityProviders}
authRequestId={authRequestId}
organization={organization}

View File

@@ -2,23 +2,14 @@ import { DynamicTheme } from "@/components/dynamic-theme";
import { SignInWithIdp } from "@/components/sign-in-with-idp";
import { UsernameForm } from "@/components/username-form";
import {
getActiveIdentityProviders,
getBrandingSettings,
getDefaultOrg,
getLoginSettings,
settingsService,
} from "@/lib/zitadel";
import { makeReqCtx } from "@zitadel/client/v2";
import { Organization } from "@zitadel/proto/zitadel/org/v2/org_pb";
import { getLocale, getTranslations } from "next-intl/server";
function getIdentityProviders(orgId?: string) {
return settingsService
.getActiveIdentityProviders({ ctx: makeReqCtx(orgId) }, {})
.then((resp) => {
return resp.identityProviders;
});
}
export default async function Page(props: {
searchParams: Promise<Record<string | number | symbol, string | undefined>>;
}) {
@@ -39,17 +30,15 @@ export default async function Page(props: {
}
}
const host = process.env.VERCEL_URL
? `https://${process.env.VERCEL_URL}`
: "http://localhost:3000";
const loginSettings = await getLoginSettings(
organization ?? defaultOrganization,
);
const identityProviders = await getIdentityProviders(
const identityProviders = await getActiveIdentityProviders(
organization ?? defaultOrganization,
);
).then((resp) => {
return resp.identityProviders;
});
const branding = await getBrandingSettings(
organization ?? defaultOrganization,
@@ -68,9 +57,8 @@ export default async function Page(props: {
submit={submit}
allowRegister={!!loginSettings?.allowRegister}
>
{identityProviders && process.env.ZITADEL_API_URL && (
{identityProviders && (
<SignInWithIdp
host={host}
identityProviders={identityProviders}
authRequestId={authRequestId}
organization={organization ?? defaultOrganization} // use the organization from the searchParams here otherwise fallback to the default organization

View File

@@ -5,6 +5,7 @@ import { UserAvatar } from "@/components/user-avatar";
import { loadMostRecentSession } from "@/lib/session";
import { getBrandingSettings, getLoginSettings } from "@/lib/zitadel";
import { getLocale, getTranslations } from "next-intl/server";
import { headers } from "next/headers";
export default async function Page(props: {
searchParams: Promise<Record<string | number | symbol, string | undefined>>;
@@ -30,6 +31,8 @@ export default async function Page(props: {
const loginSettings = await getLoginSettings(organization);
const host = (await headers()).get("host");
return (
<DynamicTheme branding={branding}>
<div className="flex flex-col items-center space-y-4">
@@ -67,6 +70,8 @@ export default async function Page(props: {
organization={organization}
method={method}
loginSettings={loginSettings}
host={host}
code={code}
></LoginOTP>
)}
</div>

View File

@@ -174,7 +174,7 @@ export async function GET(request: NextRequest) {
const idp = identityProviders.find((idp) => idp.id === idpId);
if (idp) {
const host = request.nextUrl.origin;
const origin = request.nextUrl.origin;
const identityProviderType = identityProviders[0].type;
let provider = idpTypeToSlug(identityProviderType);
@@ -193,10 +193,10 @@ export async function GET(request: NextRequest) {
idpId,
urls: {
successUrl:
`${host}/idp/${provider}/success?` +
`${origin}/idp/${provider}/success?` +
new URLSearchParams(params),
failureUrl:
`${host}/idp/${provider}/failure?` +
`${origin}/idp/${provider}/failure?` +
new URLSearchParams(params),
},
}).then((resp) => {

View File

@@ -25,6 +25,7 @@ type Props = {
method: string;
code?: string;
loginSettings?: LoginSettings;
host: string | null;
};
type Inputs = {
@@ -39,6 +40,7 @@ export function LoginOTP({
method,
code,
loginSettings,
host,
}: Props) {
const t = useTranslations("otp");
@@ -76,7 +78,18 @@ export function LoginOTP({
if (method === "email") {
challenges = create(RequestChallengesSchema, {
otpEmail: { deliveryType: { case: "sendCode", value: {} } },
otpEmail: {
deliveryType: {
case: "sendCode",
value: host
? {
urlTemplate:
`${host.includes("localhost") ? "http://" : "https://"}${host}/otp/method=${method}?code={{.Code}}&userId={{.UserID}}&sessionId={{.SessionID}}&organization={{.OrgID}}` +
(authRequestId ? `&authRequestId=${authRequestId}` : ""),
}
: {},
},
},
});
}

View File

@@ -59,7 +59,6 @@ export function PasswordForm({
password: { password: values.password },
}),
authRequestId,
forceMfa: loginSettings?.forceMfa,
})
.catch(() => {
setError("Could not verify password");
@@ -87,6 +86,7 @@ export function PasswordForm({
const response = await resetPassword({
loginName,
organization,
authRequestId,
})
.catch(() => {
setError("Could not reset password");

View File

@@ -16,12 +16,14 @@ export function isSessionValid(session: Partial<Session>): {
} {
const validPassword = session?.factors?.password?.verifiedAt;
const validPasskey = session?.factors?.webAuthN?.verifiedAt;
const validIDP = session?.factors?.intent?.verifiedAt;
const stillValid = session.expirationDate
? timestampDate(session.expirationDate) > new Date()
: true;
const verifiedAt = validPassword || validPasskey;
const valid = !!((validPassword || validPasskey) && stillValid);
const verifiedAt = validPassword || validPasskey || validIDP;
const valid = !!((validPassword || validPasskey || validIDP) && stillValid);
return { valid, verifiedAt };
}
@@ -102,15 +104,21 @@ export function SessionItem({
/>
</div>
<div className="flex flex-col overflow-hidden">
<div className="flex flex-col items-start overflow-hidden">
<span className="">{session.factors?.user?.displayName}</span>
<span className="text-xs opacity-80 text-ellipsis">
{session.factors?.user?.loginName}
</span>
{valid && (
{valid ? (
<span className="text-xs opacity-80 text-ellipsis">
{verifiedAt && moment(timestampDate(verifiedAt)).fromNow()}
</span>
) : (
<span className="text-xs opacity-80 text-ellipsis">
expired{" "}
{session.expirationDate &&
moment(timestampDate(session.expirationDate)).fromNow()}
</span>
)}
</div>

View File

@@ -18,17 +18,17 @@ import { SignInWithGoogle } from "./idps/sign-in-with-google";
export interface SignInWithIDPProps {
children?: ReactNode;
host: string;
identityProviders: IdentityProvider[];
authRequestId?: string;
organization?: string;
linkOnly?: boolean;
}
export function SignInWithIdp({
host,
identityProviders,
authRequestId,
organization,
linkOnly,
}: SignInWithIDPProps) {
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<string>("");
@@ -39,6 +39,10 @@ export function SignInWithIdp({
const params = new URLSearchParams();
if (linkOnly) {
params.set("link", "true");
}
if (authRequestId) {
params.set("authRequestId", authRequestId);
}
@@ -49,10 +53,8 @@ export function SignInWithIdp({
const response = await startIDPFlow({
idpId,
successUrl:
`${host}/idp/${provider}/success?` + new URLSearchParams(params),
failureUrl:
`${host}/idp/${provider}/failure?` + new URLSearchParams(params),
successUrl: `/idp/${provider}/success?` + new URLSearchParams(params),
failureUrl: `/idp/${provider}/failure?` + new URLSearchParams(params),
})
.catch(() => {
setError("Could not start IDP flow");
@@ -62,6 +64,11 @@ export function SignInWithIdp({
setLoading(false);
});
if (response && "error" in response && response?.error) {
setError(response.error);
return;
}
if (response && "redirect" in response && response?.redirect) {
return router.push(response.redirect);
}
@@ -70,121 +77,136 @@ export function SignInWithIdp({
return (
<div className="flex flex-col w-full space-y-2 text-sm">
{identityProviders &&
identityProviders.map((idp, i) => {
switch (idp.type) {
case IdentityProviderType.APPLE:
return (
<SignInWithApple
key={`idp-${i}`}
name={idp.name}
onClick={() =>
startFlow(idp.id, idpTypeToSlug(IdentityProviderType.APPLE))
}
></SignInWithApple>
);
case IdentityProviderType.OAUTH:
return (
<SignInWithGeneric
key={`idp-${i}`}
name={idp.name}
onClick={() =>
startFlow(idp.id, idpTypeToSlug(IdentityProviderType.OAUTH))
}
></SignInWithGeneric>
);
case IdentityProviderType.OIDC:
return (
<SignInWithGeneric
key={`idp-${i}`}
name={idp.name}
onClick={() =>
startFlow(idp.id, idpTypeToSlug(IdentityProviderType.OIDC))
}
></SignInWithGeneric>
);
case IdentityProviderType.GITHUB:
return (
<SignInWithGithub
key={`idp-${i}`}
name={idp.name}
onClick={() =>
startFlow(
idp.id,
idpTypeToSlug(IdentityProviderType.GITHUB),
)
}
></SignInWithGithub>
);
case IdentityProviderType.GITHUB_ES:
return (
<SignInWithGithub
key={`idp-${i}`}
name={idp.name}
onClick={() =>
startFlow(
idp.id,
idpTypeToSlug(IdentityProviderType.GITHUB_ES),
)
}
></SignInWithGithub>
);
case IdentityProviderType.AZURE_AD:
return (
<SignInWithAzureAd
key={`idp-${i}`}
name={idp.name}
onClick={() =>
startFlow(
idp.id,
idpTypeToSlug(IdentityProviderType.AZURE_AD),
)
}
></SignInWithAzureAd>
);
case IdentityProviderType.GOOGLE:
return (
<SignInWithGoogle
key={`idp-${i}`}
e2e="google"
name={idp.name}
onClick={() =>
startFlow(
idp.id,
idpTypeToSlug(IdentityProviderType.GOOGLE),
)
}
></SignInWithGoogle>
);
case IdentityProviderType.GITLAB:
return (
<SignInWithGitlab
key={`idp-${i}`}
name={idp.name}
onClick={() =>
startFlow(
idp.id,
idpTypeToSlug(IdentityProviderType.GITLAB),
)
}
></SignInWithGitlab>
);
case IdentityProviderType.GITLAB_SELF_HOSTED:
return (
<SignInWithGitlab
key={`idp-${i}`}
name={idp.name}
onClick={() =>
startFlow(
idp.id,
idpTypeToSlug(IdentityProviderType.GITLAB_SELF_HOSTED),
)
}
></SignInWithGitlab>
);
default:
return null;
}
})}
identityProviders
/* - TODO: Implement after https://github.com/zitadel/zitadel/issues/8981 */
// .filter((idp) =>
// linkOnly ? idp.config?.options.isLinkingAllowed : true,
// )
.map((idp, i) => {
switch (idp.type) {
case IdentityProviderType.APPLE:
return (
<SignInWithApple
key={`idp-${i}`}
name={idp.name}
onClick={() =>
startFlow(
idp.id,
idpTypeToSlug(IdentityProviderType.APPLE),
)
}
></SignInWithApple>
);
case IdentityProviderType.OAUTH:
return (
<SignInWithGeneric
key={`idp-${i}`}
name={idp.name}
onClick={() =>
startFlow(
idp.id,
idpTypeToSlug(IdentityProviderType.OAUTH),
)
}
></SignInWithGeneric>
);
case IdentityProviderType.OIDC:
return (
<SignInWithGeneric
key={`idp-${i}`}
name={idp.name}
onClick={() =>
startFlow(
idp.id,
idpTypeToSlug(IdentityProviderType.OIDC),
)
}
></SignInWithGeneric>
);
case IdentityProviderType.GITHUB:
return (
<SignInWithGithub
key={`idp-${i}`}
name={idp.name}
onClick={() =>
startFlow(
idp.id,
idpTypeToSlug(IdentityProviderType.GITHUB),
)
}
></SignInWithGithub>
);
case IdentityProviderType.GITHUB_ES:
return (
<SignInWithGithub
key={`idp-${i}`}
name={idp.name}
onClick={() =>
startFlow(
idp.id,
idpTypeToSlug(IdentityProviderType.GITHUB_ES),
)
}
></SignInWithGithub>
);
case IdentityProviderType.AZURE_AD:
return (
<SignInWithAzureAd
key={`idp-${i}`}
name={idp.name}
onClick={() =>
startFlow(
idp.id,
idpTypeToSlug(IdentityProviderType.AZURE_AD),
)
}
></SignInWithAzureAd>
);
case IdentityProviderType.GOOGLE:
return (
<SignInWithGoogle
key={`idp-${i}`}
e2e="google"
name={idp.name}
onClick={() =>
startFlow(
idp.id,
idpTypeToSlug(IdentityProviderType.GOOGLE),
)
}
></SignInWithGoogle>
);
case IdentityProviderType.GITLAB:
return (
<SignInWithGitlab
key={`idp-${i}`}
name={idp.name}
onClick={() =>
startFlow(
idp.id,
idpTypeToSlug(IdentityProviderType.GITLAB),
)
}
></SignInWithGitlab>
);
case IdentityProviderType.GITLAB_SELF_HOSTED:
return (
<SignInWithGitlab
key={`idp-${i}`}
name={idp.name}
onClick={() =>
startFlow(
idp.id,
idpTypeToSlug(IdentityProviderType.GITLAB_SELF_HOSTED),
)
}
></SignInWithGitlab>
);
default:
return null;
}
})}
{error && (
<div className="py-4">
<Alert>{error}</Alert>

View File

@@ -15,24 +15,29 @@ export async function getNextUrl(
defaultRedirectUri?: string,
): Promise<string> {
if ("sessionId" in command && "authRequestId" in command) {
const url =
`/login?` +
new URLSearchParams({
sessionId: command.sessionId,
authRequest: command.authRequestId,
});
return url;
const params = new URLSearchParams({
sessionId: command.sessionId,
authRequest: command.authRequestId,
});
if (command.organization) {
params.append("organization", command.organization);
}
return `/login?` + params;
}
if (defaultRedirectUri) {
return defaultRedirectUri;
}
const signedInUrl =
`/signedin?` +
new URLSearchParams({
loginName: command.loginName,
});
const params = new URLSearchParams({
loginName: command.loginName,
});
return signedInUrl;
if (command.organization) {
params.append("organization", command.organization);
}
return `/signedin?` + params;
}

View File

@@ -1,6 +1,7 @@
"use server";
import { startIdentityProviderFlow } from "@/lib/zitadel";
import { headers } from "next/headers";
export type StartIDPFlowCommand = {
idpId: string;
@@ -9,11 +10,17 @@ export type StartIDPFlowCommand = {
};
export async function startIDPFlow(command: StartIDPFlowCommand) {
const host = (await headers()).get("host");
if (!host) {
return { error: "Could not get host" };
}
return startIdentityProviderFlow({
idpId: command.idpId,
urls: {
successUrl: command.successUrl,
failureUrl: command.failureUrl,
successUrl: `${host.includes("localhost") ? "http://" : "https://"}${host}${command.successUrl}`,
failureUrl: `${host.includes("localhost") ? "http://" : "https://"}${host}${command.failureUrl}`,
},
}).then((response) => {
if (

View File

@@ -2,11 +2,12 @@
import { create } from "@zitadel/client";
import { ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { UserState } from "@zitadel/proto/zitadel/user/v2/user_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 {
getActiveIdentityProviders,
getIDPByID,
@@ -35,6 +36,15 @@ export async function sendLoginname(command: SendLoginnameCommand) {
const loginSettings = await getLoginSettings(command.organization);
const potentialUsers = users.result.filter((u) => {
const human = u.type.case === "human" ? u.type.value : undefined;
return loginSettings?.disableLoginWithEmail
? human?.email?.isVerified && human?.email?.email !== command.loginName
: loginSettings?.disableLoginWithPhone
? human?.phone?.isVerified && human?.phone?.phone !== command.loginName
: true;
});
const redirectUserToSingleIDPIfAvailable = async () => {
const identityProviders = await getActiveIdentityProviders(
command.organization,
@@ -44,6 +54,11 @@ export async function sendLoginname(command: SendLoginnameCommand) {
if (identityProviders.length === 1) {
const host = (await headers()).get("host");
if (!host) {
return { error: "Could not get host" };
}
const identityProviderType = identityProviders[0].type;
const provider = idpTypeToSlug(identityProviderType);
@@ -62,9 +77,11 @@ export async function sendLoginname(command: SendLoginnameCommand) {
idpId: identityProviders[0].id,
urls: {
successUrl:
`${host}/idp/${provider}/success?` + new URLSearchParams(params),
`${host.includes("localhost") ? "http://" : "https://"}${host}/idp/${provider}/success?` +
new URLSearchParams(params),
failureUrl:
`${host}/idp/${provider}/failure?` + new URLSearchParams(params),
`${host.includes("localhost") ? "http://" : "https://"}${host}/idp/${provider}/failure?` +
new URLSearchParams(params),
},
});
@@ -81,9 +98,15 @@ export async function sendLoginname(command: SendLoginnameCommand) {
if (identityProviders.length === 1) {
const host = (await headers()).get("host");
if (!host) {
return { error: "Could not get host" };
}
const identityProviderId = identityProviders[0].idpId;
const idp = await getIDPByID(identityProviderId);
const idpType = idp?.type;
if (!idp || !idpType) {
@@ -107,9 +130,11 @@ export async function sendLoginname(command: SendLoginnameCommand) {
idpId: idp.id,
urls: {
successUrl:
`${host}/idp/${provider}/success?` + new URLSearchParams(params),
`${host.includes("localhost") ? "http://" : "https://"}${host}/idp/${provider}/success?` +
new URLSearchParams(params),
failureUrl:
`${host}/idp/${provider}/failure?` + new URLSearchParams(params),
`${host.includes("localhost") ? "http://" : "https://"}${host}/idp/${provider}/failure?` +
new URLSearchParams(params),
},
});
@@ -119,8 +144,8 @@ export async function sendLoginname(command: SendLoginnameCommand) {
}
};
if (users.details?.totalResult == BigInt(1) && users.result[0].userId) {
const userId = users.result[0].userId;
if (potentialUsers.length == 1 && potentialUsers[0].userId) {
const userId = potentialUsers[0].userId;
const checks = create(ChecksSchema, {
user: { search: { case: "userId", value: userId } },
@@ -136,24 +161,9 @@ export async function sendLoginname(command: SendLoginnameCommand) {
return { error: "Could not create session for user" };
}
if (users.result[0].state === UserState.INITIAL) {
const params = new URLSearchParams({
loginName: session.factors?.user?.loginName,
initial: "true", // this does not require a code to be set
});
if (command.organization || session.factors?.user?.organizationId) {
params.append(
"organization",
command.organization ?? session.factors?.user?.organizationId,
);
}
if (command.authRequestId) {
params.append("authRequestid", command.authRequestId);
}
return { redirect: "/password/set?" + params };
// TODO: check if handling of userstate INITIAL is needed
if (potentialUsers[0].state === UserState.INITIAL) {
return { error: "Initial User not supported" };
}
const methods = await listAuthenticationMethodTypes(
@@ -162,9 +172,9 @@ export async function sendLoginname(command: SendLoginnameCommand) {
if (!methods.authMethodTypes || !methods.authMethodTypes.length) {
if (
users.result[0].type.case === "human" &&
users.result[0].type.value.email &&
!users.result[0].type.value.email.isVerified
potentialUsers[0].type.case === "human" &&
potentialUsers[0].type.value.email &&
!potentialUsers[0].type.value.email.isVerified
) {
const paramsVerify = new URLSearchParams({
loginName: session.factors?.user?.loginName,
@@ -209,6 +219,13 @@ export async function sendLoginname(command: SendLoginnameCommand) {
const method = methods.authMethodTypes[0];
switch (method) {
case AuthenticationMethodType.PASSWORD: // user has only password as auth method
if (!loginSettings?.allowUsernamePassword) {
return {
error:
"Username Password not allowed! Contact your administrator for more information.",
};
}
const paramsPassword: any = {
loginName: session.factors?.user?.loginName,
};
@@ -229,6 +246,13 @@ export async function sendLoginname(command: SendLoginnameCommand) {
};
case AuthenticationMethodType.PASSKEY: // AuthenticationMethodType.AUTHENTICATION_METHOD_TYPE_PASSKEY
if (loginSettings?.passkeysType === PasskeysType.NOT_ALLOWED) {
return {
error:
"Passkeys not allowed! Contact your administrator for more information.",
};
}
const paramsPasskey: any = { loginName: command.loginName };
if (command.authRequestId) {
paramsPasskey.authRequestId = command.authRequestId;
@@ -262,7 +286,7 @@ export async function sendLoginname(command: SendLoginnameCommand) {
} else if (
methods.authMethodTypes.includes(AuthenticationMethodType.IDP)
) {
await redirectUserToIDP(userId);
return redirectUserToIDP(userId);
} else if (
methods.authMethodTypes.includes(AuthenticationMethodType.PASSWORD)
) {
@@ -288,8 +312,10 @@ export async function sendLoginname(command: SendLoginnameCommand) {
// user not found, check if register is enabled on organization
if (loginSettings?.allowRegister && !loginSettings?.allowUsernamePassword) {
// TODO: do we need to handle login hints for IDPs here?
await redirectUserToSingleIDPIfAvailable();
const resp = await redirectUserToSingleIDPIfAvailable();
if (resp) {
return resp;
}
return { error: "Could not find user" };
} else if (
loginSettings?.allowRegister &&

View File

@@ -27,6 +27,7 @@ import { getSessionCookieByLoginName } from "../cookies";
type ResetPasswordCommand = {
loginName: string;
organization?: string;
authRequestId?: string;
};
export async function resetPassword(command: ResetPasswordCommand) {
@@ -46,7 +47,7 @@ export async function resetPassword(command: ResetPasswordCommand) {
}
const userId = users.result[0].userId;
return passwordReset(userId, host);
return passwordReset(userId, host, command.authRequestId);
}
export type UpdateSessionCommand = {
@@ -54,7 +55,6 @@ export type UpdateSessionCommand = {
organization?: string;
checks: Checks;
authRequestId?: string;
forceMfa?: boolean;
};
export async function sendPassword(command: UpdateSessionCommand) {
@@ -148,6 +148,27 @@ export async function sendPassword(command: UpdateSessionCommand) {
m !== AuthenticationMethodType.PASSKEY,
);
const humanUser = user.type.case === "human" ? user.type.value : undefined;
if (
availableSecondFactors?.length == 0 &&
humanUser?.passwordChangeRequired
) {
const params = new URLSearchParams({
loginName: session.factors?.user?.loginName,
});
if (command.organization || session.factors?.user?.organizationId) {
params.append("organization", session.factors?.user?.organizationId);
}
if (command.authRequestId) {
params.append("authRequestId", command.authRequestId);
}
return { redirect: "/password/change?" + params };
}
if (availableSecondFactors?.length == 1) {
const params = new URLSearchParams({
loginName: session.factors?.user.loginName,
@@ -192,24 +213,14 @@ export async function sendPassword(command: UpdateSessionCommand) {
}
return { redirect: `/mfa?` + params };
} else if (user.state === UserState.INITIAL) {
const params = new URLSearchParams({
loginName: session.factors.user.loginName,
});
if (command.authRequestId) {
params.append("authRequestId", command.authRequestId);
}
if (command.organization || session.factors?.user?.organizationId) {
params.append(
"organization",
command.organization ?? session.factors?.user?.organizationId,
);
}
return { redirect: `/password/change?` + params };
} else if (command.forceMfa && !availableSecondFactors.length) {
}
// TODO: check if handling of userstate INITIAL is needed
else if (user.state === UserState.INITIAL) {
return { error: "Initial User not supported" };
} else if (
(loginSettings?.forceMfa || loginSettings?.forceMfaLocalOnly) &&
!availableSecondFactors.length
) {
const params = new URLSearchParams({
loginName: session.factors.user.loginName,
force: "true", // this defines if the mfa is forced in the settings

View File

@@ -504,7 +504,11 @@ export function createUser(
* @param userId the id of the user where the email should be set
* @returns the newly set email
*/
export async function passwordReset(userId: string, host: string | null) {
export async function passwordReset(
userId: string,
host: string | null,
authRequestId?: string,
) {
let medium = create(SendPasswordResetLinkSchema, {
notificationType: NotificationType.Email,
});
@@ -512,7 +516,9 @@ export async function passwordReset(userId: string, host: string | null) {
if (host) {
medium = {
...medium,
urlTemplate: `${host.includes("localhost") ? "http://" : "https://"}${host}/password/set?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}`,
urlTemplate:
`${host.includes("localhost") ? "http://" : "https://"}${host}/password/set?code={{.Code}}&userId={{.UserID}}&organization={{.OrgID}}` +
(authRequestId ? `&authRequestId=${authRequestId}` : ""),
};
}