Spaces:
Running

Bot / frontend /src /features /auth /hooks /useAuthSession.tsx
ddosvn's picture
Initial deploy of Panel ThTuanIT full stack and Lighthouse-optimized frontend
7e79d39 verified
Raw History Blame Contribute Delete
2.99 kB
'use client';
import React, { createContext, useCallback, useContext, useEffect, useState } from 'react';
import { getToken, setToken } from '@/shared/lib/httpClient';
import { authService } from '../services/authService';
import { AuthModalMode, AuthUser, PublicPanelConfig } from '../types/authTypes';
interface AuthContextValue {
user: AuthUser | null;
authLoading: boolean;
publicConfig: PublicPanelConfig;
motdDismissed: boolean;
dismissMotd: () => void;
authModalOpen: boolean;
authModalMode: AuthModalMode;
openAuthModal: (mode?: AuthModalMode) => void;
closeAuthModal: () => void;
setSessionUser: (user: AuthUser | null) => void;
logout: () => void;
refreshAuth: () => Promise<void>;
}
const AuthContext = createContext<AuthContextValue | null>(null);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<AuthUser | null>(null);
const [authLoading, setAuthLoading] = useState(true);
const [publicConfig, setPublicConfig] = useState<PublicPanelConfig>({});
const [motdDismissed, setMotdDismissed] = useState(false);
const [authModalOpen, setAuthModalOpen] = useState(false);
const [authModalMode, setAuthModalMode] = useState<AuthModalMode>('login');
const refreshAuth = useCallback(async () => {
try {
const cfg = await authService.getPublicConfig().catch(() => null);
if (cfg) setPublicConfig(cfg);
const token = getToken();
if (!token) {
setUser(null);
return;
}
const data = await authService.getMe();
setUser(data.user ?? null);
} catch {
setToken(null);
setUser(null);
} finally {
setAuthLoading(false);
}
}, []);
useEffect(() => {
void refreshAuth();
}, [refreshAuth]);
const openAuthModal = useCallback(
(mode: AuthModalMode = 'login') => {
const nextMode = publicConfig.disable_registration ? 'login' : mode;
setAuthModalMode(nextMode);
setAuthModalOpen(true);
},
[publicConfig.disable_registration],
);
const closeAuthModal = useCallback(() => {
setAuthModalOpen(false);
}, []);
const setSessionUser = useCallback((nextUser: AuthUser | null) => {
setUser(nextUser);
setAuthLoading(false);
}, []);
const logout = useCallback(() => {
setToken(null);
setUser(null);
}, []);
const dismissMotd = useCallback(() => {
setMotdDismissed(true);
}, []);
return (
<AuthContext.Provider
value={{
user,
authLoading,
publicConfig,
motdDismissed,
dismissMotd,
authModalOpen,
authModalMode,
openAuthModal,
closeAuthModal,
setSessionUser,
logout,
refreshAuth,
}}
>
{children}
</AuthContext.Provider>
);
}
export function useAuthSession() {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error('useAuthSession must be used inside AuthProvider');
return ctx;
}