create session directly after addhuman

This commit is contained in:
peintnermax
2024-04-01 16:25:21 +02:00
parent d193cadbc6
commit d8611ab070
4 changed files with 25 additions and 293 deletions

View File

@@ -34,6 +34,7 @@ export async function POST(request: NextRequest) {
return NextResponse.json({
userId: user.userId,
sessionId: session.id,
factors: session.factors,
});
});
})

View File

@@ -1,218 +0,0 @@
"use client";
import {
LegalAndSupportSettings,
PasswordComplexitySettings,
} from "@zitadel/server";
import PasswordComplexity from "./PasswordComplexity";
import { useState } from "react";
import { Button, ButtonVariants } from "./Button";
import { TextInput } from "./Input";
import { PrivacyPolicyCheckboxes } from "./PrivacyPolicyCheckboxes";
import { FieldValues, useForm } from "react-hook-form";
import {
lowerCaseValidator,
numberValidator,
symbolValidator,
upperCaseValidator,
} from "#/utils/validators";
import { useRouter } from "next/navigation";
import { Spinner } from "./Spinner";
import { AuthRequest } from "@zitadel/server";
type Inputs =
| {
firstname: string;
lastname: string;
email: string;
password: string;
confirmPassword: string;
}
| FieldValues;
type Props = {
legal: LegalAndSupportSettings;
passwordComplexitySettings: PasswordComplexitySettings;
organization?: string;
authRequestId?: string;
};
export default function RegisterForm({
legal,
passwordComplexitySettings,
organization,
authRequestId,
}: Props) {
const { register, handleSubmit, watch, formState } = useForm<Inputs>({
mode: "onBlur",
});
const [loading, setLoading] = useState<boolean>(false);
const router = useRouter();
async function submitRegister(values: Inputs) {
setLoading(true);
const res = await fetch("/api/registeruser", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: values.email,
password: values.password,
firstName: values.firstname,
lastName: values.lastname,
organization: organization,
}),
});
if (!res.ok) {
setLoading(false);
throw new Error("Failed to register user");
}
setLoading(false);
return res.json();
}
function submitAndLink(value: Inputs): Promise<boolean | void> {
return submitRegister(value).then((session) => {
const params: any = { userId: session.userId };
if (organization) {
params.organization = organization;
}
if (authRequestId) {
params.authRequestId = authRequestId;
}
if (session && session.sessionId) {
params.sessionId = session.sessionId;
}
return router.push(`/verify?` + new URLSearchParams(params));
});
}
const { errors } = formState;
const watchPassword = watch("password", "");
const watchConfirmPassword = watch("confirmPassword", "");
const [tosAndPolicyAccepted, setTosAndPolicyAccepted] = useState(false);
const hasMinLength =
passwordComplexitySettings &&
watchPassword?.length >= passwordComplexitySettings.minLength;
const hasSymbol = symbolValidator(watchPassword);
const hasNumber = numberValidator(watchPassword);
const hasUppercase = upperCaseValidator(watchPassword);
const hasLowercase = lowerCaseValidator(watchPassword);
const policyIsValid =
passwordComplexitySettings &&
(passwordComplexitySettings.requiresLowercase ? hasLowercase : true) &&
(passwordComplexitySettings.requiresNumber ? hasNumber : true) &&
(passwordComplexitySettings.requiresUppercase ? hasUppercase : true) &&
(passwordComplexitySettings.requiresSymbol ? hasSymbol : true) &&
hasMinLength;
return (
<form className="w-full">
<div className="grid grid-cols-2 gap-4 mb-4">
<div className="">
<TextInput
type="firstname"
autoComplete="firstname"
required
{...register("firstname", { required: "This field is required" })}
label="First name"
error={errors.firstname?.message as string}
/>
</div>
<div className="">
<TextInput
type="lastname"
autoComplete="lastname"
required
{...register("lastname", { required: "This field is required" })}
label="Last name"
error={errors.lastname?.message as string}
/>
</div>
<div className="col-span-2">
<TextInput
type="email"
autoComplete="email"
required
{...register("email", { required: "This field is required" })}
label="E-mail"
error={errors.email?.message as string}
/>
</div>
<div className="">
<TextInput
type="password"
autoComplete="new-password"
required
{...register("password", {
required: "You have to provide a password!",
})}
label="Password"
error={errors.password?.message as string}
/>
</div>
<div className="">
<TextInput
type="password"
required
autoComplete="new-password"
{...register("confirmPassword", {
required: "This field is required",
})}
label="Confirm Password"
error={errors.confirmPassword?.message as string}
/>
</div>
</div>
{passwordComplexitySettings && (
<PasswordComplexity
passwordComplexitySettings={passwordComplexitySettings}
password={watchPassword}
equals={!!watchPassword && watchPassword === watchConfirmPassword}
/>
)}
{legal && (
<PrivacyPolicyCheckboxes
legal={legal}
onChange={setTosAndPolicyAccepted}
/>
)}
<div className="mt-8 flex w-full flex-row items-center justify-between">
<Button type="button" variant={ButtonVariants.Secondary}>
back
</Button>
<Button
type="submit"
variant={ButtonVariants.Primary}
disabled={
loading ||
!policyIsValid ||
!formState.isValid ||
!tosAndPolicyAccepted ||
watchPassword !== watchConfirmPassword
}
onClick={handleSubmit(submitAndLink)}
>
{loading && <Spinner className="h-5 w-5 mr-2" />}
continue
</Button>
</div>
</form>
);
}

