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(