show error on password page

This commit is contained in:
Max Peintner
2023-05-22 16:28:47 +02:00
parent a02dcd4d5b
commit b27c8af65f
8 changed files with 71 additions and 65 deletions

View File

@@ -1,36 +1,48 @@
import { getSession, server } from "#/lib/zitadel"; import { getSession, server } from "#/lib/zitadel";
import Alert from "#/ui/Alert";
import PasswordForm from "#/ui/PasswordForm"; import PasswordForm from "#/ui/PasswordForm";
import UserAvatar from "#/ui/UserAvatar"; import UserAvatar from "#/ui/UserAvatar";
import { getMostRecentCookieWithLoginname } from "#/utils/cookies"; import { getMostRecentCookieWithLoginname } from "#/utils/cookies";
async function loadSession(loginName: string) {
try {
const recent = await getMostRecentCookieWithLoginname(`${loginName}`);
return getSession(server, recent.id, recent.token).then(({ session }) => {
return session;
});
} catch (error) {
throw new Error("Session could not be loaded!");
}
}
export default async function Page({ searchParams }: { searchParams: any }) { export default async function Page({ searchParams }: { searchParams: any }) {
const { loginName } = searchParams; const { loginName } = searchParams;
const sessionFactors = await loadSession(loginName); const sessionFactors = await loadSession(loginName);
async function loadSession(loginName: string) {
try {
const recent = await getMostRecentCookieWithLoginname(loginName);
return getSession(server, recent.id, recent.token).then(({ session }) => {
return session;
});
} catch (error) {
console.log(error);
}
}
return ( return (
<div className="flex flex-col items-center space-y-4"> <div className="flex flex-col items-center space-y-4">
<h1>{sessionFactors.factors?.user?.displayName ?? "Password"}</h1> <h1>{sessionFactors?.factors?.user?.displayName ?? "Password"}</h1>
<p className="ztdl-p mb-6 block">Enter your password.</p> <p className="ztdl-p mb-6 block">Enter your password.</p>
<UserAvatar {!sessionFactors && (
loginName={loginName ?? sessionFactors.factors?.user?.loginName} <div className="py-4">
displayName={sessionFactors.factors?.user?.displayName} <Alert>
showDropdown Could not get the context of the user. Make sure to enter the
></UserAvatar> username first or provide a loginName as searchParam.
</Alert>
</div>
)}
<PasswordForm /> {sessionFactors && (
<UserAvatar
loginName={loginName ?? sessionFactors.factors?.user?.loginName}
displayName={sessionFactors.factors?.user?.displayName}
showDropdown
></UserAvatar>
)}
<PasswordForm loginName={loginName} />
</div> </div>
); );
} }

View File

