@defikitdotnet/x-ai-combat
Version:
XCombatAI - Social Media Engagement Template for the Agent Framework
130 lines • 4.42 kB
JavaScript
"use client";
import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, useCallback, useContext, useEffect, useState, } from "react";
// Create auth context with default values
const AuthContext = 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
*/
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [token, setToken] = useState(getStoredToken());
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
// Fetch user data when token changes
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 = useCallback(async (newToken) => {
localStorage.setItem("auth_token", newToken);
setToken(newToken);
}, []);
// Logout function
const logout = 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 _jsx(AuthContext.Provider, { value: value, children: children });
};
/**
* Custom hook to use auth context
*/
export const useAuth = () => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
};
export default AuthContext;
//# sourceMappingURL=AuthContext.js.map