Files
tower/apps/web/app/_lib/auth-context.tsx
T
maaz519 a3798b3059 feat: show tenancy scope (Org → Chapter) in chapter & member portals
Surface where the logged-in user sits in the hierarchy via a ScopeCard
in the sidebar, below the brand mark.

API:
- Enrich chapter login/me responses with tenantName + organization
  (LoginResponse.admin, AdminProfile types updated)
- Add GET /my/scope returning member's chapter + organization

Web:
- ScopeCard component (Organisation row + Chapter row, themed icons)
- Chapter portal: scope from auth context, blue accent
- Member portal: scope fetched server-side in layout, emerald accent
- PortalShell gains a `scope` slot rendered under the brand

Org and admin portals intentionally omit it — org IS the scope, admin is
platform-wide.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-20 18:27:23 +05:30

76 lines
1.9 KiB
TypeScript

'use client';
import { createContext, useCallback, useContext, useEffect, useState } from 'react';
export interface AuthAdmin {
id: string;
email: string;
name?: string | null;
role: 'OWNER' | 'ADMIN' | 'VIEWER';
tenantId: string;
tenantSlug: string;
tenantName?: string;
organization?: { id: string; slug: string; name: string } | null;
}
interface AuthState {
admin: AuthAdmin | null;
loading: boolean;
error: string | null;
refresh: () => Promise<void>;
logout: () => Promise<void>;
}
const AuthContext = createContext<AuthState | null>(null);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [admin, setAdmin] = useState<AuthAdmin | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const refresh = useCallback(async () => {
setLoading(true);
setError(null);
try {
const res = await fetch('/api/auth/me', { credentials: 'include' });
if (res.status === 401) {
setAdmin(null);
return;
}
if (!res.ok) {
setError('Unable to verify session');
setAdmin(null);
return;
}
const data = await res.json();
setAdmin(data.admin ?? null);
} catch (e) {
setError(e instanceof Error ? e.message : 'Network error');
setAdmin(null);
} finally {
setLoading(false);
}
}, []);
const logout = useCallback(async () => {
await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' });
setAdmin(null);
}, []);
useEffect(() => {
void refresh();
}, [refresh]);
return (
<AuthContext.Provider value={{ admin, loading, error, refresh, logout }}>
{children}
</AuthContext.Provider>
);
}
export function useAuth(): AuthState {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error('useAuth must be used within <AuthProvider>');
return ctx;
}