Basic home, Login, and Auth in client

This commit is contained in:
2024-12-01 16:59:07 +00:00
parent 62cca139af
commit 0ba95b0dab
5 changed files with 247 additions and 39 deletions

View File

@@ -0,0 +1,46 @@
// src/contexts/AuthContext.jsx
import { createContext, useContext, useState, useEffect } from 'react';
import axios from 'axios';
const AuthContext = createContext();
export function AuthProvider({ children }) {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const token = localStorage.getItem('token');
setIsAuthenticated(!!token);
setIsLoading(false);
}, []);
const login = async (username, password) => {
try {
const response = await axios.post(`${import.meta.env.VITE_API_URL}/api/auth/login`, {
username,
password
});
localStorage.setItem('token', response.data.token);
setIsAuthenticated(true);
return true;
} catch (error) {
console.error('Login error:', error);
return false;
}
};
const logout = () => {
localStorage.removeItem('token');
setIsAuthenticated(false);
};
return (
<AuthContext.Provider value={{ isAuthenticated, isLoading, login, logout }}>
{!isLoading && children}
</AuthContext.Provider>
);
}
export function useAuth() {
return useContext(AuthContext);
}