Merge branch 'main' into setup-integration-tests

This commit is contained in:
Elio Bischof
2023-06-14 09:38:51 +02:00
13 changed files with 233 additions and 83 deletions

View File

@@ -21,9 +21,6 @@ jobs:
- name: Install Dependencies
id: deps
run: pnpm install
- name: Generate Stubs
id: grpc
run: pnpm generate
- name: Test
id: test
run: pnpm test

View File

@@ -50,11 +50,11 @@ You can execute the following commands in the following directories:
- The projects root directory: all tests in the project are executed
```sh
# Run unit and integration tests once
pnpm run test -- --passWithNoTests
# Run all once
pnpm test
# Rerun unit and integration tests on file changes
pnpm run test:watch -- --passWithNoTests
# Rerun tests on file changes
pnpm test:watch
```
### Developing Against Your Local ZITADEL Instance

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 Alert from "#/ui/Alert";
import { Avatar } from "#/ui/Avatar";
import { getAllSessionIds } from "#/utils/cookies";
import { UserPlusIcon, XCircleIcon } from "@heroicons/react/24/outline";
import moment from "moment";
import { UserPlusIcon } from "@heroicons/react/24/outline";
import Link from "next/link";
import SessionsList from "#/ui/SessionsList";
async function loadSessions(): Promise<Session[]> {
const ids = await getAllSessionIds();
@@ -23,7 +21,7 @@ async function loadSessions(): Promise<Session[]> {
}
export default async function Page() {
const sessions = await loadSessions();
let sessions = await loadSessions();
return (
<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>
<div className="flex flex-col w-full space-y-2">
{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>
)}
<SessionsList sessions={sessions} />
<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="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 {
SessionCookie,
addSessionToCookie,
getMostRecentSessionCookie,
getSessionCookieById,
removeSessionFromCookie,
updateSessionCookie,
} from "#/utils/cookies";
import { NextRequest, NextResponse } from "next/server";
@@ -115,10 +123,43 @@ export async function PUT(request: NextRequest) {
}
})
.catch((error) => {
console.error("erasd", error);
return NextResponse.json(error, { status: 500 });
});
} else {
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,
VerifyEmailResponse,
SetSessionResponse,
DeleteSessionResponse,
} from "@zitadel/server";
export const zitadelConfig: ZitadelServerOptions = {
@@ -103,6 +104,15 @@ export function getSession(
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(
server: ZitadelServer,
ids: string[]

View File

@@ -8,7 +8,6 @@ import React, {
InputHTMLAttributes,
ReactNode,
} from "react";
import { v4 as uuidv4 } from "uuid";
export type TextInputProps = DetailedHTMLProps<
InputHTMLAttributes<HTMLInputElement>,
@@ -55,7 +54,6 @@ export const TextInput = forwardRef<HTMLInputElement, TextInputProps>(
},
ref
) => {
const id = uuidv4();
return (
<label className="flex flex-col text-12px text-input-light-label dark:text-input-dark-label">
<span

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> {
const cookiesList = cookies();
const stringifiedCookie = cookiesList.get("sessions");

View File

@@ -27,7 +27,7 @@ describe('authMiddleware', () => {
it(name, async () => {
const mockNext = jest.fn().mockImplementation(async function*() { });
const mockRequest = {}; // Ersetze dies mit einem geeigneten Mock Request-Objekt
const mockRequest = {};
const mockMethodDescriptor: MethodDescriptor = {
options: {idempotencyLevel: undefined},
@@ -38,7 +38,7 @@ describe('authMiddleware', () => {
const mockCall: ClientMiddlewareCall<unknown, unknown> = {
method: mockMethodDescriptor,
requestStream: false, // Setze diese Werte entsprechend deiner Testbedingungen
requestStream: false,
responseStream: false,
request: mockRequest,
next: mockNext,

View File

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

View File

@@ -27,7 +27,7 @@ describe('authMiddleware', () => {
it(name, async () => {
const mockNext = jest.fn().mockImplementation(async function*() { });
const mockRequest = {}; // Ersetze dies mit einem geeigneten Mock Request-Objekt
const mockRequest = {};
const mockMethodDescriptor: MethodDescriptor = {
options: {idempotencyLevel: undefined},
@@ -38,7 +38,7 @@ describe('authMiddleware', () => {
const mockCall: ClientMiddlewareCall<unknown, unknown> = {
method: mockMethodDescriptor,
requestStream: false, // Setze diese Werte entsprechend deiner Testbedingungen
requestStream: false,
responseStream: false,
request: mockRequest,
next: mockNext,

View File

@@ -19,9 +19,17 @@
"^build"
]
},
"test": {},
"test": {
"dependsOn": [
"generate",
"@zitadel/server#build"
]
},
"test:watch": {
"cache": false
"dependsOn": [
"generate",
"@zitadel/server#build"
]
},
"lint": {},
"dev": {
@@ -37,6 +45,11 @@
],
"globalEnv": [
"ZITADEL_API_URL",
"ZITADEL_SERVICE_USER_TOKEN"
"ZITADEL_SERVICE_USER_TOKEN",
"ZITADEL_SYSTEM_API_URL",
"ZITADEL_SYSTEM_API_USERID",
"ZITADEL_SYSTEM_API_KEY",
"ZITADEL_ISSUER",
"ZITADEL_ADMIN_TOKEN"
]
}