Merge pull request #27 from zitadel/account-switcher

feat: account switcher, delete account
This commit is contained in:
Max Peintner
2023-06-07 17:08:11 +02:00
committed by GitHub
7 changed files with 209 additions and 67 deletions

View File

@@ -1,11 +1,9 @@
import { Session } from "#/../../packages/zitadel-server/dist"; import { Session } from "@zitadel/server";
import { listSessions, server } from "#/lib/zitadel"; import { listSessions, server } from "#/lib/zitadel";
import Alert from "#/ui/Alert";
import { Avatar } from "#/ui/Avatar";
import { getAllSessionIds } from "#/utils/cookies"; import { getAllSessionIds } from "#/utils/cookies";
import { UserPlusIcon, XCircleIcon } from "@heroicons/react/24/outline"; import { UserPlusIcon } from "@heroicons/react/24/outline";
import moment from "moment";
import Link from "next/link"; import Link from "next/link";
import SessionsList from "#/ui/SessionsList";
async function loadSessions(): Promise<Session[]> { async function loadSessions(): Promise<Session[]> {
const ids = await getAllSessionIds(); const ids = await getAllSessionIds();
@@ -23,7 +21,7 @@ async function loadSessions(): Promise<Session[]> {
} }
export default async function Page() { export default async function Page() {
const sessions = await loadSessions(); let sessions = await loadSessions();
return ( return (
<div className="flex flex-col items-center space-y-4"> <div className="flex flex-col items-center space-y-4">
@@ -31,65 +29,7 @@ export default async function Page() {
<p className="ztdl-p mb-6 block">Use your ZITADEL Account</p> <p className="ztdl-p mb-6 block">Use your ZITADEL Account</p>
<div className="flex flex-col w-full space-y-2"> <div className="flex flex-col w-full space-y-2">
{sessions ? ( <SessionsList sessions={sessions} />
sessions
.filter((session) => session?.factors?.user?.loginName)
.map((session, index) => {
const validPassword = session?.factors?.password?.verifiedAt;
return (
<Link
key={"session-" + index}
href={
validPassword
? `/signedin?` +
new URLSearchParams({
loginName: session.factors?.user?.loginName as string,
})
: `/password?` +
new URLSearchParams({
loginName: session.factors?.user?.loginName as string,
})
}
className="group flex flex-row items-center bg-background-light-400 dark:bg-background-dark-400 border border-divider-light hover:shadow-lg dark:hover:bg-white/10 py-2 px-4 rounded-md transition-all"
>
<div className="pr-4">
<Avatar
size="small"
loginName={session.factors?.user?.loginName as string}
name={session.factors?.user?.displayName ?? ""}
/>
</div>
<div className="flex flex-col">
<span className="">
{session.factors?.user?.displayName}
</span>
<span className="text-xs opacity-80">
{session.factors?.user?.loginName}
</span>
{validPassword && (
<span className="text-xs opacity-80">
{moment(new Date(validPassword)).fromNow()}
</span>
)}
</div>
<span className="flex-grow"></span>
<div className="relative flex flex-row items-center">
{validPassword ? (
<div className="absolute h-2 w-2 bg-green-500 rounded-full mx-2 transform right-0 group-hover:right-6 transition-all"></div>
) : (
<div className="absolute h-2 w-2 bg-red-500 rounded-full mx-2 transform right-0 group-hover:right-6 transition-all"></div>
)}
<XCircleIcon className="hidden group-hover:block h-5 w-5 transition-all opacity-50 hover:opacity-100" />
</div>
</Link>
);
})
) : (
<Alert>No Sessions available!</Alert>
)}
<Link href="/username"> <Link href="/username">
<div className="flex flex-row items-center py-3 px-4 hover:bg-black/10 dark:hover:bg-white/10 rounded-md transition-all"> <div className="flex flex-row items-center py-3 px-4 hover:bg-black/10 dark:hover:bg-white/10 rounded-md transition-all">
<div className="w-8 h-8 mr-4 flex flex-row justify-center items-center rounded-full bg-black/5 dark:bg-white/5"> <div className="w-8 h-8 mr-4 flex flex-row justify-center items-center rounded-full bg-black/5 dark:bg-white/5">

View File

@@ -1,8 +1,16 @@
import { createSession, getSession, server, setSession } from "#/lib/zitadel"; import {
createSession,
getSession,
server,
setSession,
deleteSession,
} from "#/lib/zitadel";
import { import {
SessionCookie, SessionCookie,
addSessionToCookie, addSessionToCookie,
getMostRecentSessionCookie, getMostRecentSessionCookie,
getSessionCookieById,
removeSessionFromCookie,
updateSessionCookie, updateSessionCookie,
} from "#/utils/cookies"; } from "#/utils/cookies";
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
@@ -115,10 +123,43 @@ export async function PUT(request: NextRequest) {
} }
}) })
.catch((error) => { .catch((error) => {
console.error("erasd", error);
return NextResponse.json(error, { status: 500 }); return NextResponse.json(error, { status: 500 });
}); });
} else { } else {
return NextResponse.error(); return NextResponse.error();
} }
} }
/**
*
* @param request id of the session to be deleted
*/
export async function DELETE(request: NextRequest) {
const { searchParams } = new URL(request.url);
const id = searchParams.get("id");
if (id) {
const session = await getSessionCookieById(id);
return deleteSession(server, session.id, session.token)
.then(() => {
return removeSessionFromCookie(session)
.then(() => {
return NextResponse.json({ factors: session.factors });
})
.catch((error) => {
return NextResponse.json(
{ details: "could not set cookie" },
{ status: 500 }
);
});
})
.catch((error) => {
return NextResponse.json(
{ details: "could not delete session" },
{ status: 500 }
);
});
} else {
return NextResponse.error();
}
}

