Frontends auf Bearer: Portal-BFF, workflow-approvals, workflow-tasks #412
No files matched your search
@@ -13,6 +13,7 @@ vi.mock("../lib/http", () => ({
|
||||
identity: () => ({ userId: "u-1", tenant: "acme", role: "user" }),
|
||||
fetch: (...a: unknown[]) => fetchMock(...a),
|
||||
}),
|
||||
getWorkflowSession: () => ({ token: () => Promise.reject(new Error("kein workflow-token")) }),
|
||||
}));
|
||||
|
||||
import { ModuleGrid } from "./ModuleGrid";
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useI18n, resolveModuleHref } from "@nexarch/shl";
|
||||
import type { ModuleEntry } from "../lib/modules";
|
||||
import type { Worklist } from "../lib/worklist";
|
||||
import { getSession } from "../lib/http";
|
||||
import { getSession, getWorkflowSession } from "../lib/http";
|
||||
import { ModuleTile, StatTile } from "./Tile";
|
||||
import { Skeleton } from "./Skeleton";
|
||||
import { CommandPalette } from "./CommandPalette";
|
||||
@@ -23,9 +23,9 @@ export async function fetchVisibleModules(fetchImpl: typeof fetch): Promise<Modu
|
||||
return body.modules ?? [];
|
||||
}
|
||||
|
||||
export async function fetchWorklist(fetchImpl: typeof fetch): Promise<Worklist | null> {
|
||||
export async function fetchWorklist(fetchImpl: typeof fetch, workflowToken?: string): Promise<Worklist | null> {
|
||||
try {
|
||||
const res = await fetchImpl("/api/worklist");
|
||||
const res = await fetchImpl("/api/worklist", workflowToken ? { headers: { "X-Workflow-Token": workflowToken } } : undefined);
|
||||
return res.ok ? ((await res.json()) as Worklist) : null;
|
||||
} catch {
|
||||
return null;
|
||||
@@ -87,7 +87,8 @@ export function ModuleGrid() {
|
||||
return;
|
||||
}
|
||||
const call = (input: RequestInfo | URL, init?: RequestInit) => session.fetch(input, init);
|
||||
const [modules, worklist] = await Promise.all([fetchVisibleModules(call), fetchWorklist(call)]);
|
||||
const workflowToken = await getWorkflowSession().token().catch(() => undefined);
|
||||
const [modules, worklist] = await Promise.all([fetchVisibleModules(call), fetchWorklist(call, workflowToken)]);
|
||||
if (!cancelled) setState({ status: "ready", modules, worklist, who: { userId: identity.userId, tenant: identity.tenant } });
|
||||
} catch {
|
||||
if (!cancelled) setState({ status: "error" });
|
||||
|
||||
@@ -15,10 +15,12 @@ function mint(claims: Record<string, unknown>): string {
|
||||
}
|
||||
|
||||
describe("GET /api/worklist", () => {
|
||||
let wfCalls: { url: string; user: string }[];
|
||||
let wfCalls: { url: string; user: string; auth?: string }[];
|
||||
|
||||
const req = (token?: string, query = "") =>
|
||||
new NextRequest(`http://portal.example/api/worklist${query}`, { headers: token ? { authorization: `Bearer ${token}` } : {} });
|
||||
const req = (token?: string, query = "", wfToken?: string) =>
|
||||
new NextRequest(`http://portal.example/api/worklist${query}`, {
|
||||
headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...(wfToken ? { "x-workflow-token": wfToken } : {}) },
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
process.env.PORTAL_WORKFLOW_API_URL = "http://wf.example";
|
||||
@@ -31,7 +33,8 @@ describe("GET /api/worklist", () => {
|
||||
if (u.endsWith("/auth/module-jwks")) {
|
||||
return new Response(JSON.stringify({ keys: [{ kid: "k1", public_key: rawPub.toString("base64") }] }), { status: 200 });
|
||||
}
|
||||
wfCalls.push({ url: u, user: (init?.headers as Record<string, string>)["X-User-Id"] });
|
||||
const h = init?.headers as Record<string, string>;
|
||||
wfCalls.push({ url: u, user: h["X-User-Id"], auth: h.Authorization } as never);
|
||||
return new Response(JSON.stringify([]), { status: 200 });
|
||||
}) as typeof fetch;
|
||||
});
|
||||
@@ -57,6 +60,23 @@ describe("GET /api/worklist", () => {
|
||||
expect(wfCalls.every((c) => c.user === "u1")).toBe(true);
|
||||
});
|
||||
|
||||
it("reicht ein gueltiges Workflow-Token als Bearer weiter und sendet keine X-User-Id", async () => {
|
||||
const { GET } = await import("./route");
|
||||
const wf = mint({ sub: "u1", tenant: "acme", aud: "workflow" });
|
||||
const res = await GET(req(mint({ sub: "u1", tenant: "acme", aud: "portal" }), "", wf));
|
||||
expect(res.status).toBe(200);
|
||||
expect(wfCalls.length).toBe(3);
|
||||
expect(wfCalls.every((c) => c.auth === `Bearer ${wf}` && c.user === undefined)).toBe(true);
|
||||
});
|
||||
|
||||
it("lehnt Workflow-Token eines anderen Benutzers oder falschen Zielmoduls ab", async () => {
|
||||
const { GET } = await import("./route");
|
||||
const portal = mint({ sub: "u1", tenant: "acme", aud: "portal" });
|
||||
expect((await GET(req(portal, "", mint({ sub: "u2", tenant: "acme", aud: "workflow" })))).status).toBe(401);
|
||||
expect((await GET(req(portal, "", mint({ sub: "u1", tenant: "acme", aud: "portal" })))).status).toBe(401);
|
||||
expect(wfCalls.length).toBe(0);
|
||||
});
|
||||
|
||||
it("cached je Mandant und Benutzer", async () => {
|
||||
const { GET } = await import("./route");
|
||||
await GET(req(mint({ sub: "u1", tenant: "acme" })));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { authenticate, coreConfigured } from "../../../lib/auth";
|
||||
import { authenticate, coreConfigured, verifyWorkflowToken } from "../../../lib/auth";
|
||||
import { worklistCache } from "../../../lib/caches";
|
||||
import { loadWorklist } from "../../../lib/worklist";
|
||||
|
||||
@@ -7,7 +7,8 @@ export const dynamic = "force-dynamic";
|
||||
|
||||
const CACHE_TTL_MS = Number(process.env.PORTAL_WORKLIST_CACHE_SECONDS ?? "15") * 1000;
|
||||
// Nur Zaehler, keine Inhalte. Benutzer und Mandant stammen aus dem verifizierten Token;
|
||||
// die Workflow-API kennt bisher nur X-User-Id (Uebergangsmodus), der Header wird hier serverseitig gesetzt.
|
||||
// mit X-Workflow-Token (Zielmodul workflow, gleicher Benutzer und Mandant) geht der Aufruf per Bearer an die Workflow-API,
|
||||
// ohne ihn als X-User-Id (Uebergangsmodus).
|
||||
export async function GET(request: NextRequest) {
|
||||
const base = process.env.PORTAL_WORKFLOW_API_URL;
|
||||
if (!base || !coreConfigured()) {
|
||||
@@ -16,12 +17,22 @@ export async function GET(request: NextRequest) {
|
||||
const claims = await authenticate(request);
|
||||
if (!claims) return NextResponse.json({ error: "Anmeldung erforderlich" }, { status: 401 });
|
||||
|
||||
const wfHeader = request.headers.get("x-workflow-token");
|
||||
let workflowToken: string | undefined;
|
||||
if (wfHeader) {
|
||||
const wfClaims = await verifyWorkflowToken(wfHeader);
|
||||
if (!wfClaims || wfClaims.sub !== claims.sub || wfClaims.tenant !== claims.tenant) {
|
||||
return NextResponse.json({ error: "Anmeldung erforderlich" }, { status: 401 });
|
||||
}
|
||||
workflowToken = wfHeader;
|
||||
}
|
||||
|
||||
const noStore = { "Cache-Control": "no-store" };
|
||||
const key = `${claims.tenant}\u0000${claims.sub}`;
|
||||
const hit = worklistCache.get(key, CACHE_TTL_MS);
|
||||
if (hit) return NextResponse.json(hit, { headers: noStore });
|
||||
|
||||
const data = await loadWorklist(base, claims.tenant, claims.sub);
|
||||
const data = await loadWorklist(base, claims.tenant, claims.sub, fetch, workflowToken);
|
||||
worklistCache.set(key, data);
|
||||
return NextResponse.json(data, { headers: noStore });
|
||||
}
|
||||
@@ -17,3 +17,13 @@ export async function authenticate(request: NextRequest): Promise<VerifiedClaims
|
||||
export function coreConfigured(): boolean {
|
||||
return Boolean(process.env.PORTAL_CORE_API_URL ?? process.env.NEXT_PUBLIC_CORE_API_BASE);
|
||||
}
|
||||
|
||||
export async function verifyWorkflowToken(token: string): Promise<VerifiedClaims | null> {
|
||||
const coreBase = process.env.PORTAL_CORE_API_URL ?? process.env.NEXT_PUBLIC_CORE_API_BASE;
|
||||
if (!coreBase) return null;
|
||||
return verifyModuleToken(token, {
|
||||
jwksUrl: `${coreBase.replace(/\/$/, "")}/auth/module-jwks`,
|
||||
issuer: process.env.PORTAL_TOKEN_ISSUER,
|
||||
audience: process.env.PORTAL_WORKFLOW_TOKEN_AUDIENCE || "workflow",
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createSession, redirectToLogin, type Session } from "@nexarch/shl";
|
||||
|
||||
let session: Session | undefined;
|
||||
let workflowSession: Session | undefined;
|
||||
|
||||
export function getSession(): Session {
|
||||
if (!session) {
|
||||
@@ -17,6 +18,18 @@ export function getSession(): Session {
|
||||
return session;
|
||||
}
|
||||
|
||||
export function getWorkflowSession(): Session {
|
||||
if (!workflowSession) {
|
||||
const coreBase = process.env.NEXT_PUBLIC_CORE_API_BASE;
|
||||
if (!coreBase) {
|
||||
throw new Error("NEXT_PUBLIC_CORE_API_BASE ist nicht gesetzt (Umgebungsvariable erforderlich)");
|
||||
}
|
||||
workflowSession = createSession({ coreBase, module: "workflow" });
|
||||
}
|
||||
return workflowSession;
|
||||
}
|
||||
|
||||
export function resetSessionForTests(): void {
|
||||
session = undefined;
|
||||
workflowSession = undefined;
|
||||
}
|
||||
@@ -46,6 +46,17 @@ describe("loadWorklist", () => {
|
||||
expect(calls.every((c) => c.headers["X-User-Id"] === "u1" && c.headers["X-Tenant-Slug"] === "acme")).toBe(true);
|
||||
});
|
||||
|
||||
it("sendet mit Workflow-Token nur Authorization und keine X-User-Id", async () => {
|
||||
const seen: Record<string, string>[] = [];
|
||||
const fetchImpl = vi.fn(async (_url: string, init: RequestInit) => {
|
||||
seen.push(init.headers as Record<string, string>);
|
||||
return new Response(JSON.stringify([]), { status: 200 });
|
||||
}) as unknown as typeof fetch;
|
||||
await loadWorklist("http://wf.example", "acme", "u1", fetchImpl, "tok");
|
||||
expect(seen).toHaveLength(3);
|
||||
expect(seen.every((h) => h.Authorization === "Bearer tok" && !("X-User-Id" in h) && !("X-Tenant-Slug" in h))).toBe(true);
|
||||
});
|
||||
|
||||
it("markiert ausgefallene Quellen mit null, ohne die anderen zu verlieren", async () => {
|
||||
const fetchImpl = vi.fn(async (url: string) => {
|
||||
if (url.endsWith("/tasks")) throw new Error("down");
|
||||
|
||||
@@ -39,10 +39,13 @@ export async function loadWorklist(
|
||||
base: string,
|
||||
tenant: string,
|
||||
userId: string,
|
||||
fetchImpl: typeof fetch = fetch
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
workflowToken?: string
|
||||
): Promise<Worklist> {
|
||||
const root = base.replace(/\/$/, "");
|
||||
const headers = { "X-User-Id": userId, "X-Tenant-Slug": tenant, Accept: "application/json" };
|
||||
const headers: Record<string, string> = workflowToken
|
||||
? { Authorization: `Bearer ${workflowToken}`, Accept: "application/json" }
|
||||
: { "X-User-Id": userId, "X-Tenant-Slug": tenant, Accept: "application/json" };
|
||||
const get = async (path: string): Promise<unknown | null> => {
|
||||
try {
|
||||
const res = await fetchImpl(`${root}${path}`, { headers, cache: "no-store" });
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { bearerHeader } from "../../../../../lib/forward";
|
||||
|
||||
function backendURL(): string {
|
||||
const base = process.env.ROUTING_RULES_API_URL;
|
||||
@@ -10,8 +11,9 @@ function backendURL(): string {
|
||||
|
||||
export async function PUT(request: NextRequest, context: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await context.params;
|
||||
const bearer = bearerHeader(request);
|
||||
const userId = request.nextUrl.searchParams.get("userId");
|
||||
if (!userId) {
|
||||
if (!bearer && !userId) {
|
||||
return NextResponse.json({ error: "'userId' ist erforderlich" }, { status: 400 });
|
||||
}
|
||||
const payload = await request.json().catch(() => null);
|
||||
@@ -22,7 +24,7 @@ export async function PUT(request: NextRequest, context: { params: Promise<{ id:
|
||||
try {
|
||||
backendResponse = await fetch(`${backendURL()}/routing-rules/${encodeURIComponent(id)}/enabled`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json", "X-User-Id": userId },
|
||||
headers: { "Content-Type": "application/json", ...(bearer ? { Authorization: bearer } : { "X-User-Id": userId as string }) },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { bearerHeader } from "../../../../../lib/forward";
|
||||
|
||||
function backendURL(): string {
|
||||
const base = process.env.ROUTING_RULES_API_URL;
|
||||
@@ -10,8 +11,9 @@ function backendURL(): string {
|
||||
|
||||
export async function PUT(request: NextRequest, context: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await context.params;
|
||||
const bearer = bearerHeader(request);
|
||||
const userId = request.nextUrl.searchParams.get("userId");
|
||||
if (!userId) {
|
||||
if (!bearer && !userId) {
|
||||
return NextResponse.json({ error: "'userId' ist erforderlich" }, { status: 400 });
|
||||
}
|
||||
const payload = await request.json().catch(() => null);
|
||||
@@ -22,7 +24,7 @@ export async function PUT(request: NextRequest, context: { params: Promise<{ id:
|
||||
try {
|
||||
backendResponse = await fetch(`${backendURL()}/routing-rules/${encodeURIComponent(id)}/priority`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json", "X-User-Id": userId },
|
||||
headers: { "Content-Type": "application/json", ...(bearer ? { Authorization: bearer } : { "X-User-Id": userId as string }) },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
} catch (err) {
|
||||
|
||||
@@ -58,3 +58,26 @@ describe("POST /api/routing-rules", () => {
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("Bearer routing-rules", () => {
|
||||
const originalFetch = global.fetch;
|
||||
const originalEnv = process.env.ROUTING_RULES_API_URL;
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
process.env.ROUTING_RULES_API_URL = originalEnv;
|
||||
});
|
||||
|
||||
it("leitet Authorization weiter und sendet keine X-User-Id", async () => {
|
||||
process.env.ROUTING_RULES_API_URL = "http://backend.local";
|
||||
let h: Headers | undefined;
|
||||
global.fetch = vi.fn(async (_url: string | URL, init?: RequestInit) => {
|
||||
h = new Headers(init?.headers);
|
||||
return new Response(JSON.stringify([]), { status: 200 });
|
||||
}) as typeof fetch;
|
||||
const res = await GET(new NextRequest("http://localhost/api/routing-rules?userId=fremd", { headers: { authorization: "Bearer tok" } }));
|
||||
expect(res.status).toBe(200);
|
||||
expect(h?.get("authorization")).toBe("Bearer tok");
|
||||
expect(h?.get("x-user-id")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { bearerHeader } from "../../../lib/forward";
|
||||
|
||||
function backendURL(): string {
|
||||
const base = process.env.ROUTING_RULES_API_URL;
|
||||
@@ -13,14 +14,15 @@ function requireUserID(request: NextRequest): string | null {
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const bearer = bearerHeader(request);
|
||||
const userId = requireUserID(request);
|
||||
if (!userId) {
|
||||
if (!bearer && !userId) {
|
||||
return NextResponse.json({ error: "'userId' ist erforderlich" }, { status: 400 });
|
||||
}
|
||||
let backendResponse: Response;
|
||||
try {
|
||||
backendResponse = await fetch(`${backendURL()}/routing-rules`, {
|
||||
headers: { "X-User-Id": userId },
|
||||
headers: { ...(bearer ? { Authorization: bearer } : { "X-User-Id": userId as string }) },
|
||||
cache: "no-store",
|
||||
});
|
||||
} catch (err) {
|
||||
@@ -34,8 +36,9 @@ export async function GET(request: NextRequest) {
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const bearer = bearerHeader(request);
|
||||
const userId = requireUserID(request);
|
||||
if (!userId) {
|
||||
if (!bearer && !userId) {
|
||||
return NextResponse.json({ error: "'userId' ist erforderlich" }, { status: 400 });
|
||||
}
|
||||
const payload = await request.json().catch(() => null);
|
||||
@@ -46,7 +49,7 @@ export async function POST(request: NextRequest) {
|
||||
try {
|
||||
backendResponse = await fetch(`${backendURL()}/routing-rules`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", "X-User-Id": userId },
|
||||
headers: { "Content-Type": "application/json", ...(bearer ? { Authorization: bearer } : { "X-User-Id": userId as string }) },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { bearerHeader } from "../../../../lib/forward";
|
||||
|
||||
function backendURL(): string {
|
||||
const base = process.env.ROUTING_RULES_API_URL;
|
||||
@@ -9,8 +10,9 @@ function backendURL(): string {
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const bearer = bearerHeader(request);
|
||||
const userId = request.nextUrl.searchParams.get("userId");
|
||||
if (!userId) {
|
||||
if (!bearer && !userId) {
|
||||
return NextResponse.json({ error: "'userId' ist erforderlich" }, { status: 400 });
|
||||
}
|
||||
const payload = await request.json().catch(() => null);
|
||||
@@ -21,7 +23,7 @@ export async function POST(request: NextRequest) {
|
||||
try {
|
||||
backendResponse = await fetch(`${backendURL()}/routing-rules/test`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", "X-User-Id": userId },
|
||||
headers: { "Content-Type": "application/json", ...(bearer ? { Authorization: bearer } : { "X-User-Id": userId as string }) },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
"use client";
|
||||
|
||||
import { Suspense } from "react";
|
||||
import { Suspense, useEffect, useState } from "react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { TextField } from "@nexarch/shl";
|
||||
import { RuleEditor } from "./RuleEditor";
|
||||
import { bearerEnabled, sessionUserId } from "../lib/http";
|
||||
|
||||
function RulesPage() {
|
||||
const params = useSearchParams();
|
||||
const userId = params.get("user") ?? "";
|
||||
const [sessionUser, setSessionUser] = useState("");
|
||||
useEffect(() => {
|
||||
sessionUserId().then(setSessionUser).catch(() => {});
|
||||
}, []);
|
||||
const userId = bearerEnabled() ? sessionUser : (params.get("user") ?? "");
|
||||
|
||||
return (
|
||||
<main style={{ maxWidth: 1100, margin: "0 auto", padding: 24 }}>
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
// app/api — kein direkter Zugriff auf die Workflow-API vom Client aus,
|
||||
// gleiches Muster wie web/workflow-cases/web/workflow-approvals.
|
||||
|
||||
import { apiFetch } from "./http";
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
constructor(message: string, status: number) {
|
||||
@@ -60,12 +62,12 @@ async function handle<T>(res: Response): Promise<T> {
|
||||
}
|
||||
|
||||
export async function listRules(userId: string): Promise<Rule[]> {
|
||||
const res = await fetch(`/api/routing-rules?userId=${encodeURIComponent(userId)}`, { cache: "no-store" });
|
||||
const res = await apiFetch(`/api/routing-rules?userId=${encodeURIComponent(userId)}`, { cache: "no-store" });
|
||||
return handle<Rule[]>(res);
|
||||
}
|
||||
|
||||
export async function createRule(userId: string, input: { name: string; priority: number; conditions: Condition[]; actions: Action[] }): Promise<Rule> {
|
||||
const res = await fetch(`/api/routing-rules?userId=${encodeURIComponent(userId)}`, {
|
||||
const res = await apiFetch(`/api/routing-rules?userId=${encodeURIComponent(userId)}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(input),
|
||||
@@ -74,7 +76,7 @@ export async function createRule(userId: string, input: { name: string; priority
|
||||
}
|
||||
|
||||
export async function setPriority(userId: string, id: string, priority: number): Promise<void> {
|
||||
const res = await fetch(`/api/routing-rules/${encodeURIComponent(id)}/priority?userId=${encodeURIComponent(userId)}`, {
|
||||
const res = await apiFetch(`/api/routing-rules/${encodeURIComponent(id)}/priority?userId=${encodeURIComponent(userId)}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ priority }),
|
||||
@@ -85,7 +87,7 @@ export async function setPriority(userId: string, id: string, priority: number):
|
||||
}
|
||||
|
||||
export async function setEnabled(userId: string, id: string, enabled: boolean): Promise<void> {
|
||||
const res = await fetch(`/api/routing-rules/${encodeURIComponent(id)}/enabled?userId=${encodeURIComponent(userId)}`, {
|
||||
const res = await apiFetch(`/api/routing-rules/${encodeURIComponent(id)}/enabled?userId=${encodeURIComponent(userId)}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ enabled }),
|
||||
@@ -96,7 +98,7 @@ export async function setEnabled(userId: string, id: string, enabled: boolean):
|
||||
}
|
||||
|
||||
export async function testRule(userId: string, object: Record<string, unknown>, history?: string[]): Promise<TestResult> {
|
||||
const res = await fetch(`/api/routing-rules/test?userId=${encodeURIComponent(userId)}`, {
|
||||
const res = await apiFetch(`/api/routing-rules/test?userId=${encodeURIComponent(userId)}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ object, history }),
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
export function bearerHeader(request: NextRequest): string | null {
|
||||
const auth = request.headers.get("authorization") ?? "";
|
||||
return auth.startsWith("Bearer ") && auth.length > 7 ? auth : null;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { createSession, redirectToLogin, type Session } from "@nexarch/shl";
|
||||
|
||||
let session: Session | undefined;
|
||||
|
||||
export function bearerEnabled(): boolean {
|
||||
return Boolean(process.env.NEXT_PUBLIC_CORE_API_BASE);
|
||||
}
|
||||
|
||||
export function getSession(): Session {
|
||||
if (!session) {
|
||||
session = createSession({
|
||||
coreBase: process.env.NEXT_PUBLIC_CORE_API_BASE as string,
|
||||
module: "workflow",
|
||||
onLoginRequired: () => redirectToLogin(process.env.NEXT_PUBLIC_LOGIN_URL),
|
||||
});
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
export function apiFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
|
||||
return bearerEnabled() ? getSession().fetch(input, init) : fetch(input, init);
|
||||
}
|
||||
|
||||
export async function sessionUserId(): Promise<string> {
|
||||
if (!bearerEnabled()) return "";
|
||||
const s = getSession();
|
||||
await s.token();
|
||||
return s.identity()?.userId ?? "";
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
// unveraendert durch, damit die Oberflaeche 409 (bereits entschieden) und
|
||||
// 403 (nicht zustaendig) korrekt unterscheiden kann.
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { bearerHeader } from "../../../../../lib/forward";
|
||||
|
||||
function backendURL(): string {
|
||||
const base = process.env.WORKFLOW_APPROVALS_API_URL;
|
||||
@@ -14,8 +15,9 @@ function backendURL(): string {
|
||||
|
||||
export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
const bearer = bearerHeader(request);
|
||||
const userId = request.nextUrl.searchParams.get("userId");
|
||||
if (!userId) {
|
||||
if (!bearer && !userId) {
|
||||
return NextResponse.json({ error: "'userId' ist erforderlich" }, { status: 400 });
|
||||
}
|
||||
|
||||
@@ -28,7 +30,7 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{
|
||||
try {
|
||||
backendResponse = await fetch(`${backendURL()}/approvals/${encodeURIComponent(id)}/decide`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", "X-User-Id": userId },
|
||||
headers: { "Content-Type": "application/json", ...(bearer ? { Authorization: bearer } : { "X-User-Id": userId as string }) },
|
||||
body: JSON.stringify({ decision: payload.decision, reason: payload.reason ?? "" }),
|
||||
});
|
||||
} catch (err) {
|
||||
|
||||
@@ -28,4 +28,20 @@ describe("GET /api/approvals", () => {
|
||||
expect(res.status).toBe(200);
|
||||
expect(seenHeader).toBe("alice");
|
||||
});
|
||||
|
||||
it("leitet Bearer weiter und ignoriert userId aus der URL", async () => {
|
||||
process.env.WORKFLOW_APPROVALS_API_URL = "http://backend.local";
|
||||
let seen: Record<string, string> = {};
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn((_url: string, init?: RequestInit) => {
|
||||
seen = init?.headers as Record<string, string>;
|
||||
return Promise.resolve(new Response(JSON.stringify([]), { status: 200 }));
|
||||
})
|
||||
);
|
||||
const res = await GET(new NextRequest("http://localhost/api/approvals?userId=fremd", { headers: { authorization: "Bearer tok" } }));
|
||||
expect(res.status).toBe(200);
|
||||
expect(seen.Authorization).toBe("Bearer tok");
|
||||
expect(seen["X-User-Id"]).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,7 @@
|
||||
// Session-Anbindung (auesserhalb dieser Kachel) gibt der Aufrufer sie
|
||||
// als Query-Parameter mit, wie tenantSlug in web/mail-search.
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { bearerHeader } from "../../../lib/forward";
|
||||
|
||||
function backendURL(): string {
|
||||
const base = process.env.WORKFLOW_APPROVALS_API_URL;
|
||||
@@ -14,15 +15,16 @@ function backendURL(): string {
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const bearer = bearerHeader(request);
|
||||
const userId = request.nextUrl.searchParams.get("userId");
|
||||
if (!userId) {
|
||||
if (!bearer && !userId) {
|
||||
return NextResponse.json({ error: "'userId' ist erforderlich" }, { status: 400 });
|
||||
}
|
||||
|
||||
let backendResponse: Response;
|
||||
try {
|
||||
backendResponse = await fetch(`${backendURL()}/approvals`, {
|
||||
headers: { "X-User-Id": userId },
|
||||
headers: bearer ? { Authorization: bearer } : { "X-User-Id": userId as string },
|
||||
cache: "no-store",
|
||||
});
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
"use client";
|
||||
|
||||
import { Suspense } from "react";
|
||||
import { Suspense, useEffect, useState } from "react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { TextField } from "@nexarch/shl";
|
||||
import { ApprovalList } from "./ApprovalList";
|
||||
import { bearerEnabled, sessionUserId } from "../lib/http";
|
||||
|
||||
function ApprovalsPage() {
|
||||
const params = useSearchParams();
|
||||
const userId = params.get("user") ?? "";
|
||||
const [sessionUser, setSessionUser] = useState("");
|
||||
useEffect(() => {
|
||||
sessionUserId().then(setSessionUser).catch(() => {});
|
||||
}, []);
|
||||
const userId = bearerEnabled() ? sessionUser : (params.get("user") ?? "");
|
||||
|
||||
return (
|
||||
<main style={{ maxWidth: 720, margin: "0 auto", padding: 24 }}>
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
// Client aus (Rolle: "Alle Daten ausschliesslich ueber die oeffentliche
|
||||
// Schnittstelle beziehen").
|
||||
|
||||
import { apiFetch } from "./http";
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
constructor(message: string, status: number) {
|
||||
@@ -22,7 +24,7 @@ export interface ApprovalTask {
|
||||
}
|
||||
|
||||
export async function listApprovals(userId: string): Promise<ApprovalTask[]> {
|
||||
const res = await fetch(`/api/approvals?userId=${encodeURIComponent(userId)}`, { cache: "no-store" });
|
||||
const res = await apiFetch(`/api/approvals?userId=${encodeURIComponent(userId)}`, { cache: "no-store" });
|
||||
const body = await res.json().catch(() => null);
|
||||
if (!res.ok) {
|
||||
throw new ApiError(body?.error ?? `Freigaben konnten nicht geladen werden (${res.status})`, res.status);
|
||||
@@ -38,7 +40,7 @@ export async function decideApproval(
|
||||
decision: Decision,
|
||||
reason: string
|
||||
): Promise<ApprovalTask> {
|
||||
const res = await fetch(`/api/approvals/${encodeURIComponent(id)}/decide?userId=${encodeURIComponent(userId)}`, {
|
||||
const res = await apiFetch(`/api/approvals/${encodeURIComponent(id)}/decide?userId=${encodeURIComponent(userId)}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ decision, reason }),
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
export function bearerHeader(request: NextRequest): string | null {
|
||||
const auth = request.headers.get("authorization") ?? "";
|
||||
return auth.startsWith("Bearer ") && auth.length > 7 ? auth : null;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { createSession, redirectToLogin, type Session } from "@nexarch/shl";
|
||||
|
||||
let session: Session | undefined;
|
||||
|
||||
export function bearerEnabled(): boolean {
|
||||
return Boolean(process.env.NEXT_PUBLIC_CORE_API_BASE);
|
||||
}
|
||||
|
||||
export function getSession(): Session {
|
||||
if (!session) {
|
||||
session = createSession({
|
||||
coreBase: process.env.NEXT_PUBLIC_CORE_API_BASE as string,
|
||||
module: "workflow",
|
||||
onLoginRequired: () => redirectToLogin(process.env.NEXT_PUBLIC_LOGIN_URL),
|
||||
});
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
export function apiFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
|
||||
return bearerEnabled() ? getSession().fetch(input, init) : fetch(input, init);
|
||||
}
|
||||
|
||||
export async function sessionUserId(): Promise<string> {
|
||||
if (!bearerEnabled()) return "";
|
||||
const s = getSession();
|
||||
await s.token();
|
||||
return s.identity()?.userId ?? "";
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { bearerHeader } from "../../../../../lib/forward";
|
||||
|
||||
function backendURL(): string {
|
||||
const base = process.env.WORKFLOW_CASES_API_URL;
|
||||
@@ -10,15 +11,16 @@ function backendURL(): string {
|
||||
|
||||
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
const bearer = bearerHeader(request);
|
||||
const userId = request.nextUrl.searchParams.get("userId");
|
||||
if (!userId) {
|
||||
if (!bearer && !userId) {
|
||||
return NextResponse.json({ error: "'userId' ist erforderlich" }, { status: 400 });
|
||||
}
|
||||
|
||||
let backendResponse: Response;
|
||||
try {
|
||||
backendResponse = await fetch(`${backendURL()}/cases/${encodeURIComponent(id)}/overview`, {
|
||||
headers: { "X-User-Id": userId },
|
||||
headers: { ...(bearer ? { Authorization: bearer } : { "X-User-Id": userId as string }) },
|
||||
cache: "no-store",
|
||||
});
|
||||
} catch (err) {
|
||||
|
||||
@@ -39,3 +39,26 @@ describe("GET /api/cases", () => {
|
||||
expect(capturedHeaders?.get("X-User-Id")).toBe("alice");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("Bearer cases", () => {
|
||||
const originalFetch = global.fetch;
|
||||
const originalEnv = process.env.WORKFLOW_CASES_API_URL;
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
process.env.WORKFLOW_CASES_API_URL = originalEnv;
|
||||
});
|
||||
|
||||
it("leitet Authorization weiter und sendet keine X-User-Id", async () => {
|
||||
process.env.WORKFLOW_CASES_API_URL = "http://backend.local";
|
||||
let h: Headers | undefined;
|
||||
global.fetch = vi.fn(async (_url: string | URL, init?: RequestInit) => {
|
||||
h = new Headers(init?.headers);
|
||||
return new Response(JSON.stringify([]), { status: 200 });
|
||||
}) as typeof fetch;
|
||||
const res = await GET(new NextRequest("http://localhost/api/cases?userId=fremd", { headers: { authorization: "Bearer tok" } }));
|
||||
expect(res.status).toBe(200);
|
||||
expect(h?.get("authorization")).toBe("Bearer tok");
|
||||
expect(h?.get("x-user-id")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { bearerHeader } from "../../../lib/forward";
|
||||
|
||||
function backendURL(): string {
|
||||
const base = process.env.WORKFLOW_CASES_API_URL;
|
||||
@@ -9,8 +10,9 @@ function backendURL(): string {
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const bearer = bearerHeader(request);
|
||||
const userId = request.nextUrl.searchParams.get("userId");
|
||||
if (!userId) {
|
||||
if (!bearer && !userId) {
|
||||
return NextResponse.json({ error: "'userId' ist erforderlich" }, { status: 400 });
|
||||
}
|
||||
const status = request.nextUrl.searchParams.get("status") ?? "";
|
||||
@@ -22,7 +24,7 @@ export async function GET(request: NextRequest) {
|
||||
let backendResponse: Response;
|
||||
try {
|
||||
backendResponse = await fetch(`${backendURL()}/cases?${params.toString()}`, {
|
||||
headers: { "X-User-Id": userId },
|
||||
headers: { ...(bearer ? { Authorization: bearer } : { "X-User-Id": userId as string }) },
|
||||
cache: "no-store",
|
||||
});
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { bearerHeader } from "../../../../../lib/forward";
|
||||
|
||||
function backendURL(): string {
|
||||
const base = process.env.WORKFLOW_CASES_API_URL;
|
||||
@@ -10,8 +11,9 @@ function backendURL(): string {
|
||||
|
||||
export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
const bearer = bearerHeader(request);
|
||||
const userId = request.nextUrl.searchParams.get("userId");
|
||||
if (!userId) {
|
||||
if (!bearer && !userId) {
|
||||
return NextResponse.json({ error: "'userId' ist erforderlich" }, { status: 400 });
|
||||
}
|
||||
const payload = await request.json().catch(() => null);
|
||||
@@ -23,7 +25,7 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{
|
||||
try {
|
||||
backendResponse = await fetch(`${backendURL()}/reminders/${encodeURIComponent(id)}/move`, {
|
||||
method: "POST",
|
||||
headers: { "X-User-Id": userId, "Content-Type": "application/json" },
|
||||
headers: { ...(bearer ? { Authorization: bearer } : { "X-User-Id": userId as string }), "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ target: payload.target }),
|
||||
});
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { bearerHeader } from "../../../../lib/forward";
|
||||
|
||||
function backendURL(): string {
|
||||
const base = process.env.WORKFLOW_CASES_API_URL;
|
||||
@@ -9,15 +10,16 @@ function backendURL(): string {
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const bearer = bearerHeader(request);
|
||||
const userId = request.nextUrl.searchParams.get("userId");
|
||||
if (!userId) {
|
||||
if (!bearer && !userId) {
|
||||
return NextResponse.json({ error: "'userId' ist erforderlich" }, { status: 400 });
|
||||
}
|
||||
|
||||
let backendResponse: Response;
|
||||
try {
|
||||
backendResponse = await fetch(`${backendURL()}/reminders/kanban`, {
|
||||
headers: { "X-User-Id": userId },
|
||||
headers: { ...(bearer ? { Authorization: bearer } : { "X-User-Id": userId as string }) },
|
||||
cache: "no-store",
|
||||
});
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,16 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import { Suspense, useState } from "react";
|
||||
import { Suspense, useEffect, useState } from "react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { TextField } from "@nexarch/shl";
|
||||
import { CaseOverview } from "./CaseOverview";
|
||||
import { ReminderKanban } from "./ReminderKanban";
|
||||
import { bearerEnabled, sessionUserId } from "../lib/http";
|
||||
|
||||
type Tab = "cases" | "kanban";
|
||||
|
||||
function CasesPage() {
|
||||
const params = useSearchParams();
|
||||
const userId = params.get("user") ?? "";
|
||||
const [sessionUser, setSessionUser] = useState("");
|
||||
useEffect(() => {
|
||||
sessionUserId().then(setSessionUser).catch(() => {});
|
||||
}, []);
|
||||
const userId = bearerEnabled() ? sessionUser : (params.get("user") ?? "");
|
||||
const [tab, setTab] = useState<Tab>("cases");
|
||||
|
||||
return (
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
// (Rolle: "Alle Daten ausschliesslich ueber die oeffentliche
|
||||
// Schnittstelle beziehen"), gleiches Muster wie web/workflow-approvals.
|
||||
|
||||
import { apiFetch } from "./http";
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
constructor(message: string, status: number) {
|
||||
@@ -72,24 +74,24 @@ export async function listCases(userId: string, status: string, responsible: str
|
||||
const params = new URLSearchParams({ userId });
|
||||
if (status) params.set("status", status);
|
||||
if (responsible) params.set("responsible", responsible);
|
||||
const res = await fetch(`/api/cases?${params.toString()}`, { cache: "no-store" });
|
||||
const res = await apiFetch(`/api/cases?${params.toString()}`, { cache: "no-store" });
|
||||
return parse<Case[]>(res, "Akten konnten nicht geladen werden");
|
||||
}
|
||||
|
||||
export async function getCaseDetail(userId: string, id: string): Promise<CaseDetail> {
|
||||
const res = await fetch(`/api/cases/${encodeURIComponent(id)}/overview?userId=${encodeURIComponent(userId)}`, {
|
||||
const res = await apiFetch(`/api/cases/${encodeURIComponent(id)}/overview?userId=${encodeURIComponent(userId)}`, {
|
||||
cache: "no-store",
|
||||
});
|
||||
return parse<CaseDetail>(res, "Akte konnte nicht geladen werden");
|
||||
}
|
||||
|
||||
export async function listKanban(userId: string): Promise<KanbanItem[]> {
|
||||
const res = await fetch(`/api/reminders/kanban?userId=${encodeURIComponent(userId)}`, { cache: "no-store" });
|
||||
const res = await apiFetch(`/api/reminders/kanban?userId=${encodeURIComponent(userId)}`, { cache: "no-store" });
|
||||
return parse<KanbanItem[]>(res, "Wiedervorlagen konnten nicht geladen werden");
|
||||
}
|
||||
|
||||
export async function moveReminder(userId: string, id: string, target: KanbanColumn): Promise<void> {
|
||||
const res = await fetch(`/api/reminders/${encodeURIComponent(id)}/move?userId=${encodeURIComponent(userId)}`, {
|
||||
const res = await apiFetch(`/api/reminders/${encodeURIComponent(id)}/move?userId=${encodeURIComponent(userId)}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ target }),
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
export function bearerHeader(request: NextRequest): string | null {
|
||||
const auth = request.headers.get("authorization") ?? "";
|
||||
return auth.startsWith("Bearer ") && auth.length > 7 ? auth : null;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { createSession, redirectToLogin, type Session } from "@nexarch/shl";
|
||||
|
||||
let session: Session | undefined;
|
||||
|
||||
export function bearerEnabled(): boolean {
|
||||
return Boolean(process.env.NEXT_PUBLIC_CORE_API_BASE);
|
||||
}
|
||||
|
||||
export function getSession(): Session {
|
||||
if (!session) {
|
||||
session = createSession({
|
||||
coreBase: process.env.NEXT_PUBLIC_CORE_API_BASE as string,
|
||||
module: "workflow",
|
||||
onLoginRequired: () => redirectToLogin(process.env.NEXT_PUBLIC_LOGIN_URL),
|
||||
});
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
export function apiFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
|
||||
return bearerEnabled() ? getSession().fetch(input, init) : fetch(input, init);
|
||||
}
|
||||
|
||||
export async function sessionUserId(): Promise<string> {
|
||||
if (!bearerEnabled()) return "";
|
||||
const s = getSession();
|
||||
await s.token();
|
||||
return s.identity()?.userId ?? "";
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { bearerHeader } from "../../../../../lib/forward";
|
||||
|
||||
function backendURL(): string {
|
||||
const base = process.env.WORKFLOW_TASKS_API_URL;
|
||||
@@ -10,9 +11,10 @@ function backendURL(): string {
|
||||
|
||||
export async function PATCH(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
const bearer = bearerHeader(request);
|
||||
const userId = request.nextUrl.searchParams.get("userId");
|
||||
const tenantSlug = request.nextUrl.searchParams.get("tenant");
|
||||
if (!userId || !tenantSlug) {
|
||||
if (!bearer && (!userId || !tenantSlug)) {
|
||||
return NextResponse.json({ error: "'userId' und 'tenant' sind erforderlich" }, { status: 400 });
|
||||
}
|
||||
const payload = await request.json().catch(() => null);
|
||||
@@ -24,7 +26,7 @@ export async function PATCH(request: NextRequest, { params }: { params: Promise<
|
||||
try {
|
||||
backendResponse = await fetch(`${backendURL()}/tasks/${encodeURIComponent(id)}/status`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json", "X-User-Id": userId, "X-Tenant-Slug": tenantSlug },
|
||||
headers: { "Content-Type": "application/json", ...(bearer ? { Authorization: bearer } : { "X-User-Id": userId as string, "X-Tenant-Slug": tenantSlug as string }) },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
} catch (err) {
|
||||
|
||||
@@ -41,4 +41,16 @@ describe("GET /api/tasks", () => {
|
||||
const res = await GET(req);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
it("leitet Bearer weiter, auch ohne userId/tenant, und sendet keine X-User-Id", async () => {
|
||||
let capturedHeaders: Headers | undefined;
|
||||
global.fetch = vi.fn(async (_url: string | URL, init?: RequestInit) => {
|
||||
capturedHeaders = new Headers(init?.headers);
|
||||
return new Response(JSON.stringify([]), { status: 200 });
|
||||
}) as typeof fetch;
|
||||
const res = await GET(new NextRequest("http://localhost/api/tasks", { headers: { authorization: "Bearer tok" } }));
|
||||
expect(res.status).toBe(200);
|
||||
expect(capturedHeaders?.get("authorization")).toBe("Bearer tok");
|
||||
expect(capturedHeaders?.get("x-user-id")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@
|
||||
// (app/api/case-context/route.ts) als Query-Parameter mitgegeben, bis zu
|
||||
// einer zentralen Session-Anbindung.
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { bearerHeader } from "../../../lib/forward";
|
||||
|
||||
function backendURL(): string {
|
||||
const base = process.env.WORKFLOW_TASKS_API_URL;
|
||||
@@ -13,16 +14,17 @@ function backendURL(): string {
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const bearer = bearerHeader(request);
|
||||
const userId = request.nextUrl.searchParams.get("userId");
|
||||
const tenantSlug = request.nextUrl.searchParams.get("tenant");
|
||||
if (!userId || !tenantSlug) {
|
||||
if (!bearer && (!userId || !tenantSlug)) {
|
||||
return NextResponse.json({ error: "'userId' und 'tenant' sind erforderlich" }, { status: 400 });
|
||||
}
|
||||
|
||||
let backendResponse: Response;
|
||||
try {
|
||||
backendResponse = await fetch(`${backendURL()}/tasks`, {
|
||||
headers: { "X-User-Id": userId, "X-Tenant-Slug": tenantSlug },
|
||||
headers: bearer ? { Authorization: bearer } : { "X-User-Id": userId as string, "X-Tenant-Slug": tenantSlug as string },
|
||||
cache: "no-store",
|
||||
});
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import { Suspense } from "react";
|
||||
import { Suspense, useEffect, useState } from "react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { TextField } from "@nexarch/shl";
|
||||
import { TaskBoard } from "./TaskBoard";
|
||||
import { bearerEnabled, getSession, sessionUserId } from "../lib/http";
|
||||
|
||||
function TasksPage() {
|
||||
const params = useSearchParams();
|
||||
const userId = params.get("user") ?? "";
|
||||
const tenantSlug = params.get("tenant") ?? "";
|
||||
const [sessionIdentity, setSessionIdentity] = useState({ userId: "", tenant: "" });
|
||||
useEffect(() => {
|
||||
sessionUserId()
|
||||
.then((userId) => setSessionIdentity({ userId, tenant: getSession().identity()?.tenant ?? "" }))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
const userId = bearerEnabled() ? sessionIdentity.userId : (params.get("user") ?? "");
|
||||
const tenantSlug = bearerEnabled() ? sessionIdentity.tenant : (params.get("tenant") ?? "");
|
||||
|
||||
return (
|
||||
<main style={{ maxWidth: 1100, margin: "0 auto", padding: 24 }}>
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
// app/api — kein direkter Zugriff auf workflow/internal/taskapi vom Client
|
||||
// aus, gleiches Muster wie web/routing-rules/web/workflow-cases.
|
||||
|
||||
import { apiFetch } from "./http";
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
constructor(message: string, status: number) {
|
||||
@@ -43,7 +45,7 @@ async function handle<T>(res: Response): Promise<T> {
|
||||
}
|
||||
|
||||
export async function listTasks(userId: string, tenantSlug: string): Promise<Task[]> {
|
||||
const res = await fetch(
|
||||
const res = await apiFetch(
|
||||
`/api/tasks?userId=${encodeURIComponent(userId)}&tenant=${encodeURIComponent(tenantSlug)}`,
|
||||
{ cache: "no-store" }
|
||||
);
|
||||
@@ -56,7 +58,7 @@ export async function setTaskStatus(
|
||||
id: string,
|
||||
status: TaskStatus
|
||||
): Promise<void> {
|
||||
const res = await fetch(
|
||||
const res = await apiFetch(
|
||||
`/api/tasks/${encodeURIComponent(id)}/status?userId=${encodeURIComponent(userId)}&tenant=${encodeURIComponent(tenantSlug)}`,
|
||||
{
|
||||
method: "PATCH",
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
export function bearerHeader(request: NextRequest): string | null {
|
||||
const auth = request.headers.get("authorization") ?? "";
|
||||
return auth.startsWith("Bearer ") && auth.length > 7 ? auth : null;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { createSession, redirectToLogin, type Session } from "@nexarch/shl";
|
||||
|
||||
let session: Session | undefined;
|
||||
|
||||
export function bearerEnabled(): boolean {
|
||||
return Boolean(process.env.NEXT_PUBLIC_CORE_API_BASE);
|
||||
}
|
||||
|
||||
export function getSession(): Session {
|
||||
if (!session) {
|
||||
session = createSession({
|
||||
coreBase: process.env.NEXT_PUBLIC_CORE_API_BASE as string,
|
||||
module: "workflow",
|
||||
onLoginRequired: () => redirectToLogin(process.env.NEXT_PUBLIC_LOGIN_URL),
|
||||
});
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
export function apiFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
|
||||
return bearerEnabled() ? getSession().fetch(input, init) : fetch(input, init);
|
||||
}
|
||||
|
||||
export async function sessionUserId(): Promise<string> {
|
||||
if (!bearerEnabled()) return "";
|
||||
const s = getSession();
|
||||
await s.token();
|
||||
return s.identity()?.userId ?? "";
|
||||
}
|
||||
Reference in new issue
Block a user