125 lines
4.8 KiB
TypeScript
125 lines
4.8 KiB
TypeScript
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
|
|
import { keepPreviousData, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
import { rpc } from '../api/client';
|
|
import { createExternalSession, fetchSessionUser, login as apiLogin, logout as apiLogout, type SessionUser } from '../api/session';
|
|
import { getConfig, type AppConfig } from '../api/config';
|
|
|
|
interface AuthState {
|
|
user: SessionUser | null;
|
|
config: AppConfig | undefined;
|
|
lang: string;
|
|
setLang: (l: string) => void;
|
|
ready: boolean;
|
|
/** the backend session already speaks `lang`: language-dependent data fetched before this would come back in the old language */
|
|
langReady: boolean;
|
|
signIn: (u: string, p: string, rememberMe?: boolean) => Promise<void>;
|
|
signOut: () => Promise<void>;
|
|
/** true once the unauthenticated "self-registration" session + its config (role REGISTER) are ready */
|
|
registerReady: boolean;
|
|
/** opens the anonymous REGISTER-role session the public sign-up pages run under; safe to call repeatedly */
|
|
beginRegistration: () => void;
|
|
}
|
|
|
|
const Ctx = createContext<AuthState>(null as never);
|
|
export const useAuth = () => useContext(Ctx);
|
|
|
|
const LANG_IDS: Record<string, number> = { AR: 1, EN: 2, URD: 3 };
|
|
|
|
export function AuthProvider({ children }: { children: ReactNode }) {
|
|
const qc = useQueryClient();
|
|
const [lang, setLangState] = useState(() => localStorage.getItem('mams.lang') || 'AR');
|
|
const setLang = (l: string) => {
|
|
localStorage.setItem('mams.lang', l);
|
|
setLangState(l);
|
|
};
|
|
|
|
const session = useQuery({
|
|
queryKey: ['session'],
|
|
queryFn: () => fetchSessionUser(lang),
|
|
staleTime: Infinity,
|
|
retry: false,
|
|
});
|
|
const user = session.data ?? null;
|
|
|
|
// The public sign-up pages (and "forgot password") act before any login exists: they run under an
|
|
// unauthenticated, role-REGISTER session instead. Starting it is idempotent and only ever done when
|
|
// there is no real user.
|
|
const [registering, setRegistering] = useState(false);
|
|
const beginRegistration = () => setRegistering(true);
|
|
const registerSession = useQuery({
|
|
queryKey: ['register-session', lang],
|
|
queryFn: () => createExternalSession(lang),
|
|
enabled: registering && !user,
|
|
staleTime: Infinity,
|
|
retry: false,
|
|
});
|
|
|
|
// The backend answers in the language of the session (names, plate numbers, statuses…), so the session must follow
|
|
// the language chosen here, exactly as the old "change language" link did. Data already on screen is then reloaded.
|
|
const backendLang = useQuery({
|
|
queryKey: ['backend-lang', user?.user_id, lang],
|
|
queryFn: async () => {
|
|
try {
|
|
await rpc('CONFIG', 'setLanaguage', { language: lang });
|
|
} catch {
|
|
/* the interface language still changes; data stays in the previous language */
|
|
}
|
|
await qc.invalidateQueries({ predicate: (q) => !['session', 'config', 'backend-lang'].includes(String(q.queryKey[0])) });
|
|
return lang;
|
|
},
|
|
enabled: !!user,
|
|
staleTime: Infinity,
|
|
retry: false,
|
|
placeholderData: keepPreviousData,
|
|
});
|
|
|
|
// the menu captions inside the config are written in the session language, so it is read again after a language change
|
|
const cfg = useQuery({
|
|
queryKey: ['config', user ? user.user_id : registering ? 'register' : 'none', lang],
|
|
queryFn: getConfig,
|
|
enabled: user ? backendLang.data === lang && !backendLang.isPlaceholderData : registering && registerSession.isSuccess,
|
|
staleTime: Infinity,
|
|
placeholderData: keepPreviousData,
|
|
});
|
|
const registerReady = !user && registering && registerSession.isSuccess && cfg.isSuccess && !cfg.isPlaceholderData;
|
|
|
|
useEffect(() => {
|
|
document.documentElement.lang = lang.toLowerCase();
|
|
document.documentElement.dir = lang === 'AR' || lang === 'URD' ? 'rtl' : 'ltr';
|
|
}, [lang]);
|
|
|
|
const signIn = async (u: string, p: string, rememberMe = false) => {
|
|
await apiLogin(u, p, LANG_IDS[lang] ?? 1, rememberMe);
|
|
await qc.invalidateQueries({ queryKey: ['session'] });
|
|
};
|
|
const signOut = async () => {
|
|
try {
|
|
await apiLogout(LANG_IDS[lang] ?? 1);
|
|
} finally {
|
|
// set this directly rather than clear()-then-invalidate: clear() removes the 'session' query
|
|
// from the cache first, so the invalidate that follows has nothing left to match and never refetches
|
|
qc.setQueryData(['session'], null);
|
|
qc.removeQueries({ predicate: (q) => q.queryKey[0] !== 'session' });
|
|
}
|
|
};
|
|
|
|
return (
|
|
<Ctx.Provider
|
|
value={{
|
|
user,
|
|
config: cfg.data,
|
|
lang,
|
|
setLang,
|
|
langReady: !user || (backendLang.data === lang && !backendLang.isPlaceholderData),
|
|
ready: !session.isPending && (!user || (!!cfg.data && !!backendLang.data)),
|
|
signIn,
|
|
signOut,
|
|
registerReady,
|
|
beginRegistration,
|
|
}}
|
|
>
|
|
{children}
|
|
</Ctx.Provider>
|
|
);
|
|
}
|