1
0
forked from baron/baron-sso

feat(adminfront): add user profile dropdown and enhance session sync

This commit is contained in:
2026-03-03 12:56:57 +09:00
parent 86ef9c6f60
commit 1c3985ce19
6 changed files with 146 additions and 26 deletions

View File

@@ -1,6 +1,8 @@
import { useQuery } from "@tanstack/react-query";
import { import {
BadgeCheck, BadgeCheck,
Building2, Building2,
ChevronDown,
Key, Key,
KeyRound, KeyRound,
LayoutDashboard, LayoutDashboard,
@@ -9,11 +11,13 @@ import {
NotebookTabs, NotebookTabs,
ShieldHalf, ShieldHalf,
Sun, Sun,
User as UserIcon,
Users, Users,
} from "lucide-react"; } from "lucide-react";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useAuth } from "react-oidc-context"; import { useAuth } from "react-oidc-context";
import { NavLink, Outlet, useNavigate } from "react-router-dom"; import { NavLink, Outlet, useNavigate } from "react-router-dom";
import { fetchMe } from "../../lib/adminApi";
import { t } from "../../lib/i18n"; import { t } from "../../lib/i18n";
import LanguageSelector from "../common/LanguageSelector"; import LanguageSelector from "../common/LanguageSelector";
import RoleSwitcher from "./RoleSwitcher"; import RoleSwitcher from "./RoleSwitcher";
@@ -42,6 +46,13 @@ function AppLayout() {
const stored = window.localStorage.getItem("admin_theme"); const stored = window.localStorage.getItem("admin_theme");
return stored === "dark" ? "dark" : "light"; return stored === "dark" ? "dark" : "light";
}); });
const [isProfileOpen, setIsProfileOpen] = useState(false);
const { data: profile } = useQuery({
queryKey: ["me"],
queryFn: fetchMe,
enabled: auth.isAuthenticated && !auth.isLoading,
});
const handleLogout = () => { const handleLogout = () => {
if ( if (
@@ -59,6 +70,12 @@ function AppLayout() {
} }
}, [auth.isLoading, auth.isAuthenticated, navigate]); }, [auth.isLoading, auth.isAuthenticated, navigate]);
useEffect(() => {
if (auth.user?.access_token) {
window.localStorage.setItem("admin_session", auth.user.access_token);
}
}, [auth.user]);
useEffect(() => { useEffect(() => {
const root = document.documentElement; const root = document.documentElement;
root.classList.remove("light", "dark"); root.classList.remove("light", "dark");
@@ -187,7 +204,84 @@ function AppLayout() {
? t("ui.common.theme_light", "Light") ? t("ui.common.theme_light", "Light")
: t("ui.common.theme_dark", "Dark")} : t("ui.common.theme_dark", "Dark")}
</button> </button>
<span className="rounded-full border border-border px-3 py-2 text-muted-foreground">
<div className="relative">
<button
type="button"
onClick={() => setIsProfileOpen(!isProfileOpen)}
className="inline-flex items-center gap-2 rounded-full border border-border bg-card px-3 py-1.5 text-muted-foreground transition hover:bg-muted/20"
>
<div className="flex h-7 w-7 items-center justify-center rounded-full bg-primary/10 text-primary font-bold text-xs uppercase">
{profile?.name?.charAt(0) || <UserIcon size={14} />}
</div>
<span className="hidden max-w-[100px] truncate font-medium md:inline-block">
{profile?.name || auth.user?.profile.name || "User"}
</span>
<ChevronDown
size={14}
className={`transition-transform duration-200 ${isProfileOpen ? "rotate-180" : ""}`}
/>
</button>
{isProfileOpen && (
<>
<div
className="fixed inset-0 z-30"
onClick={() => setIsProfileOpen(false)}
onKeyDown={(e) => {
if (e.key === "Escape") setIsProfileOpen(false);
}}
role="button"
tabIndex={-1}
aria-label="Close profile menu"
/>
<div className="absolute right-0 mt-2 w-56 origin-top-right rounded-xl border border-border bg-card p-2 shadow-xl ring-1 ring-black ring-opacity-5 focus:outline-none z-40 animate-in fade-in zoom-in-95 duration-200">
<div className="px-3 py-3 border-b border-border/50 mb-1">
<p className="text-sm font-semibold truncate">
{profile?.name || auth.user?.profile.name}
</p>
<p className="text-xs text-muted-foreground truncate">
{profile?.email || auth.user?.profile.email}
</p>
<div className="mt-2">
<span className="inline-flex items-center rounded-md bg-primary/10 px-2 py-0.5 text-[10px] font-medium text-primary uppercase">
{t(
`ui.admin.role.${profile?.role || "user"}`,
profile?.role || "USER",
)}
</span>
</div>
</div>
<button
type="button"
onClick={() => {
setIsProfileOpen(false);
navigate(
`/users/${profile?.id || auth.user?.profile.sub}`,
);
}}
className="flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm text-muted-foreground transition hover:bg-muted/50 hover:text-foreground"
>
<UserIcon size={16} />
<span>{t("ui.userfront.nav.profile", "내 정보")}</span>
</button>
<button
type="button"
onClick={() => {
setIsProfileOpen(false);
handleLogout();
}}
className="flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm text-destructive transition hover:bg-destructive/10"
>
<LogOut size={16} />
<span>{t("ui.admin.nav.logout", "Logout")}</span>
</button>
</div>
</>
)}
</div>
<span className="hidden md:inline-flex rounded-full border border-border px-3 py-2 text-muted-foreground">
{t("msg.admin.session_ttl", "Session TTL: 15m admin")} {t("msg.admin.session_ttl", "Session TTL: 15m admin")}
</span> </span>
</div> </div>

View File

@@ -482,9 +482,7 @@ export function TenantAdminsAndOwnersTab() {
(a) => a.id === user.id, (a) => a.id === user.id,
); );
const isAlreadyMember = const isAlreadyMember =
dialogMode === "owner" dialogMode === "owner" ? isAlreadyOwner : isAlreadyAdmin;
? isAlreadyOwner
: isAlreadyAdmin;
return ( return (
<div <div

View File

@@ -436,6 +436,26 @@ export async function deleteUser(userId: string) {
await apiClient.delete(`/v1/admin/users/${userId}`); await apiClient.delete(`/v1/admin/users/${userId}`);
} }
export type UserProfileResponse = {
id: string;
email: string;
name: string;
phone: string;
role: string;
department: string;
affiliationType: string;
companyCode?: string;
tenantId?: string;
metadata?: Record<string, unknown>;
tenant?: TenantSummary;
manageableTenants?: TenantSummary[];
};
export async function fetchMe() {
const { data } = await apiClient.get<UserProfileResponse>("/v1/user/me");
return data;
}
// Relying Party Management // Relying Party Management
export type RelyingParty = { export type RelyingParty = {
clientId: string; clientId: string;

View File

@@ -44,13 +44,16 @@ test.describe("Tenant Owners Management", () => {
test("should list tenant owners", async ({ page }) => { test("should list tenant owners", async ({ page }) => {
// Mock owners list // Mock owners list
await page.route("**/api/v1/admin/tenants/tenant-1/owners**", async (route) => { await page.route(
await route.fulfill({ "**/api/v1/admin/tenants/tenant-1/owners**",
json: [ async (route) => {
{ id: "owner-1", name: "Owner One", email: "owner1@example.com" }, await route.fulfill({
], json: [
}); { id: "owner-1", name: "Owner One", email: "owner1@example.com" },
}); ],
});
},
);
await page.goto("/tenants/tenant-1/owners"); await page.goto("/tenants/tenant-1/owners");
@@ -62,13 +65,16 @@ test.describe("Tenant Owners Management", () => {
test("should add a new owner", async ({ page }) => { test("should add a new owner", async ({ page }) => {
// Mock owners list (initially empty) // Mock owners list (initially empty)
await page.route("**/api/v1/admin/tenants/tenant-1/owners**", async (route) => { await page.route(
if (route.request().method() === "GET") { "**/api/v1/admin/tenants/tenant-1/owners**",
await route.fulfill({ json: [] }); async (route) => {
} else if (route.request().method() === "POST") { if (route.request().method() === "GET") {
await route.fulfill({ status: 200 }); await route.fulfill({ json: [] });
} } else if (route.request().method() === "POST") {
}); await route.fulfill({ status: 200 });
}
},
);
// Mock users search // Mock users search
await page.route("**/api/v1/admin/users?**", async (route) => { await page.route("**/api/v1/admin/users?**", async (route) => {
@@ -91,7 +97,9 @@ test.describe("Tenant Owners Management", () => {
await page.fill('input[placeholder*="사용자 검색"]', "User Two"); await page.fill('input[placeholder*="사용자 검색"]', "User Two");
// Wait for results and add - using a more specific selector to target the button in the dialog // Wait for results and add - using a more specific selector to target the button in the dialog
const addButton = page.locator('role=dialog').getByRole('button', { name: '추가' }); const addButton = page
.locator("role=dialog")
.getByRole("button", { name: "추가" });
await addButton.click(); await addButton.click();
// Verify toast or mutation (in a real app, the list would refresh) // Verify toast or mutation (in a real app, the list would refresh)

View File

@@ -3974,7 +3974,7 @@ func (h *AuthHandler) resolveCurrentProfile(c *fiber.Ctx) (*domain.UserProfileRe
"email", profile.Email, "oldRole", profile.Role, "newRole", mockRole) "email", profile.Email, "oldRole", profile.Role, "newRole", mockRole)
profile.Role = mockRole profile.Role = mockRole
} }
} else if isDev && mockRole != "" { } else if isDev && mockRole != "" && token == "" && cookie == "" {
slog.Info("🔑 [AUTH_DEBUG] No real session found, using full Mock Auth", "role", mockRole) slog.Info("🔑 [AUTH_DEBUG] No real session found, using full Mock Auth", "role", mockRole)
profile = &domain.UserProfileResponse{ profile = &domain.UserProfileResponse{
ID: "00000000-0000-0000-0000-000000000000", ID: "00000000-0000-0000-0000-000000000000",

View File

@@ -608,7 +608,7 @@ type HydraIntrospectionResponse struct {
} }
func (s *HydraAdminService) IntrospectToken(ctx context.Context, token string) (*HydraIntrospectionResponse, error) { func (s *HydraAdminService) IntrospectToken(ctx context.Context, token string) (*HydraIntrospectionResponse, error) {
endpoint := fmt.Sprintf("%s/admin/oauth2/introspect", strings.TrimRight(s.AdminURL, "/")) endpoint := fmt.Sprintf("%s/oauth2/introspect", strings.TrimRight(s.AdminURL, "/"))
form := url.Values{} form := url.Values{}
form.Set("token", token) form.Set("token", token)