2026-01-06 15:33:03 +00:00
|
|
|
import { createContext, useContext, useState, useEffect, useCallback, ReactNode } from 'react';
|
|
|
|
|
import { useNavigate } from 'react-router-dom';
|
2026-01-16 17:31:25 +10:30
|
|
|
import { api, User, ApiError, tokenManager, MfaComplianceSummary } from '@/lib/api';
|
2026-01-06 15:33:03 +00:00
|
|
|
|
2026-01-14 07:21:55 +00:00
|
|
|
interface LoginResult {
|
|
|
|
|
requiresTotp: boolean;
|
2026-01-16 17:50:56 +10:30
|
|
|
requiresWebAuthn: boolean;
|
2026-01-16 17:31:25 +10:30
|
|
|
requiresMfaEnrollment?: boolean;
|
2026-01-14 07:21:55 +00:00
|
|
|
}
|
|
|
|
|
|
2026-01-06 15:33:03 +00:00
|
|
|
interface AuthContextType {
|
|
|
|
|
user: User | null;
|
|
|
|
|
isLoading: boolean;
|
|
|
|
|
isAuthenticated: boolean;
|
2026-03-01 16:50:19 +05:45
|
|
|
isOrgAdmin: boolean;
|
|
|
|
|
isOrgMember: boolean;
|
2026-01-16 17:31:25 +10:30
|
|
|
mfaCompliance: MfaComplianceSummary | null;
|
|
|
|
|
requiresMfaEnrollment: boolean;
|
2026-03-01 16:50:19 +05:45
|
|
|
login: (email: string, password: string, rememberMe?: boolean, skipNavigate?: boolean) => Promise<LoginResult>;
|
|
|
|
|
verifyTotp: (code: string, isBackupCode?: boolean, skipNavigate?: boolean) => Promise<void>;
|
2026-01-16 17:50:56 +10:30
|
|
|
verifyWebAuthn: () => Promise<void>;
|
2026-01-06 15:33:03 +00:00
|
|
|
logout: () => Promise<void>;
|
|
|
|
|
refreshUser: () => Promise<void>;
|
2026-01-16 17:31:25 +10:30
|
|
|
refreshCompliance: () => Promise<void>;
|
2026-01-06 15:33:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const AuthContext = createContext<AuthContextType | null>(null);
|
|
|
|
|
|
2026-01-16 17:31:25 +10:30
|
|
|
// LocalStorage key for MFA compliance persistence
|
|
|
|
|
const MFA_COMPLIANCE_KEY = 'gatehouse_mfa_compliance';
|
|
|
|
|
|
|
|
|
|
// Helper to persist MFA compliance to localStorage
|
|
|
|
|
function persistMfaCompliance(compliance: MfaComplianceSummary | null): void {
|
|
|
|
|
if (compliance) {
|
|
|
|
|
localStorage.setItem(MFA_COMPLIANCE_KEY, JSON.stringify(compliance));
|
|
|
|
|
} else {
|
|
|
|
|
localStorage.removeItem(MFA_COMPLIANCE_KEY);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Helper to load MFA compliance from localStorage
|
|
|
|
|
function loadMfaCompliance(): MfaComplianceSummary | null {
|
|
|
|
|
try {
|
|
|
|
|
const stored = localStorage.getItem(MFA_COMPLIANCE_KEY);
|
2026-03-01 16:50:19 +05:45
|
|
|
if (!stored) return null;
|
|
|
|
|
|
2026-01-16 17:50:56 +10:30
|
|
|
const parsed = JSON.parse(stored);
|
2026-03-01 16:50:19 +05:45
|
|
|
|
2026-01-16 17:50:56 +10:30
|
|
|
// Handle both direct format and legacy double-nested format
|
|
|
|
|
// Legacy format: { mfa_compliance: { ... } }
|
|
|
|
|
// Current format: { ... }
|
|
|
|
|
let compliance: Record<string, unknown>;
|
|
|
|
|
if (parsed.mfa_compliance && typeof parsed.mfa_compliance === 'object') {
|
|
|
|
|
compliance = parsed.mfa_compliance as Record<string, unknown>;
|
|
|
|
|
} else {
|
|
|
|
|
compliance = parsed;
|
|
|
|
|
}
|
2026-03-01 16:50:19 +05:45
|
|
|
|
2026-01-16 17:31:25 +10:30
|
|
|
// Validate that the stored data has the required fields
|
2026-03-01 16:50:19 +05:45
|
|
|
if (!compliance || typeof compliance !== 'object') return null;
|
|
|
|
|
if (!Array.isArray(compliance.orgs)) return null;
|
|
|
|
|
|
2026-01-16 17:31:25 +10:30
|
|
|
// Check if at least one org has effective_mode (new field from API)
|
|
|
|
|
// If not, treat as stale data and return null to fetch fresh data
|
|
|
|
|
const hasEffectiveMode = compliance.orgs.some((org: Record<string, unknown>) =>
|
|
|
|
|
typeof org.effective_mode === 'string'
|
|
|
|
|
);
|
2026-03-01 16:50:19 +05:45
|
|
|
if (!hasEffectiveMode) return null;
|
|
|
|
|
|
2026-01-16 17:50:56 +10:30
|
|
|
return compliance as unknown as MfaComplianceSummary;
|
2026-03-01 16:50:19 +05:45
|
|
|
} catch {
|
2026-01-16 17:31:25 +10:30
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-06 15:33:03 +00:00
|
|
|
export function AuthProvider({ children }: { children: ReactNode }) {
|
|
|
|
|
const [user, setUser] = useState<User | null>(null);
|
2026-03-01 16:50:19 +05:45
|
|
|
const [isOrgAdmin, setIsOrgAdmin] = useState(false);
|
|
|
|
|
const [isOrgMember, setIsOrgMember] = useState(false);
|
2026-01-16 17:31:25 +10:30
|
|
|
const [mfaCompliance, setMfaCompliance] = useState<MfaComplianceSummary | null>(loadMfaCompliance);
|
|
|
|
|
const [requiresMfaEnrollment, setRequiresMfaEnrollment] = useState(false);
|
2026-01-06 15:33:03 +00:00
|
|
|
const [isLoading, setIsLoading] = useState(true);
|
|
|
|
|
const navigate = useNavigate();
|
|
|
|
|
|
2026-03-01 16:50:19 +05:45
|
|
|
// Helper to check if user is admin/owner in any org
|
|
|
|
|
const checkOrgAdmin = useCallback(async () => {
|
|
|
|
|
try {
|
|
|
|
|
const data = await api.users.organizations();
|
|
|
|
|
const admin = data.organizations.some(
|
|
|
|
|
(org) => org.role === 'owner' || org.role === 'admin'
|
|
|
|
|
);
|
|
|
|
|
setIsOrgAdmin(admin);
|
|
|
|
|
setIsOrgMember(data.organizations.length > 0);
|
|
|
|
|
} catch {
|
|
|
|
|
setIsOrgAdmin(false);
|
|
|
|
|
setIsOrgMember(false);
|
|
|
|
|
}
|
|
|
|
|
}, []);
|
|
|
|
|
|
2026-01-16 17:31:25 +10:30
|
|
|
const refreshCompliance = useCallback(async () => {
|
|
|
|
|
try {
|
|
|
|
|
const compliance = await api.policies.getMyCompliance();
|
|
|
|
|
setMfaCompliance(compliance);
|
|
|
|
|
persistMfaCompliance(compliance);
|
|
|
|
|
|
|
|
|
|
// Check if user is now compliant
|
|
|
|
|
if (compliance.overall_status === 'compliant' && requiresMfaEnrollment) {
|
|
|
|
|
setRequiresMfaEnrollment(false);
|
|
|
|
|
navigate('/profile');
|
|
|
|
|
}
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('[AuthContext] Failed to refresh compliance:', error);
|
|
|
|
|
}
|
|
|
|
|
}, [requiresMfaEnrollment, navigate]);
|
|
|
|
|
|
2026-01-06 15:33:03 +00:00
|
|
|
const refreshUser = useCallback(async () => {
|
|
|
|
|
try {
|
|
|
|
|
const response = await api.users.me();
|
|
|
|
|
setUser(response.user);
|
|
|
|
|
} catch (error) {
|
|
|
|
|
if (error instanceof ApiError && error.code === 401) {
|
|
|
|
|
setUser(null);
|
2026-01-16 17:31:25 +10:30
|
|
|
setMfaCompliance(null);
|
|
|
|
|
persistMfaCompliance(null);
|
|
|
|
|
setRequiresMfaEnrollment(false);
|
2026-01-06 15:33:03 +00:00
|
|
|
}
|
|
|
|
|
// Silently fail for other errors during refresh
|
|
|
|
|
}
|
|
|
|
|
}, []);
|
|
|
|
|
|
2026-01-07 14:29:40 +00:00
|
|
|
// Check for existing token on mount
|
2026-01-06 15:33:03 +00:00
|
|
|
useEffect(() => {
|
2026-01-07 14:29:40 +00:00
|
|
|
const checkAuth = async () => {
|
|
|
|
|
// Only attempt to fetch user if we have a valid token
|
|
|
|
|
if (!tokenManager.hasValidToken()) {
|
|
|
|
|
setUser(null);
|
2026-01-16 17:31:25 +10:30
|
|
|
setMfaCompliance(null);
|
|
|
|
|
persistMfaCompliance(null);
|
|
|
|
|
setRequiresMfaEnrollment(false);
|
2026-01-07 14:29:40 +00:00
|
|
|
setIsLoading(false);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-06 15:33:03 +00:00
|
|
|
try {
|
|
|
|
|
const response = await api.users.me();
|
|
|
|
|
setUser(response.user);
|
2026-01-16 17:31:25 +10:30
|
|
|
|
2026-03-01 16:50:19 +05:45
|
|
|
// Also fetch compliance status and org role
|
2026-01-16 17:31:25 +10:30
|
|
|
try {
|
|
|
|
|
const compliance = await api.policies.getMyCompliance();
|
|
|
|
|
setMfaCompliance(compliance);
|
|
|
|
|
persistMfaCompliance(compliance);
|
|
|
|
|
setRequiresMfaEnrollment(compliance.overall_status === 'suspended');
|
|
|
|
|
} catch {
|
|
|
|
|
// Compliance fetch failed, continue without it
|
|
|
|
|
setMfaCompliance(null);
|
|
|
|
|
persistMfaCompliance(null);
|
|
|
|
|
}
|
2026-03-01 16:50:19 +05:45
|
|
|
// Check org admin status
|
|
|
|
|
await checkOrgAdmin();
|
2026-01-06 15:33:03 +00:00
|
|
|
} catch {
|
|
|
|
|
setUser(null);
|
2026-03-01 16:50:19 +05:45
|
|
|
setIsOrgAdmin(false);
|
|
|
|
|
setIsOrgMember(false);
|
2026-01-16 17:31:25 +10:30
|
|
|
setMfaCompliance(null);
|
|
|
|
|
persistMfaCompliance(null);
|
|
|
|
|
setRequiresMfaEnrollment(false);
|
2026-01-06 15:33:03 +00:00
|
|
|
} finally {
|
|
|
|
|
setIsLoading(false);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2026-01-07 14:29:40 +00:00
|
|
|
checkAuth();
|
2026-01-06 15:33:03 +00:00
|
|
|
}, []);
|
|
|
|
|
|
2026-03-01 16:50:19 +05:45
|
|
|
const login = useCallback(async (email: string, password: string, rememberMe = false, skipNavigate = false): Promise<LoginResult> => {
|
2026-01-06 15:33:03 +00:00
|
|
|
const response = await api.auth.login(email, password, rememberMe);
|
2026-03-01 16:50:19 +05:45
|
|
|
|
2026-01-16 17:50:56 +10:30
|
|
|
// If WebAuthn is required, don't set user yet - wait for WebAuthn verification
|
|
|
|
|
if (response.requires_webauthn) {
|
|
|
|
|
return { requiresTotp: false, requiresWebAuthn: true };
|
|
|
|
|
}
|
2026-03-01 16:50:19 +05:45
|
|
|
|
2026-01-14 07:21:55 +00:00
|
|
|
// If TOTP is required, don't set user yet - wait for TOTP verification
|
|
|
|
|
if (response.requires_totp) {
|
2026-01-16 17:50:56 +10:30
|
|
|
return { requiresTotp: true, requiresWebAuthn: false };
|
2026-01-14 07:21:55 +00:00
|
|
|
}
|
2026-03-01 16:50:19 +05:45
|
|
|
|
2026-01-16 17:31:25 +10:30
|
|
|
// If MFA enrollment is required (past deadline), set compliance state
|
|
|
|
|
if (response.requires_mfa_enrollment) {
|
|
|
|
|
if (response.token) {
|
|
|
|
|
tokenManager.setToken(response.token, response.expires_at ?? null);
|
|
|
|
|
}
|
|
|
|
|
if (response.user) {
|
|
|
|
|
setUser(response.user);
|
|
|
|
|
}
|
|
|
|
|
if (response.mfa_compliance) {
|
|
|
|
|
setMfaCompliance(response.mfa_compliance);
|
|
|
|
|
persistMfaCompliance(response.mfa_compliance);
|
|
|
|
|
}
|
|
|
|
|
setRequiresMfaEnrollment(true);
|
2026-01-16 17:50:56 +10:30
|
|
|
return { requiresTotp: false, requiresWebAuthn: false, requiresMfaEnrollment: true };
|
2026-01-16 17:31:25 +10:30
|
|
|
}
|
2026-03-01 16:50:19 +05:45
|
|
|
|
2026-01-16 11:35:21 +10:30
|
|
|
if (response.token) {
|
|
|
|
|
tokenManager.setToken(response.token, response.expires_at ?? null);
|
|
|
|
|
}
|
2026-03-01 16:50:19 +05:45
|
|
|
|
2026-01-14 07:21:55 +00:00
|
|
|
if (response.user) {
|
|
|
|
|
setUser(response.user);
|
2026-01-16 17:31:25 +10:30
|
|
|
if (response.mfa_compliance) {
|
|
|
|
|
setMfaCompliance(response.mfa_compliance);
|
|
|
|
|
persistMfaCompliance(response.mfa_compliance);
|
|
|
|
|
}
|
|
|
|
|
setRequiresMfaEnrollment(false);
|
2026-03-01 16:50:19 +05:45
|
|
|
await checkOrgAdmin();
|
|
|
|
|
if (!skipNavigate) {
|
|
|
|
|
navigate('/profile');
|
|
|
|
|
}
|
2026-01-14 07:21:55 +00:00
|
|
|
}
|
2026-01-16 17:50:56 +10:30
|
|
|
return { requiresTotp: false, requiresWebAuthn: false };
|
2026-03-01 16:50:19 +05:45
|
|
|
}, [navigate, checkOrgAdmin]);
|
2026-01-14 07:21:55 +00:00
|
|
|
|
2026-01-16 17:50:56 +10:30
|
|
|
const verifyWebAuthn = useCallback(async () => {
|
|
|
|
|
// WebAuthn verification is handled directly in the LoginPage component
|
|
|
|
|
}, []);
|
|
|
|
|
|
2026-03-01 16:50:19 +05:45
|
|
|
const verifyTotp = useCallback(async (code: string, isBackupCode = false, skipNavigate = false) => {
|
2026-01-14 07:21:55 +00:00
|
|
|
const response = await api.totp.verify(code, isBackupCode);
|
2026-01-16 11:35:21 +10:30
|
|
|
|
|
|
|
|
if (response.token) {
|
|
|
|
|
tokenManager.setToken(response.token, response.expires_at ?? null);
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-06 15:33:03 +00:00
|
|
|
setUser(response.user);
|
2026-01-16 17:31:25 +10:30
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const compliance = await api.policies.getMyCompliance();
|
|
|
|
|
setMfaCompliance(compliance);
|
|
|
|
|
persistMfaCompliance(compliance);
|
|
|
|
|
setRequiresMfaEnrollment(compliance.overall_status === 'suspended');
|
|
|
|
|
} catch {
|
|
|
|
|
setMfaCompliance(null);
|
|
|
|
|
persistMfaCompliance(null);
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-01 16:50:19 +05:45
|
|
|
await checkOrgAdmin();
|
|
|
|
|
if (!skipNavigate) {
|
|
|
|
|
navigate('/profile');
|
|
|
|
|
}
|
|
|
|
|
}, [navigate, checkOrgAdmin]);
|
2026-01-06 15:33:03 +00:00
|
|
|
|
|
|
|
|
const logout = useCallback(async () => {
|
|
|
|
|
try {
|
|
|
|
|
await api.auth.logout();
|
|
|
|
|
} finally {
|
|
|
|
|
setUser(null);
|
2026-03-01 16:50:19 +05:45
|
|
|
setIsOrgAdmin(false);
|
|
|
|
|
setIsOrgMember(false);
|
2026-01-16 17:31:25 +10:30
|
|
|
setMfaCompliance(null);
|
|
|
|
|
persistMfaCompliance(null);
|
|
|
|
|
setRequiresMfaEnrollment(false);
|
2026-01-06 15:33:03 +00:00
|
|
|
navigate('/login');
|
|
|
|
|
}
|
|
|
|
|
}, [navigate]);
|
|
|
|
|
|
|
|
|
|
return (
|
|
|
|
|
<AuthContext.Provider
|
|
|
|
|
value={{
|
|
|
|
|
user,
|
|
|
|
|
isLoading,
|
|
|
|
|
isAuthenticated: !!user,
|
2026-03-01 16:50:19 +05:45
|
|
|
isOrgAdmin,
|
|
|
|
|
isOrgMember,
|
2026-01-16 17:31:25 +10:30
|
|
|
mfaCompliance,
|
|
|
|
|
requiresMfaEnrollment,
|
2026-01-06 15:33:03 +00:00
|
|
|
login,
|
2026-01-14 07:21:55 +00:00
|
|
|
verifyTotp,
|
2026-01-16 17:50:56 +10:30
|
|
|
verifyWebAuthn,
|
2026-01-06 15:33:03 +00:00
|
|
|
logout,
|
|
|
|
|
refreshUser,
|
2026-01-16 17:31:25 +10:30
|
|
|
refreshCompliance,
|
2026-01-06 15:33:03 +00:00
|
|
|
}}
|
|
|
|
|
>
|
|
|
|
|
{children}
|
|
|
|
|
</AuthContext.Provider>
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function useAuth() {
|
|
|
|
|
const context = useContext(AuthContext);
|
|
|
|
|
if (!context) {
|
|
|
|
|
throw new Error('useAuth must be used within an AuthProvider');
|
|
|
|
|
}
|
|
|
|
|
return context;
|
|
|
|
|
}
|