UNPKG

@defikitdotnet/x-ai-combat

Version:

XCombatAI - Social Media Engagement Template for the Agent Framework

135 lines 4.7 kB
"use strict"; "use client"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useAuth = exports.AuthProvider = void 0; const jsx_runtime_1 = require("react/jsx-runtime"); const react_1 = require("react"); // Create auth context with default values const AuthContext = (0, react_1.createContext)({ user: null, token: null, isAuthenticated: false, isLoading: true, error: null, login: async () => { }, logout: async () => { }, }); // Helper function to get token from localStorage const getStoredToken = () => { if (typeof window !== "undefined") { return localStorage.getItem("auth_token"); } return null; }; /** * Auth provider component to manage authentication state */ const AuthProvider = ({ children }) => { const [user, setUser] = (0, react_1.useState)(null); const [token, setToken] = (0, react_1.useState)(getStoredToken()); const [isAuthenticated, setIsAuthenticated] = (0, react_1.useState)(false); const [isLoading, setIsLoading] = (0, react_1.useState)(true); const [error, setError] = (0, react_1.useState)(null); // Fetch user data when token changes (0, react_1.useEffect)(() => { const fetchUserData = async () => { if (!token) { setIsLoading(false); setIsAuthenticated(false); setUser(null); return; } try { const backendUrl = process.env.NEXT_PUBLIC_BACKEND_URL || "http://localhost:3005"; setIsLoading(true); // Fetch current user data from API const response = await fetch(`${backendUrl}/xaicombat/api/auth/me`, { headers: { Authorization: `Bearer ${token}`, }, }); if (!response.ok) { throw new Error("Failed to fetch user data"); } const userData = await response.json(); setUser(userData.data); setIsAuthenticated(true); setError(null); } catch (err) { console.error("Error fetching user data:", err); // Handle invalid token if (err.message.includes("Invalid token")) { setToken(null); localStorage.removeItem("auth_token"); } setIsAuthenticated(false); setUser(null); setError(err.message); } finally { setIsLoading(false); } }; fetchUserData(); }, [token]); // Login function const login = (0, react_1.useCallback)(async (newToken) => { localStorage.setItem("auth_token", newToken); setToken(newToken); }, []); // Logout function const logout = (0, react_1.useCallback)(async () => { try { // Call logout API endpoint const backendUrl = process.env.NEXT_PUBLIC_BACKEND_URL || "http://localhost:3005"; await fetch(`${backendUrl}/xaicombat/api/auth/logout`, { method: "POST", credentials: "include", // Đảm bảo gửi cookies trong request headers: { Authorization: `Bearer ${token}`, }, }); // Xóa cookies bằng cách thiết lập hết hạn document.cookie.split(";").forEach(function (c) { document.cookie = c .replace(/^ +/, "") .replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); }); } catch (err) { console.error("Error during logout:", err); } finally { // Clear auth state even if API call fails localStorage.removeItem("auth_token"); setToken(null); setUser(null); setIsAuthenticated(false); } }, [token]); const value = { user, token, isAuthenticated, isLoading, error, login, logout, }; return (0, jsx_runtime_1.jsx)(AuthContext.Provider, { value: value, children: children }); }; exports.AuthProvider = AuthProvider; /** * Custom hook to use auth context */ const useAuth = () => { const context = (0, react_1.useContext)(AuthContext); if (context === undefined) { throw new Error("useAuth must be used within an AuthProvider"); } return context; }; exports.useAuth = useAuth; exports.default = AuthContext; //# sourceMappingURL=AuthContext.js.map