Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 | 5x 5x 5x 5x 54x 36x 54x 2x 52x 84x 84x 84x 84x 84x 84x 84x 84x 84x 28x 1x 30x 30x 84x 30x 26x 26x 2x 2x 26x 26x 84x 2x 82x 28x 1x 27x 2x 14x 20x 14x 1x 1x 54x 84x 84x 84x 84x 84x 84x 84x 84x 19x 12x 126x 126x 180x 126x 5x 5x 5x 5x 1x 1x 4x 5x | "use client";
import { signIn, signOut } from "next-auth/react";
import {
LogIn,
LogOut,
Settings,
Shield,
ShieldCheck,
User,
Users,
} from "lucide-react";
import { useState, useRef, useEffect } from "react";
import { ROLE_LABELS, DEMO_PERSONAS, deriveParticipantType } from "@/lib/auth";
import {
useDemoPersona,
setDemoPersona,
clearDemoPersona,
} from "@/lib/use-demo-persona";
import { useTabSession, markSessionSwitch } from "@/lib/use-tab-session";
import { BuildInfo } from "@/components/BuildInfo";
/** Badge colours per role code — uses semantic CSS tokens, adapts to light/dark. */
const ROLE_BADGE: Record<string, string> = {
EDC_ADMIN: "bg-[var(--role-admin-bg)] text-[var(--role-admin-text)]",
EDC_USER_PARTICIPANT:
"bg-[var(--role-holder-bg)] text-[var(--role-holder-text)]",
HDAB_AUTHORITY: "bg-[var(--role-hdab-bg)] text-[var(--role-hdab-text)]",
DATA_HOLDER: "bg-[var(--role-holder-bg)] text-[var(--role-holder-text)]",
DATA_USER: "bg-[var(--role-user-bg)] text-[var(--role-user-text)]",
TRUST_CENTER_OPERATOR:
"bg-[var(--role-trust-bg)] text-[var(--role-trust-text)]",
PATIENT: "bg-[var(--role-patient-bg)] text-[var(--role-patient-text)]",
};
/** Dropdown border accent per primary role. */
const ROLE_ACCENT: Record<string, string> = {
EDC_ADMIN: "border-[var(--role-admin-border)]",
HDAB_AUTHORITY: "border-[var(--role-hdab-border)]",
DATA_HOLDER: "border-[var(--role-holder-border)]",
DATA_USER: "border-[var(--role-user-border)]",
TRUST_CENTER_OPERATOR: "border-[var(--role-trust-border)]",
EDC_USER_PARTICIPANT: "border-[var(--role-holder-border)]",
PATIENT: "border-[var(--role-patient-border)]",
};
/** Shield icon colour per primary role. */
const ROLE_SHIELD: Record<string, string> = {
EDC_ADMIN: "text-[var(--role-admin-text)]",
HDAB_AUTHORITY: "text-[var(--role-hdab-text)]",
DATA_HOLDER: "text-[var(--role-holder-text)]",
DATA_USER: "text-[var(--role-user-text)]",
TRUST_CENTER_OPERATOR: "text-[var(--role-trust-text)]",
EDC_USER_PARTICIPANT: "text-[var(--text-secondary)]",
PATIENT: "text-[var(--role-patient-text)]",
};
const IS_STATIC = process.env.NEXT_PUBLIC_STATIC_EXPORT === "true";
/**
* Returns the most meaningful roles to display.
* Hides EDC_USER_PARTICIPANT when a more specific sub-role is present.
*/
function displayRolesFor(roles: string[]): string[] {
const specific = roles.filter((r) =>
[
"EDC_ADMIN",
"HDAB_AUTHORITY",
"DATA_HOLDER",
"DATA_USER",
"TRUST_CENTER_OPERATOR",
"PATIENT",
].includes(r),
);
if (specific.length === 0 && roles.includes("EDC_USER_PARTICIPANT")) {
return ["EDC_USER_PARTICIPANT"];
}
return specific;
}
/**
* Switch to a different Keycloak user.
* Must sign out from BOTH NextAuth AND Keycloak itself — otherwise Keycloak's
* SSO session cookie auto-authenticates the same user on the next signIn().
*
* After logout, redirects to NextAuth's signIn with login_hint so Keycloak
* pre-fills the username field for the target user.
*/
function switchPersona(
username: string,
_personaId: string,
onClose: () => void,
keycloakConfig: { publicUrl: string; clientId: string } | null,
) {
onClose();
// Fall back to same-origin "/" if the runtime config hasn't loaded yet —
// never bake in localhost since this code runs in the browser against the
// production deployment.
const keycloakPublicUrl = keycloakConfig?.publicUrl;
const clientId = keycloakConfig?.clientId ?? "health-dataspace-ui";
if (!keycloakPublicUrl) {
// Config not loaded yet — fall back to plain NextAuth signOut.
signOut({ callbackUrl: "/auth/switch" });
return;
}
// Store the target username so we can pass it as login_hint after logout
sessionStorage.setItem("switch_to_user", username);
// Mark this tab as intentionally switching — clears the session snapshot
// so the new Keycloak session is accepted after redirect.
markSessionSwitch();
// Re-show the demo password warning for the new user
sessionStorage.removeItem("demo-password-banner-dismissed");
// Sign out from NextAuth first, then redirect to Keycloak's logout endpoint.
// The post_logout_redirect_uri sends the user to /auth/switch which triggers
// a new sign-in with login_hint.
signOut({ redirect: false }).then(() => {
const returnUrl = window.location.origin + "/auth/switch";
const logoutUrl = `${keycloakPublicUrl}/protocol/openid-connect/logout?post_logout_redirect_uri=${encodeURIComponent(
returnUrl,
)}&client_id=${clientId}`;
window.location.href = logoutUrl;
});
}
export default function UserMenu() {
// Tab-scoped session: immune to cross-tab cookie changes in live mode.
const { session: tabSession, status: tabStatus } = useTabSession();
// Always call useDemoPersona — hook rules require unconditional calls.
const demoPersona = useDemoPersona();
const demoSession =
IS_STATIC && demoPersona
? {
user: {
name: demoPersona.username,
email: `${demoPersona.username}@demo.ehds.eu`,
},
roles: [...demoPersona.roles],
}
: null;
// In static mode: use demo persona (null = signed out). In live mode: use tab-scoped snapshot.
const session = IS_STATIC
? demoSession
: tabSession
? {
user: { name: tabSession.username, email: tabSession.email },
roles: tabSession.roles,
}
: null;
const status = IS_STATIC
? demoPersona
? "authenticated"
: "unauthenticated"
: tabStatus;
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
// Runtime Keycloak config — fetched once on mount from /api/auth/keycloak-config.
// We can't use NEXT_PUBLIC_* env vars because they're baked in at `npm run build`
// time inside the Docker image and our build doesn't pass them as build args.
const [keycloakConfig, setKeycloakConfig] = useState<{
publicUrl: string;
clientId: string;
} | null>(null);
useEffect(() => {
function handleClick(e: MouseEvent) {
if (ref.current && !ref.current.contains(e.target as Node)) {
setOpen(false);
}
}
document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, []);
useEffect(() => {
if (IS_STATIC) return;
let cancelled = false;
fetch("/api/keycloak-config")
.then((r) => (r.ok ? r.json() : null))
.then((cfg) => {
Eif (!cancelled && cfg) setKeycloakConfig(cfg);
})
.catch(() => {
/* leave null — sign-out falls back to NextAuth-only */
});
return () => {
cancelled = true;
};
}, []);
if (status === "loading") {
return (
<div className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-[var(--text-secondary)]">
<User size={15} />
<span className="animate-pulse">…</span>
</div>
);
}
if (!session) {
if (IS_STATIC) {
// Static demo: show persona picker dropdown
return (
<div ref={ref} className="relative">
<button
onClick={() => setOpen(!open)}
className="flex items-center gap-1.5 px-3 py-1.5 rounded text-sm text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--surface-2)] transition-colors"
>
<LogIn size={15} />
Sign in
</button>
{open && (
<div className="absolute right-0 top-full mt-1 w-64 bg-[var(--surface-2)] border border-[var(--border)] rounded-lg shadow-xl z-50">
<div className="px-3 pt-2 pb-1 flex items-center gap-1.5">
<Users size={11} className="text-[var(--text-secondary)]" />
<span className="text-[10px] text-[var(--text-secondary)] uppercase tracking-wide font-semibold">
Choose a demo persona
</span>
</div>
<div className="px-2 pb-2 space-y-0.5">
{DEMO_PERSONAS.map((persona) => {
const pRole = [...persona.roles].find((r) =>
[
"EDC_ADMIN",
"HDAB_AUTHORITY",
"DATA_HOLDER",
"DATA_USER",
"PATIENT",
].includes(r),
);
return (
<button
key={persona.username}
onClick={() => {
setDemoPersona(persona.username);
setOpen(false);
}}
className="flex items-center gap-2 w-full px-2 py-1.5 rounded text-left hover:bg-[var(--surface-2)] cursor-pointer transition-colors"
>
<span
className={`inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded font-medium shrink-0 ${
ROLE_BADGE[pRole ?? ""] ??
"bg-gray-600 text-[var(--text-primary)]"
}`}
>
<Shield size={8} />
{ROLE_LABELS[pRole ?? ""] ?? pRole}
</span>
<span className="font-mono text-xs truncate text-[var(--text-primary)]">
{persona.username}
</span>
</button>
);
})}
</div>
<BuildInfo />
</div>
)}
</div>
);
}
// Live mode: show persona picker dropdown (same as static mode but triggers Keycloak sign-in)
return (
<div ref={ref} className="relative">
<button
onClick={() => setOpen(!open)}
className="flex items-center gap-1.5 px-3 py-1.5 rounded text-sm text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--surface-2)] transition-colors"
>
<LogIn size={15} />
Sign in
</button>
{open && (
<div className="absolute right-0 top-full mt-1 w-64 bg-[var(--surface-2)] border border-[var(--border)] rounded-lg shadow-xl z-50">
<div className="px-3 pt-2 pb-1 flex items-center gap-1.5">
<Users size={11} className="text-[var(--text-secondary)]" />
<span className="text-[10px] text-[var(--text-secondary)] uppercase tracking-wide font-semibold">
Returning users
</span>
</div>
<div className="px-2 pb-2 space-y-0.5">
{DEMO_PERSONAS.map((persona) => {
const pRole = [...persona.roles].find((r) =>
[
"EDC_ADMIN",
"HDAB_AUTHORITY",
"DATA_HOLDER",
"DATA_USER",
"PATIENT",
].includes(r),
);
return (
<button
key={persona.username}
onClick={() => {
setOpen(false);
signIn(
"keycloak",
{ callbackUrl: `/graph?persona=${persona.personaId}` },
{ login_hint: persona.username },
);
}}
className="flex items-center gap-2 w-full px-2 py-1.5 rounded text-left hover:bg-[var(--surface-2)] cursor-pointer transition-colors"
>
<span
className={`inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded font-medium shrink-0 ${
ROLE_BADGE[pRole ?? ""] ??
"bg-gray-600 text-[var(--text-primary)]"
}`}
>
<Shield size={8} />
{ROLE_LABELS[pRole ?? ""] ?? pRole}
</span>
<span className="font-mono text-xs truncate text-[var(--text-primary)]">
{persona.username}
</span>
</button>
);
})}
</div>
<div className="p-2 border-t border-[var(--border)]">
<a
href="/auth/signin"
onClick={() => setOpen(false)}
className="flex items-center justify-center gap-1.5 w-full px-3 py-2 text-xs text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--surface-2)] rounded transition-colors"
>
<ShieldCheck size={12} />
All users & details
</a>
</div>
<BuildInfo />
</div>
)}
</div>
);
}
const roles = (session as { roles?: string[] }).roles ?? [];
const username = session.user?.name ?? session.user?.email ?? "";
const shownRoles = displayRolesFor(roles);
const primaryRole = shownRoles[0] ?? "EDC_USER_PARTICIPANT";
// Derive a friendly participant type for display
const _participantType = deriveParticipantType(roles, username);
// Short role label for the nav bar chip
const navLabel = ROLE_LABELS[primaryRole] ?? username;
const accentClass = ROLE_ACCENT[primaryRole] ?? "border-gray-600";
const shieldClass =
ROLE_SHIELD[primaryRole] ?? "text-[var(--text-secondary)]";
return (
<div ref={ref} className="relative">
{/* ── Nav bar button ── */}
<button
onClick={() => setOpen(!open)}
className="flex items-center gap-1.5 px-2.5 py-1.5 rounded text-sm text-[var(--text-primary)] hover:text-[var(--text-primary)] hover:bg-[var(--surface-2)] transition-colors"
aria-label="User menu"
>
<Shield size={14} className={shieldClass} />
<span className="max-w-[90px] truncate text-xs font-medium">
{username}
{IS_STATIC && (
<span className="ml-1 text-[9px] text-amber-400">(demo)</span>
)}
</span>
{/* Role chip — hidden on very small screens */}
<span
className={`hidden sm:inline-block text-[10px] px-1.5 py-0.5 rounded font-medium ${
ROLE_BADGE[primaryRole] ?? "bg-gray-600 text-[var(--text-primary)]"
}`}
>
{navLabel}
</span>
</button>
{/* ── Dropdown panel ── */}
{open && (
<div
className={`absolute right-0 top-full mt-1 w-72 bg-[var(--surface-2)] border rounded-lg shadow-xl z-50 ${accentClass}`}
>
{/* Identity block */}
<div className="p-3 border-b border-[var(--border)]">
<p className="text-sm text-[var(--text-primary)] font-semibold truncate">
{username}
{IS_STATIC && (
<span className="ml-1.5 text-[10px] text-amber-400 font-normal">
demo mode
</span>
)}
</p>
<p className="text-xs text-[var(--text-secondary)] truncate mt-0.5">
{session.user?.email}
</p>
{/* Role badges */}
<div className="flex flex-wrap gap-1 mt-2">
{shownRoles.map((role) => (
<span
key={role}
className={`inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded border font-medium ${
ROLE_BADGE[role] ?? "bg-gray-600 text-[var(--text-primary)]"
} border-transparent`}
>
<Shield size={9} />
{ROLE_LABELS[role] ?? role}
</span>
))}
</div>
</div>
{/* Settings link — hidden for PATIENT (no DCP business credentials) */}
{!roles.includes("PATIENT") && (
<div className="p-2 border-b border-[var(--border)]">
<a
href="/settings"
onClick={() => setOpen(false)}
className="flex items-center gap-2 w-full px-3 py-2 rounded text-sm text-[var(--text-primary)] hover:bg-[var(--surface-2)] transition-colors"
>
<Settings size={14} />
<span className="font-medium">Settings</span>
</a>
</div>
)}
{/* Persona switcher — Keycloak in live mode, localStorage in static demo */}
<div className="border-t border-[var(--border)]">
<div className="px-3 pt-2 pb-1 flex items-center gap-1.5">
<Users size={11} className="text-[var(--text-secondary)]" />
<span className="text-[10px] text-[var(--text-secondary)] uppercase tracking-wide font-semibold">
{IS_STATIC ? "Switch demo persona" : "Returning users"}
</span>
</div>
<div className="px-2 pb-2 space-y-0.5">
{DEMO_PERSONAS.map((persona) => {
const isActive = persona.username === username;
const primaryRole = [...persona.roles].find((r) =>
[
"EDC_ADMIN",
"HDAB_AUTHORITY",
"DATA_HOLDER",
"DATA_USER",
"PATIENT",
].includes(r),
);
return (
<button
key={persona.username}
disabled={isActive}
onClick={() => {
if (IS_STATIC) {
setDemoPersona(persona.username);
setOpen(false);
} else {
switchPersona(
persona.username,
persona.personaId,
() => setOpen(false),
keycloakConfig,
);
}
}}
className={`flex items-center gap-2 w-full px-2 py-1.5 rounded text-left transition-colors ${
isActive
? "bg-[var(--surface-2)] cursor-default"
: "hover:bg-[var(--surface-2)] cursor-pointer"
}`}
>
<span
className={`inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded font-medium shrink-0 ${
ROLE_BADGE[primaryRole ?? ""] ??
"bg-gray-600 text-[var(--text-primary)]"
}`}
>
<Shield size={8} />
{ROLE_LABELS[primaryRole ?? ""] ?? primaryRole}
</span>
<span
className={`font-mono text-xs truncate ${
isActive
? "text-[var(--accent)] font-semibold"
: "text-[var(--text-primary)]"
}`}
>
{persona.username}
</span>
{isActive && (
<span className="ml-auto text-[9px] text-[var(--text-secondary)] shrink-0">
active
</span>
)}
</button>
);
})}
</div>
</div>
{/* Sign out + build info — inline on one row to save vertical
space. Sign out stays left-aligned; BuildInfo right-aligned. */}
<div className="flex items-center justify-between gap-2 p-2 border-t border-[var(--border)]">
<button
onClick={() => {
setOpen(false);
sessionStorage.removeItem("demo-password-banner-dismissed");
// Clear the tab session snapshot so re-login gets a fresh one
markSessionSwitch();
if (IS_STATIC) {
clearDemoPersona();
return;
}
const logoutUrl = keycloakConfig?.publicUrl
? `${
keycloakConfig.publicUrl
}/protocol/openid-connect/logout?post_logout_redirect_uri=${encodeURIComponent(
window.location.origin,
)}&client_id=${keycloakConfig.clientId}`
: undefined;
signOut({ callbackUrl: logoutUrl ?? "/" });
}}
className="flex items-center gap-2 px-3 py-2 text-sm text-red-400 hover:bg-[var(--surface-2)] rounded transition-colors"
>
<LogOut size={14} />
Sign out
</button>
<BuildInfo />
</div>
</div>
)}
</div>
);
}
|