View File

@@ -19,6 +19,7 @@ import {
GetSessionResponse, GetSessionResponse,
VerifyEmailResponse, VerifyEmailResponse,
SetSessionResponse, SetSessionResponse,
DeleteSessionResponse,
} from "@zitadel/server"; } from "@zitadel/server";
export const zitadelConfig: ZitadelServerOptions = { export const zitadelConfig: ZitadelServerOptions = {
@@ -103,6 +104,15 @@ export function getSession(
return sessionService.getSession({ sessionId, sessionToken }, {}); return sessionService.getSession({ sessionId, sessionToken }, {});
} }
export function deleteSession(
server: ZitadelServer,
sessionId: string,
sessionToken: string
): Promise<DeleteSessionResponse | undefined> {
const sessionService = session.getSession(server);
return sessionService.deleteSession({ sessionId, sessionToken }, {});
}
export function listSessions( export function listSessions(
server: ZitadelServer, server: ZitadelServer,
ids: string[] ids: string[]

View File

@@ -0,0 +1,98 @@
"use client";
import { Session } from "@zitadel/server";
import Link from "next/link";
import { useState } from "react";
import { Avatar } from "./Avatar";
import moment from "moment";
import { XCircleIcon } from "@heroicons/react/24/outline";
export default function SessionItem({
session,
reload,
}: {
session: Session;
reload: () => void;
}) {
const [loading, setLoading] = useState<boolean>(false);
async function clearSession(id: string) {
setLoading(true);
const res = await fetch("/session?" + new URLSearchParams({ id }), {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
id: id,
}),
});
const response = await res.json();
setLoading(false);
if (!res.ok) {
// setError(response.details);
return Promise.reject(response);
} else {
return response;
}
}
const validPassword = session?.factors?.password?.verifiedAt;
return (
<Link
href={
validPassword
? `/signedin?` +
new URLSearchParams({
loginName: session.factors?.user?.loginName as string,
})
: `/password?` +
new URLSearchParams({
loginName: session.factors?.user?.loginName as string,
})
}
className="group flex flex-row items-center bg-background-light-400 dark:bg-background-dark-400 border border-divider-light hover:shadow-lg dark:hover:bg-white/10 py-2 px-4 rounded-md transition-all"
>
<div className="pr-4">
<Avatar
size="small"
loginName={session.factors?.user?.loginName as string}
name={session.factors?.user?.displayName ?? ""}
/>
</div>
<div className="flex flex-col">
<span className="">{session.factors?.user?.displayName}</span>
<span className="text-xs opacity-80">
{session.factors?.user?.loginName}
</span>
{validPassword && (
<span className="text-xs opacity-80">
{moment(new Date(validPassword)).fromNow()}
</span>
)}
</div>
<span className="flex-grow"></span>
<div className="relative flex flex-row items-center">
{validPassword ? (
<div className="absolute h-2 w-2 bg-green-500 rounded-full mx-2 transform right-0 group-hover:right-6 transition-all"></div>
) : (
<div className="absolute h-2 w-2 bg-red-500 rounded-full mx-2 transform right-0 group-hover:right-6 transition-all"></div>
)}
<XCircleIcon
className="hidden group-hover:block h-5 w-5 transition-all opacity-50 hover:opacity-100"
onClick={(event) => {
event.preventDefault();
clearSession(session.id).then(() => {
reload();
});
}}
/>
</div>
</Link>
);
}

View File

@@ -0,0 +1,34 @@
"use client";
import { Session } from "@zitadel/server";
import SessionItem from "./SessionItem";
import Alert from "./Alert";
import { useEffect, useState } from "react";
type Props = {
sessions: Session[];
};
export default function SessionsList({ sessions }: Props) {
const [list, setList] = useState<Session[]>(sessions);
return sessions ? (
<div className="flex flex-col">
{list
.filter((session) => session?.factors?.user?.loginName)
.map((session, index) => {
return (
<SessionItem
session={session}
reload={() => {
setList(list.filter((s) => s.id !== session.id));
}}
key={"session-" + index}
/>
);
})}
</div>
) : (
<Alert>No Sessions available!</Alert>
);
}

View File

@@ -92,6 +92,24 @@ export async function getMostRecentSessionCookie(): Promise<any> {
} }
} }
export async function getSessionCookieById(id: string): Promise<any> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");
if (stringifiedCookie?.value) {
const sessions: SessionCookie[] = JSON.parse(stringifiedCookie?.value);
const found = sessions.find((s) => s.id === id);
if (found) {
return found;
} else {
return Promise.reject();
}
} else {
return Promise.reject();
}
}
export async function getAllSessionIds(): Promise<any> { export async function getAllSessionIds(): Promise<any> {
const cookiesList = cookies(); const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions"); const stringifiedCookie = cookiesList.get("sessions");

View File

@@ -17,6 +17,7 @@ export {
GetSessionResponse, GetSessionResponse,
CreateSessionResponse, CreateSessionResponse,
SetSessionResponse, SetSessionResponse,
DeleteSessionResponse,
} from "./proto/server/zitadel/session/v2alpha/session_service"; } from "./proto/server/zitadel/session/v2alpha/session_service";
export { export {
GetPasswordComplexitySettingsResponse, GetPasswordComplexitySettingsResponse,