admin / Synapse-Cortex
publicSelf Hosted ITSM Tool with RBAC/Tenanting and MFA
Synapse-Cortex / Synapse-Cortexv2 / frontend / src / auth / AuthContext.tsx
1466 B · main
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 | import { createContext, useCallback, useContext, useEffect, useState, type ReactNode } from 'react' import { authApi } from '../api/auth' import type { Me } from '../api/types' interface AuthState { user: Me | null loading: boolean isAdmin: boolean isGlobalAdmin: boolean aiEnabled: boolean refresh: () => Promise<void> logout: () => Promise<void> } const AuthContext = createContext<AuthState | undefined>(undefined) export function AuthProvider({ children }: { children: ReactNode }) { const [user, setUser] = useState<Me | null>(null) const [loading, setLoading] = useState(true) const refresh = useCallback(async () => { try { const me = await authApi.me() setUser(me) } catch { setUser(null) } finally { setLoading(false) } }, []) useEffect(() => { refresh() }, [refresh]) const logout = useCallback(async () => { await authApi.logout() setUser(null) }, []) const isAdmin = user?.role === 'global_admin' || user?.role === 'tenant_admin' const isGlobalAdmin = user?.role === 'global_admin' const aiEnabled = user?.ai_enabled ?? false return ( <AuthContext.Provider value={{ user, loading, isAdmin, isGlobalAdmin, aiEnabled, 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 } |