document password pages, move redirects to sendPassword server action

This commit is contained in:
peintnermax
2024-10-17 10:06:17 +02:00
parent bc3e09ed0c
commit bfe3448f5a
7 changed files with 252 additions and 165 deletions

View File

@@ -24,6 +24,10 @@ This diagram shows the available pages and flows.
passkey --> B[signedin]
password -- hasMFA --> mfa
password -- allowPasskeys --> passkey-add
password -- reset --> password-set
email -- reset --> password-set
password -- userstate=initial --> password-change
mfa --> otp
otp --> B[signedin]
mfa--> u2f
@@ -103,10 +107,14 @@ Requests to the APIs made:
- `listAuthenticationMethodTypes`
- `getSession()`
- `updateSession()`
- `listUsers()`
- `getUserById()`
**MFA AVAILABLE:** After the password has been submitted, additional authentication methods are loaded.
If the user has set up an additional **single** second factor, it is redirected to add the next factor. Depending on the available method he is redirected to `/otp/time-based`,`/otp/sms?`, `/otp/email?` or `/u2f?`. If the user has multiple second factors, he is redirected to `/mfa` to select his preferred method to continue.
**NO MFA, USER STATE INITIAL** If the user has no MFA methods and is in an initial state, we redirect to `/password/change` where a new password can be set.
**NO MFA, FORCE MFA:** If no MFA method is available, and the settings force MFA, the user is sent to `/mfa/set` which prompts to setup a second factor.
**PROMPT PASSKEY** If the settings do not enforce MFA, we check if passkeys are allowed with `loginSettings?.passkeysType === PasskeysType.ALLOWED` and redirect the user to `/passkey/set` if no passkeys are setup. This step can be skipped.
@@ -115,6 +123,38 @@ If none of the previous conditions apply, we continue to sign in.
> NOTE: `listAuthenticationMethodTypes()` does not consider different domains for u2f methods or passkeys. The check whether a user should be redirected to one of the pages `/passkey` or `/u2f`, should be extended to use a domain filter (https://github.com/zitadel/zitadel/issues/8615)
### /password/change
This page allows to change the password. It is used after a user is in an initial state and is required to change the password, or it can be directly invoked with an active session.
<img src="./screenshots/password_change.png" alt="/password/change" width="400px" />
Requests to the APIs made:
- `getLoginSettings(org?)`
- `getPasswordComplexitySettings(user?)`
- `getBrandingSettings(org?)`
- `getSession()`
- `setPassword()`
> NOTE: The request to change the password is using the session of the user itself not the service user, therefore no code is required.
### /password/set
This page allows to set a password. It is used after a user has requested to reset the password on the `/password` page.
<img src="./screenshots/password_set.png" alt="/password/set" width="400px" />
Requests to the APIs made:
- `getLoginSettings(org?)`
- `getPasswordComplexitySettings(user?)`
- `getBrandingSettings(org?)`
- `getUserByID()`
- `setPassword()`
The page allows to enter a code or be invoked directly from a email link which prefills the code. The user can enter a new password and submit.
### /otp/[method]
This page shows a code field to check an otp method. The session of the user is then hydrated with the respective factor. Supported methods are `time-based`, `sms` and `email`.

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 150 KiB

View File

@@ -194,7 +194,7 @@ export function LoginOTP({
<Alert type={AlertType.INFO}>
<div className="flex flex-row">
<span className="flex-1 mr-auto text-left">
{t("noCodeReceived")}
{t("verify.noCodeReceived")}
</span>
<button
aria-label="Resend OTP Code"
@@ -212,7 +212,7 @@ export function LoginOTP({
});
}}
>
{t("resendCode")}
{t("verify.resendCode")}
</button>
</div>
</Alert>
@@ -244,7 +244,7 @@ export function LoginOTP({
})}
>
{loading && <Spinner className="h-5 w-5 mr-2" />}
{t("submit")}
{t("verify.submit")}
</Button>
</div>
</form>

View File