@@ -1,4 +1,3 @@
"use client";
import UsernameForm from "#/ui/UsernameForm"; import UsernameForm from "#/ui/UsernameForm";
export default function Page() { export default function Page() {

View File

@@ -19,7 +19,6 @@ export async function POST(request: NextRequest) {
createdSession.sessionId, createdSession.sessionId,
createdSession.sessionToken createdSession.sessionToken
).then(({ session }) => { ).then(({ session }) => {
console.log(session);
const sessionCookie: SessionCookie = { const sessionCookie: SessionCookie = {
id: createdSession.sessionId, id: createdSession.sessionId,
token: createdSession.sessionToken, token: createdSession.sessionToken,
@@ -46,9 +45,7 @@ export async function PUT(request: NextRequest) {
const { password } = body; const { password } = body;
const recent = await getMostRecentSessionCookie(); const recent = await getMostRecentSessionCookie();
console.log("found recent cookie: ", recent);
const session = await setSession(server, recent.id, recent.token, password); const session = await setSession(server, recent.id, recent.token, password);
console.log("updatedsession", session);
const sessionCookie: SessionCookie = { const sessionCookie: SessionCookie = {
id: recent.id, id: recent.id,
@@ -59,46 +56,25 @@ export async function PUT(request: NextRequest) {
return getSession(server, sessionCookie.id, sessionCookie.token).then( return getSession(server, sessionCookie.id, sessionCookie.token).then(
({ session }) => { ({ session }) => {
console.log(session);
const newCookie: SessionCookie = { const newCookie: SessionCookie = {
id: sessionCookie.id, id: sessionCookie.id,
token: sessionCookie.token, token: sessionCookie.token,
changeDate: session.changeDate, changeDate: session.changeDate,
loginName: session.factors.user.loginName, loginName: session.factors.user.loginName,
}; };
// return addSessionToCookie(sessionCookie).then(() => {
// return NextResponse.json({ factors: session.factors }); return updateSessionCookie(sessionCookie.id, sessionCookie)
// }); .then(() => {
return updateSessionCookie(sessionCookie.id, sessionCookie).then(() => { console.log("updatedRecent:", sessionCookie);
console.log("updatedRecent:", sessionCookie); return NextResponse.json({ factors: session.factors });
return NextResponse.json({ factors: session.factors }); })
}); .catch((error) => {
console.error("errr", error);
return NextResponse.json(error, { status: 500 });
});
} }
); );
} else { } else {
return NextResponse.error(); return NextResponse.error();
} }
} }
// /**
// *
// * @param request loginName of a session
// * @returns the session
// */
// export async function GET(request: NextRequest) {
// console.log(request);
// if (request) {
// const { loginName } = request.params;
// const recent = await getMostRecentCookieWithLoginname(loginName);
// console.log("found recent cookie: ", recent);
// return getSession(server, recent.id, recent.token).then(({ session }) => {
// console.log(session);
// return NextResponse.json({ factors: session.factors });
// });
// } else {
// return NextResponse.error();
// }
// }

View File

@@ -7,7 +7,7 @@ type Props = {
export default function Alert({ children }: Props) { export default function Alert({ children }: Props) {
return ( return (
<div className="flex flex-row items-center justify-center border border-yellow-600/40 dark:border-yellow-500/20 bg-yellow-200/30 text-yellow-600 dark:bg-yellow-700/20 dark:text-yellow-200 rounded-md py-2 scroll-px-40"> <div className="flex flex-row items-center justify-center border border-yellow-600/40 dark:border-yellow-500/20 bg-yellow-200/30 text-yellow-600 dark:bg-yellow-700/20 dark:text-yellow-200 rounded-md py-2 scroll-px-40">
<ExclamationTriangleIcon className="h-5 w-5 mr-2" /> <ExclamationTriangleIcon className="flex-shrink-0 h-5 w-5 mr-2 ml-2" />
<span className="text-center text-sm">{children}</span> <span className="text-center text-sm">{children}</span>
</div> </div>
); );

View File

@@ -6,12 +6,17 @@ import { TextInput } from "./Input";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Spinner } from "./Spinner"; import { Spinner } from "./Spinner";
import Alert from "./Alert";
type Inputs = { type Inputs = {
password: string; password: string;
}; };
export default function PasswordForm() { type Props = {
loginName: string;
};
export default function PasswordForm({ loginName }: Props) {
const { register, handleSubmit, formState } = useForm<Inputs>({ const { register, handleSubmit, formState } = useForm<Inputs>({
mode: "onBlur", mode: "onBlur",
}); });
@@ -34,17 +39,20 @@ export default function PasswordForm() {
}), }),
}); });
const response = await res.json();
if (!res.ok) { if (!res.ok) {
setLoading(false); setLoading(false);
throw new Error("Failed to register user"); console.log(response);
setError(response.details);
return Promise.reject(response.details);
} else {
setLoading(false);
return response;
} }
setLoading(false);
return res.json();
} }
function submitPasswordAndContinue(value: Inputs): Promise<boolean | void> { function submitPasswordAndContinue(value: Inputs): Promise<boolean | void> {
console.log(value);
return submitPassword(value).then((resp: any) => { return submitPassword(value).then((resp: any) => {
return router.push(`/accounts`); return router.push(`/accounts`);
}); });
@@ -62,8 +70,18 @@ export default function PasswordForm() {
label="Password" label="Password"
// error={errors.username?.message as string} // error={errors.username?.message as string}
/> />
{loginName && (
<input type="hidden" name="loginName" value={loginName} />
)}
</div> </div>
{error && (
<div className="py-4">
<Alert>{error}</Alert>
</div>
)}
<div className="mt-8 flex w-full flex-row items-center"> <div className="mt-8 flex w-full flex-row items-center">
{/* <Button type="button" variant={ButtonVariants.Secondary}> {/* <Button type="button" variant={ButtonVariants.Secondary}>
back back

View File

@@ -34,7 +34,7 @@ export default function UsernameForm() {
if (!res.ok) { if (!res.ok) {
setLoading(false); setLoading(false);
throw new Error("Failed to register user"); throw new Error("Failed to set user");
} }
setLoading(false); setLoading(false);

View File

@@ -87,7 +87,7 @@ export default function VerifyEmailForm({ userId, code, submit }: Props) {
function submitCodeAndContinue(value: Inputs): Promise<boolean | void> { function submitCodeAndContinue(value: Inputs): Promise<boolean | void> {
console.log(value); console.log(value);
return submitCode(value).then((resp: any) => { return submitCode(value).then((resp: any) => {
return router.push(`/accounts`); return router.push(`/username`);
}); });
} }

View File

@@ -146,12 +146,13 @@ export async function getMostRecentCookieWithLoginname(
if (stringifiedCookie?.value) { if (stringifiedCookie?.value) {
const sessions: SessionCookie[] = JSON.parse(stringifiedCookie?.value); const sessions: SessionCookie[] = JSON.parse(stringifiedCookie?.value);
console.log("sess", sessions);
const filtered = sessions.filter((cookie) => { const filtered = sessions.filter((cookie) => {
console.log("filtered", `${cookie.loginName}`, loginName?.toString()); console.log(!!loginName);
return !!loginName ? cookie.loginName === loginName : true; return !!loginName ? cookie.loginName === loginName : true;
}); });
console.log(filtered);
const latest = const latest =
filtered && filtered.length filtered && filtered.length
? filtered.reduce((prev, current) => { ? filtered.reduce((prev, current) => {