import { createContext, useContext, useEffect, useState, type ReactNode } from "react"; import * as SecureStore from "expo-secure-store"; import { api } from "./api"; /** * Auth mobile : JWT stocké de façon sécurisée (Keychain/Keystore via * expo-secure-store). Owner unique, login fort (mdp + TOTP) côté backend. */ interface AuthState { token: string | null; ready: boolean; login: (user: string, password: string, totp: string) => Promise; logout: () => Promise; } const KEY = "chlova.token"; const Ctx = createContext(null); export function AuthProvider({ children }: { children: ReactNode }) { const [token, setToken] = useState(null); const [ready, setReady] = useState(false); useEffect(() => { void SecureStore.getItemAsync(KEY).then((t) => { setToken(t); setReady(true); }); }, []); const login = async (user: string, password: string, totp: string): Promise => { const { token: t } = await api.login(user, password, totp); await SecureStore.setItemAsync(KEY, t); setToken(t); }; const logout = async (): Promise => { await SecureStore.deleteItemAsync(KEY); setToken(null); }; return {children}; } export function useAuth(): AuthState { const ctx = useContext(Ctx); if (!ctx) throw new Error("useAuth hors AuthProvider"); return ctx; }