@@ -4,7 +4,6 @@ import { resetPassword, sendPassword } from "@/lib/server/password";
import { create } from "@zitadel/client";
import { ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { LoginSettings } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb";
import { AuthenticationMethodType } from "@zitadel/proto/zitadel/user/v2/user_service_pb";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { useState } from "react";
@@ -60,6 +59,7 @@ export function PasswordForm({
password: { password: values.password },
}),
authRequestId,
forceMfa: loginSettings?.forceMfa,
}).catch(() => {
setLoading(false);
setError("Could not verify password");
@@ -87,14 +87,16 @@ export function PasswordForm({
setError("Could not reset password");
});
setLoading(false);
if (response && "error" in response) {
setError(response.error);
return;
}
setInfo("Password was reset. Please check your email.");
setLoading(false);
const params = new URLSearchParams({
loginName: loginName,
});
@@ -110,141 +112,6 @@ export function PasswordForm({
return router.push("/password/set?" + params);
}
async function submitPasswordAndContinue(
value: Inputs,
): Promise<boolean | void> {
const submitted = await submitPassword(value);
setInfo("");
// if user has mfa -> /otp/[method] or /u2f
// if mfa is forced and user has no mfa -> /mfa/set
// if no passwordless -> /passkey/set
// exclude password and passwordless
if (
!submitted ||
!submitted.authMethods ||
!submitted.factors?.user?.loginName
) {
return;
}
const availableSecondFactors = submitted?.authMethods?.filter(
(m: AuthenticationMethodType) =>
m !== AuthenticationMethodType.PASSWORD &&
m !== AuthenticationMethodType.PASSKEY,
);
if (availableSecondFactors?.length == 1) {
const params = new URLSearchParams({
loginName: submitted.factors?.user.loginName,
});
if (authRequestId) {
params.append("authRequestId", authRequestId);
}
if (organization) {
params.append("organization", organization);
}
const factor = availableSecondFactors[0];
// if passwordless is other method, but user selected password as alternative, perform a login
if (factor === AuthenticationMethodType.TOTP) {
return router.push(`/otp/time-based?` + params);
} else if (factor === AuthenticationMethodType.OTP_SMS) {
return router.push(`/otp/sms?` + params);
} else if (factor === AuthenticationMethodType.OTP_EMAIL) {
return router.push(`/otp/email?` + params);
} else if (factor === AuthenticationMethodType.U2F) {
return router.push(`/u2f?` + params);
}
} else if (availableSecondFactors?.length >= 1) {
const params = new URLSearchParams({
loginName: submitted.factors.user.loginName,
});
if (authRequestId) {
params.append("authRequestId", authRequestId);
}
if (organization) {
params.append("organization", organization);
}
return router.push(`/mfa?` + params);
} else if (loginSettings?.forceMfa && !availableSecondFactors.length) {
const params = new URLSearchParams({
loginName: submitted.factors.user.loginName,
force: "true", // this defines if the mfa is forced in the settings
checkAfter: "true", // this defines if the check is directly made after the setup
});
if (authRequestId) {
params.append("authRequestId", authRequestId);
}
if (organization) {
params.append("organization", organization);
}
// TODO: provide a way to setup passkeys on mfa page?
return router.push(`/mfa/set?` + params);
}
// TODO: implement passkey setup
// else if (
// submitted.factors &&
// !submitted.factors.webAuthN && // if session was not verified with a passkey
// promptPasswordless && // if explicitly prompted due policy
// !isAlternative // escaped if password was used as an alternative method
// ) {
// const params = new URLSearchParams({
// loginName: submitted.factors.user.loginName,
// prompt: "true",
// });
// if (authRequestId) {
// params.append("authRequestId", authRequestId);
// }
// if (organization) {
// params.append("organization", organization);
// }
// return router.push(`/passkey/set?` + params);
// }
else if (authRequestId && submitted.sessionId) {
const params = new URLSearchParams({
sessionId: submitted.sessionId,
authRequest: authRequestId,
});
if (organization) {
params.append("organization", organization);
}
return router.push(`/login?` + params);
}
// without OIDC flow
const params = new URLSearchParams(
authRequestId
? {
loginName: submitted.factors.user.loginName,
authRequestId,
}
: {
loginName: submitted.factors.user.loginName,
},
);
if (organization) {
params.append("organization", organization);
}
return router.push(`/signedin?` + params);
}
return (
<form className="w-full">
<div className={`${error && "transform-gpu animate-shake"}`}>
@@ -295,7 +162,7 @@ export function PasswordForm({
className="self-end"
variant={ButtonVariants.Primary}
disabled={loading || !formState.isValid}
onClick={handleSubmit(submitPasswordAndContinue)}
onClick={handleSubmit(submitPassword)}
>
{loading && <Spinner className="h-5 w-5 mr-2" />}
{t("verify.submit")}

View File

@@ -6,9 +6,10 @@ import {
symbolValidator,
upperCaseValidator,
} from "@/helpers/validators";
import { changePassword } from "@/lib/server/password";
import { changePassword, sendPassword } from "@/lib/server/password";
import { create } from "@zitadel/client";
import { ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { PasswordComplexitySettings } from "@zitadel/proto/zitadel/settings/v2/password_settings_pb";
import { SetPasswordResponse } from "@zitadel/proto/zitadel/user/v2/user_service_pb";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { useState } from "react";
@@ -61,7 +62,7 @@ export function SetPasswordForm({
async function submitRegister(values: Inputs) {
setLoading(true);
const response = await changePassword({
const changeResponse = await changePassword({
userId: userId,
password: values.password,
code: values.code,
@@ -69,21 +70,17 @@ export function SetPasswordForm({
setError("Could not register user");
});
if (response && "error" in response) {
setError(response.error);
if (changeResponse && "error" in changeResponse) {
setError(changeResponse.error);
}
setLoading(false);
if (!response) {
if (!changeResponse) {
setError("Could not register user");
return;
}
const userResponse = response as SetPasswordResponse & {
sessionId: string;
};
const params = new URLSearchParams({});
if (loginName) {
@@ -93,22 +90,45 @@ export function SetPasswordForm({
params.append("organization", organization);
}
// skip verification for now as it is an app based flow
// return router.push(`/verify?` + params);
const passwordResponse = await sendPassword({
loginName,
organization,
checks: create(ChecksSchema, {
password: { password: values.password },
}),
authRequestId,
}).catch(() => {
setLoading(false);
setError("Could not verify password");
return;
});
// check for mfa force to continue with mfa setup
setLoading(false);
if (authRequestId && userResponse.sessionId) {
if (authRequestId) {
params.append("authRequest", authRequestId);
}
return router.push(`/login?` + params);
} else {
if (authRequestId) {
params.append("authRequestId", authRequestId);
}
return router.push(`/signedin?` + params);
if (
passwordResponse &&
"error" in passwordResponse &&
passwordResponse.error
) {
setError(passwordResponse.error);
}
// // skip verification for now as it is an app based flow
// // return router.push(`/verify?` + params);
// // check for mfa force to continue with mfa setup
// if (authRequestId && changeResponse.sessionId) {
// if (authRequestId) {
// params.append("authRequest", authRequestId);
// }
// return router.push(`/login?` + params);
// } else {
// if (authRequestId) {
// params.append("authRequestId", authRequestId);
// }
// return router.push(`/signedin?` + params);
// }
}
const { errors } = formState;

View File

@@ -16,6 +16,9 @@ import {
Checks,
ChecksSchema,
} from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { User, UserState } from "@zitadel/proto/zitadel/user/v2/user_pb";
import { AuthenticationMethodType } from "@zitadel/proto/zitadel/user/v2/user_service_pb";
import { redirect } from "next/navigation";
import { getSessionCookieByLoginName } from "../cookies";
type ResetPasswordCommand = {
@@ -46,6 +49,7 @@ export type UpdateSessionCommand = {
organization?: string;
checks: Checks;
authRequestId?: string;
forceMfa?: boolean;
};
export async function sendPassword(command: UpdateSessionCommand) {
@@ -57,13 +61,18 @@ export async function sendPassword(command: UpdateSessionCommand) {
});
let session;
let user: User;
if (!sessionCookie) {
const users = await listUsers({
loginName: command.loginName,
organizationId: command.organization,
});
console.log(users);
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 },
@@ -85,6 +94,18 @@ export async function sendPassword(command: UpdateSessionCommand) {
undefined,
command.authRequestId,
);
if (!session?.factors?.user?.id) {
return { error: "Could not create session for user" };
}
const userResponse = await getUserByID(session?.factors?.user?.id);
if (!userResponse.user) {
return { error: "Could not find user" };
}
user = userResponse.user;
}
if (!session?.factors?.user?.id || !sessionCookie) {
@@ -102,12 +123,151 @@ export async function sendPassword(command: UpdateSessionCommand) {
}
}
return {
const submitted = {
sessionId: session.id,
factors: session.factors,
challenges: session.challenges,
authMethods,
userState: user.state,
};
if (
!submitted ||
!submitted.authMethods ||
!submitted.factors?.user?.loginName
) {
return { error: "Could not verify password!" };
}
const availableSecondFactors = submitted?.authMethods?.filter(
(m: AuthenticationMethodType) =>
m !== AuthenticationMethodType.PASSWORD &&
m !== AuthenticationMethodType.PASSKEY,
);
if (availableSecondFactors?.length == 1) {
const params = new URLSearchParams({
loginName: submitted.factors?.user.loginName,
});
if (command.authRequestId) {
params.append("authRequestId", command.authRequestId);
}
if (command.organization) {
params.append("organization", command.organization);
}
const factor = availableSecondFactors[0];
// if passwordless is other method, but user selected password as alternative, perform a login
if (factor === AuthenticationMethodType.TOTP) {
return redirect(`/otp/time-based?` + params);
} else if (factor === AuthenticationMethodType.OTP_SMS) {
return redirect(`/otp/sms?` + params);
} else if (factor === AuthenticationMethodType.OTP_EMAIL) {
return redirect(`/otp/email?` + params);
} else if (factor === AuthenticationMethodType.U2F) {
return redirect(`/u2f?` + params);
}
} else if (availableSecondFactors?.length >= 1) {
const params = new URLSearchParams({
loginName: submitted.factors.user.loginName,
});
if (command.authRequestId) {
params.append("authRequestId", command.authRequestId);
}
if (command.organization) {
params.append("organization", command.organization);
}
return redirect(`/mfa?` + params);
} else if (submitted.userState === UserState.INITIAL) {
const params = new URLSearchParams({
loginName: submitted.factors.user.loginName,
});
if (command.authRequestId) {
params.append("authRequestId", command.authRequestId);
}
if (command.organization) {
params.append("organization", command.organization);
}
return redirect(`/password/change?` + params);
} else if (command.forceMfa && !availableSecondFactors.length) {
const params = new URLSearchParams({
loginName: submitted.factors.user.loginName,
force: "true", // this defines if the mfa is forced in the settings
checkAfter: "true", // this defines if the check is directly made after the setup
});
if (command.authRequestId) {
params.append("authRequestId", command.authRequestId);
}
if (command.organization) {
params.append("organization", command.organization);
}
// TODO: provide a way to setup passkeys on mfa page?
return redirect(`/mfa/set?` + params);
}
// TODO: implement passkey setup
// else if (
// submitted.factors &&
// !submitted.factors.webAuthN && // if session was not verified with a passkey
// promptPasswordless && // if explicitly prompted due policy
// !isAlternative // escaped if password was used as an alternative method
// ) {
// const params = new URLSearchParams({
// loginName: submitted.factors.user.loginName,
// prompt: "true",
// });
// if (authRequestId) {
// params.append("authRequestId", authRequestId);
// }
// if (organization) {
// params.append("organization", organization);
// }
// return router.push(`/passkey/set?` + params);
// }
else if (command.authRequestId && submitted.sessionId) {
const params = new URLSearchParams({
sessionId: submitted.sessionId,
authRequest: command.authRequestId,
});
if (command.organization) {
params.append("organization", command.organization);
}
return redirect(`/login?` + params);
}
// without OIDC flow
const params = new URLSearchParams(
command.authRequestId
? {
loginName: submitted.factors.user.loginName,
authRequestId: command.authRequestId,
}
: {
loginName: submitted.factors.user.loginName,
},
);
if (command.organization) {
params.append("organization", command.organization);
}
return redirect(`/signedin?` + params);
}
export async function changePassword(command: {