View File

@@ -64,27 +64,6 @@ export default function RegisterFormWithoutPassword({
return res.json();
}
async function createSessionWithLoginName(loginName: string) {
setLoading(true);
const res = await fetch("/api/session", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
loginName: loginName,
organization: organization,
authRequestId: authRequestId,
}),
});
setLoading(false);
if (!res.ok) {
throw new Error("Failed to set user");
}
return res.json();
}
async function submitAndContinue(
value: Inputs,
withPassword: boolean = false
@@ -102,22 +81,20 @@ export default function RegisterFormWithoutPassword({
return withPassword
? router.push(`/register?` + new URLSearchParams(registerParams))
: submitAndRegister(value)
.then((resp: any) => {
createSessionWithLoginName(value.email).then(({ factors }) => {
setError("");
.then((session) => {
setError("");
const params: any = { loginName: factors.user.loginName };
const params: any = { loginName: session.factors.user.loginName };
if (organization) {
params.organization = organization;
}
if (organization) {
params.organization = organization;
}
if (authRequestId) {
params.authRequestId = authRequestId;
}
if (authRequestId) {
params.authRequestId = authRequestId;
}
return router.push(`/passkey/add?` + new URLSearchParams(params));
});
return router.push(`/passkey/add?` + new URLSearchParams(params));
})
.catch((errorDetails: Error) => {
setLoading(false);

View File

@@ -15,7 +15,6 @@ import {
import { useRouter } from "next/navigation";
import { Spinner } from "./Spinner";
import Alert from "./Alert";
import { AuthRequest } from "@zitadel/server";
type Inputs =
| {
@@ -74,52 +73,25 @@ export default function SetPasswordForm({
return res.json();
}
async function createSessionWithLoginNameAndPassword(
loginName: string,
password: string
) {
const res = await fetch("/api/session", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
loginName: loginName,
password: password,
organization: organization,
authRequestId, //, register does not need an oidc callback
}),
});
if (!res.ok) {
throw new Error("Failed to set user");
}
return res.json();
}
function submitAndLink(value: Inputs): Promise<boolean | void> {
return submitRegister(value)
.then((humanResponse: any) => {
.then((registerResponse) => {
setError("");
return createSessionWithLoginNameAndPassword(
email,
value.password
).then((session) => {
setLoading(false);
const params: any = { userId: humanResponse.userId };
if (authRequestId) {
params.authRequestId = authRequestId;
}
if (organization) {
params.organization = organization;
}
if (session && session.sessionId) {
params.sessionId = session.sessionId;
}
setLoading(false);
const params: any = { userId: registerResponse.userId };
return router.push(`/verify?` + new URLSearchParams(params));
});
if (authRequestId) {
params.authRequestId = authRequestId;
}
if (organization) {
params.organization = organization;
}
if (registerResponse && registerResponse.sessionId) {
params.sessionId = registerResponse.sessionId;
}
return router.push(`/verify?` + new URLSearchParams(params));
})
.catch((errorDetails: Error) => {
setLoading(false);