session put

This commit is contained in:
Max Peintner
2023-06-29 17:04:34 +02:00
parent c21961f593
commit e25fa6a228
7 changed files with 263 additions and 219 deletions

View File

@@ -1,11 +1,11 @@
import {
createSession,
getLoginSettings,
listAuthenticationMethodTypes,
server,
} from "#/lib/zitadel";
import UsernameForm from "#/ui/UsernameForm";
import { AuthenticationMethodType, Factors } from "@zitadel/server";
import { redirect } from "next/navigation";
type SessionAuthMethods = {
authMethodTypes: AuthenticationMethodType[];
@@ -13,7 +13,7 @@ type SessionAuthMethods = {
factors: Factors;
};
async function updateCookie(loginName: string) {
async function createSessionAndCookie(loginName: string) {
const res = await fetch(
`${process.env.VERCEL_URL ?? "http://localhost:3000"}/session`,
{
@@ -24,52 +24,39 @@ async function updateCookie(loginName: string) {
body: JSON.stringify({
loginName,
}),
next: { revalidate: 0 },
}
);
const response = await res.json();
if (!res.ok) {
console.log("damn");
return Promise.reject(response.details);
}
return response;
}
async function getSessionAndAuthMethods(
loginName: string,
domain: string
async function createSessionAndGetAuthMethods(
loginName: string
): Promise<SessionAuthMethods> {
const createdSession = await createSession(
server,
loginName,
domain,
undefined,
undefined
);
if (createdSession) {
return updateCookie(loginName)
.then((resp) => {
return listAuthenticationMethodTypes(resp.factors.user.id)
.then((methods) => {
return {
authMethodTypes: methods.authMethodTypes,
sessionId: createdSession.sessionId,
factors: resp?.factors,
};
})
.catch((error) => {
throw "Could not get auth methods";
});
})
.catch((error) => {
console.log(error);
throw "Could not add session to cookie";
});
} else {
throw "Could not create session";
}
return createSessionAndCookie(loginName)
.then((resp) => {
return listAuthenticationMethodTypes(resp.factors.user.id)
.then((methods) => {
return {
authMethodTypes: methods.authMethodTypes,
sessionId: resp.sessionId,
factors: resp?.factors,
};
})
.catch((error) => {
throw "Could not get auth methods";
});
})
.catch((error) => {
console.log(error);
throw "Could not add session to cookie";
});
}
export default async function Page({
@@ -77,17 +64,25 @@ export default async function Page({
}: {
searchParams: Record<string | number | symbol, string | undefined>;
}) {
const domain: string = process.env.VERCEL_URL ?? "localhost";
const loginName = searchParams?.loginName;
if (loginName) {
const login = await getLoginSettings(server);
console.log(login);
const sessionAndAuthMethods = await getSessionAndAuthMethods(
loginName,
domain
const sessionAndAuthMethods = await createSessionAndGetAuthMethods(
loginName
);
console.log(sessionAndAuthMethods);
if (sessionAndAuthMethods.authMethodTypes.length == 1) {
const method = sessionAndAuthMethods.authMethodTypes[0];
switch (method) {
case AuthenticationMethodType.AUTHENTICATION_METHOD_TYPE_PASSWORD:
return redirect("/password?" + new URLSearchParams({ loginName }));
case AuthenticationMethodType.AUTHENTICATION_METHOD_TYPE_PASSKEY:
return redirect(
"/passkey/login?" + new URLSearchParams({ loginName })
);
default:
return redirect("/password?" + new URLSearchParams({ loginName }));
}
}
return (
<div className="flex flex-col items-center space-y-4">
<h1>Welcome back!</h1>

View File

@@ -1,68 +1,55 @@
import {
getSession,
listAuthenticationMethodTypes,
server,
setSession,
} from "#/lib/zitadel";
import Alert, { AlertType } from "#/ui/Alert";
import Alert from "#/ui/Alert";
import LoginPasskey from "#/ui/LoginPasskey";
import RegisterPasskey from "#/ui/RegisterPasskey";
import UserAvatar from "#/ui/UserAvatar";
import {
SessionCookie,
getMostRecentCookieWithLoginname,
updateSessionCookie,
} from "#/utils/cookies";
import { ChallengeKind } from "@zitadel/server";
async function updateSessionAndCookie(loginName: string) {
const res = await fetch(
`${process.env.VERCEL_URL ?? "http://localhost:3000"}/session`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
loginName,
challenges: [ChallengeKind.CHALLENGE_KIND_PASSKEY],
}),
next: { revalidate: 0 },
}
);
const response = await res.json();
if (!res.ok) {
return Promise.reject(response.details);
}
return response;
}
const title = "Authenticate with a passkey";
const description =
"Your device will ask for your fingerprint, face, or screen lock";
export default async function Page({
searchParams,
}: {
searchParams: Record<string | number | symbol, string | undefined>;
}) {
const { loginName } = searchParams;
if (loginName) {
console.log(loginName);
const session = await updateSessionAndCookie(loginName);
const session = await setSessionForPasskeyChallenge(loginName);
console.log("sess", session);
const challenge = session?.challenges?.passkey;
const challenge = session?.challenges?.passkey;
console.log(challenge);
// let methods = [];
// if (sessionFactors?.factors?.user?.id) {
// methods = await listAuthenticationMethodTypes(
// sessionFactors.factors.user.id
// );
return (
<div className="flex flex-col items-center space-y-4">
<h1>{title}</h1>
// console.log(methods);
// }
async function setSessionForPasskeyChallenge(loginName?: string) {
const recent = await getMostRecentCookieWithLoginname(loginName);
console.log(recent);
return setSession(server, recent.id, recent.token, undefined, [
ChallengeKind.CHALLENGE_KIND_PASSKEY,
]).then((session) => {
const sessionCookie: SessionCookie = {
id: recent.id,
token: session.sessionToken,
changeDate: session.changeDate?.toString() ?? "",
loginName: session.factors?.user?.loginName ?? "",
};
return updateSessionCookie(sessionCookie.id, sessionCookie).then(() => {
return session;
});
});
}
const title = "Authenticate with a passkey";
const description =
"Your device will ask for your fingerprint, face, or screen lock";
return (
<div className="flex flex-col items-center space-y-4">
<h1>{title}</h1>
{/* {sessionFactors && (
{/* {sessionFactors && (
<UserAvatar
loginName={loginName ?? sessionFactors.factors?.user?.loginName}
displayName={sessionFactors.factors?.user?.displayName}
@@ -80,7 +67,31 @@ export default async function Page({
</div>
)} */}
{challenge && <LoginPasskey challenge={challenge} />}
</div>
);
{challenge && <LoginPasskey challenge={challenge} />}
</div>
);
} else {
return (
<div className="flex flex-col items-center space-y-4">
<h1>{title}</h1>
{/* {sessionFactors && (
<UserAvatar
loginName={loginName ?? sessionFactors.factors?.user?.loginName}
displayName={sessionFactors.factors?.user?.displayName}
showDropdown
></UserAvatar>
)}
<p className="ztdl-p mb-6 block">{description}</p>
{!sessionFactors && (
<div className="py-4">
</div>
)} */}
<Alert>Provide your active session as loginName param</Alert>
</div>
);
}
}

View File

@@ -10,6 +10,7 @@ import {
addSessionToCookie,
getMostRecentSessionCookie,
getSessionCookieById,
getSessionCookieByLoginName,
removeSessionFromCookie,
updateSessionCookie,
} from "#/utils/cookies";
@@ -43,6 +44,7 @@ export async function POST(request: NextRequest) {
changeDate: response.session.changeDate?.toString() ?? "",
loginName: response.session?.factors?.user?.loginName ?? "",
};
return addSessionToCookie(sessionCookie).then(() => {
return NextResponse.json({
sessionId: createdSession.sessionId,
@@ -77,68 +79,86 @@ export async function POST(request: NextRequest) {
*/
export async function PUT(request: NextRequest) {
const body = await request.json();
if (body) {
const { password } = body;
const { loginName, password, challenges } = body;
const recent = await getMostRecentSessionCookie();
const recentPromise: Promise<SessionCookie> = loginName
? getSessionCookieByLoginName(loginName).catch((error) => {
return Promise.reject(error);
})
: getMostRecentSessionCookie().catch((error) => {
return Promise.reject(error);
});
return setSession(server, recent.id, recent.token, password)
.then((session) => {
if (session) {
const sessionCookie: SessionCookie = {
id: recent.id,
token: session.sessionToken,
changeDate: session.details?.changeDate?.toString() ?? "",
loginName: recent.loginName,
};
return recentPromise
.then((recent) => {
return setSession(server, recent.id, recent.token, password, challenges)
.then((session) => {
if (session) {
const sessionCookie: SessionCookie = {
id: recent.id,
token: session.sessionToken,
changeDate: session.details?.changeDate?.toString() ?? "",
loginName: recent.loginName,
};
return getSession(server, sessionCookie.id, sessionCookie.token).then(
(response) => {
if (
response?.session &&
response.session.factors?.user?.loginName
) {
const { session } = response;
const newCookie: SessionCookie = {
id: sessionCookie.id,
token: sessionCookie.token,
changeDate: session.changeDate?.toString() ?? "",
loginName: session.factors?.user?.loginName ?? "",
};
return getSession(
server,
sessionCookie.id,
sessionCookie.token
).then((response) => {
if (
response?.session &&
response.session.factors?.user?.loginName
) {
const { session } = response;
const newCookie: SessionCookie = {
id: sessionCookie.id,
token: sessionCookie.token,
changeDate: session.changeDate?.toString() ?? "",
loginName: session.factors?.user?.loginName ?? "",
};
return updateSessionCookie(sessionCookie.id, newCookie)
.then(() => {
return NextResponse.json({ factors: session.factors });
})
.catch((error) => {
return NextResponse.json(
{ details: "could not set cookie" },
{ status: 500 }
);
});
} else {
return NextResponse.json(
{
details:
"could not get session or session does not have loginName",
},
{ status: 500 }
);
}
return updateSessionCookie(sessionCookie.id, newCookie)
.then(() => {
return NextResponse.json({ factors: session.factors });
})
.catch((error) => {
return NextResponse.json(
{ details: "could not set cookie" },
{ status: 500 }
);
});
} else {
return NextResponse.json(
{
details:
"could not get session or session does not have loginName",
},
{ status: 500 }
);
}
});
} else {
return NextResponse.json(
{ details: "Session not be set" },
{ status: 500 }
);
}
);
} else {
return NextResponse.json(
{ details: "Session not be set" },
{ status: 500 }
);
}
})
.catch((error) => {
return NextResponse.json({ details: error }, { status: 500 });
});
})
.catch((error) => {
return NextResponse.json(error, { status: 500 });
return NextResponse.json({ details: error }, { status: 500 });
});
} else {
return NextResponse.error();
return NextResponse.json(
{ details: "Request body is missing" },
{ status: 400 }
);
}
}
@@ -156,7 +176,7 @@ export async function DELETE(request: NextRequest) {
.then(() => {
return removeSessionFromCookie(session)
.then(() => {
return NextResponse.json({ factors: session.factors });
return NextResponse.json({});
})
.catch((error) => {
return NextResponse.json(

View File

@@ -118,17 +118,17 @@ export async function setSession(
challenges: ChallengeKind[] | undefined
): Promise<SetSessionResponse | undefined> {
const sessionService = session.getSession(server);
const payload = { sessionId, sessionToken, challenges };
return password
? sessionService.setSession(
{
sessionId,
sessionToken,
...payload,
checks: { password: { password } },
challenges,
},
{}
)
: sessionService.setSession({ sessionId, sessionToken, challenges }, {});
: sessionService.setSession(payload, {});
}
export async function getSession(

View File

@@ -1,13 +1,12 @@
"use client";
import { useState } from "react";
import { Button, ButtonVariants } from "./Button";
import { useForm } from "react-hook-form";
import { useRouter } from "next/navigation";
import { Spinner } from "./Spinner";
import Alert from "./Alert";
import { Challenges_Passkey } from "@zitadel/server";
import { coerceToArrayBuffer, coerceToBase64Url } from "#/utils/base64";
import { Button, ButtonVariants } from "./Button";
import Alert from "./Alert";
import { Spinner } from "./Spinner";
type Props = {
challenge: Challenges_Passkey;
@@ -50,55 +49,52 @@ export default function LoginPasskey({ challenge }: Props) {
return response;
}
function submitLoginAndContinue(): Promise<boolean | void> {
navigator.credentials
.get({
publicKey: challenge.publicKeyCredentialRequestOptions,
})
.then((assertedCredential: any) => {
if (assertedCredential) {
let authData = new Uint8Array(
assertedCredential.response.authenticatorData
);
let clientDataJSON = new Uint8Array(
assertedCredential.response.clientDataJSON
);
let rawId = new Uint8Array(assertedCredential.rawId);
let sig = new Uint8Array(assertedCredential.response.signature);
let userHandle = new Uint8Array(
assertedCredential.response.userHandle
);
let data = JSON.stringify({
id: assertedCredential.id,
rawId: coerceToBase64Url(rawId, "rawId"),
type: assertedCredential.type,
response: {
authenticatorData: coerceToBase64Url(authData, "authData"),
clientDataJSON: coerceToBase64Url(
clientDataJSON,
"clientDataJSON"
),
signature: coerceToBase64Url(sig, "sig"),
userHandle: coerceToBase64Url(userHandle, "userHandle"),
},
});
return submitLogin(passkeyId, "", data, sessionId);
} else {
setLoading(false);
setError("An error on retrieving passkey");
return null;
}
})
.catch((error) => {
console.error(error);
setLoading(false);
// setError(error);
return null;
});
}
async function submitLoginAndContinue(): Promise<boolean | void> {
// navigator.credentials
// .get({
// publicKey: challenge.publicKeyCredentialRequestOptions,
// })
// .then((assertedCredential: any) => {
// if (assertedCredential) {
// let authData = new Uint8Array(
// assertedCredential.response.authenticatorData
// );
// let clientDataJSON = new Uint8Array(
// assertedCredential.response.clientDataJSON
// );
// let rawId = new Uint8Array(assertedCredential.rawId);
// let sig = new Uint8Array(assertedCredential.response.signature);
// let userHandle = new Uint8Array(
// assertedCredential.response.userHandle
// );
// let data = JSON.stringify({
// id: assertedCredential.id,
// rawId: coerceToBase64Url(rawId, "rawId"),
// type: assertedCredential.type,
// response: {
// authenticatorData: coerceToBase64Url(authData, "authData"),
// clientDataJSON: coerceToBase64Url(
// clientDataJSON,
// "clientDataJSON"
// ),
// signature: coerceToBase64Url(sig, "sig"),
// userHandle: coerceToBase64Url(userHandle, "userHandle"),
// },
// });
// return submitLogin(passkeyId, "", data, sessionId);
// } else {
// setLoading(false);
// setError("An error on retrieving passkey");
// return null;
// }
// })
// .catch((error) => {
// console.error(error);
// setLoading(false);
// // setError(error);
// return null;
// });
// }
// return router.push(`/accounts`);
}
@@ -111,14 +107,13 @@ export default function LoginPasskey({ challenge }: Props) {
)}
<div className="mt-8 flex w-full flex-row items-center">
<Button
type="button"
variant={ButtonVariants.Secondary}
onClick={() => router.back()}
>
back
</Button>
<Button
type="button"
variant={ButtonVariants.Secondary}
onClick={() => router.back()}
>
back
</Button>
<span className="flex-grow"></span>
<Button
@@ -126,7 +121,7 @@ export default function LoginPasskey({ challenge }: Props) {
className="self-end"
variant={ButtonVariants.Primary}
disabled={loading}
onClick={handleSubmit(submitLoginAndContinue)}
onClick={() => submitLoginAndContinue()}
>
{loading && <Spinner className="h-5 w-5 mr-2" />}
continue

View File

@@ -36,6 +36,7 @@ export default function PasswordForm({ loginName }: Props) {
"Content-Type": "application/json",
},
body: JSON.stringify({
loginName,
password: values.password,
}),
});

View File

@@ -91,11 +91,11 @@ export async function getMostRecentSessionCookie(): Promise<any> {
return latest;
} else {
return Promise.reject();
return Promise.reject("no session cookie found");
}
}
export async function getSessionCookieById(id: string): Promise<any> {
export async function getSessionCookieById(id: string): Promise<SessionCookie> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
@@ -113,6 +113,28 @@ export async function getSessionCookieById(id: string): Promise<any> {
}
}
export async function getSessionCookieByLoginName(
loginName: string
): Promise<SessionCookie> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
console.log("str", stringifiedCookie);
if (stringifiedCookie?.value) {
const sessions: SessionCookie[] = JSON.parse(stringifiedCookie?.value);
console.log("sessions", sessions);
const found = sessions.find((s) => s.loginName === loginName);
if (found) {
return found;
} else {
return Promise.reject("no cookie found with loginName: " + loginName);
}
} else {
return Promise.reject("no session cookie found");
}
}
export async function getAllSessionIds(): Promise<any> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");