68 lines
1.4 KiB
JavaScript
68 lines
1.4 KiB
JavaScript
import React, { createContext, useContext, useState, useEffect } from 'react';
|
|
import { api } from '../services/api';
|
|
|
|
const AuthContext = createContext();
|
|
|
|
export function useAuth() {
|
|
const context = useContext(AuthContext);
|
|
if (!context) {
|
|
throw new Error('useAuth must be used within an AuthProvider');
|
|
}
|
|
return context;
|
|
}
|
|
|
|
export function AuthProvider({ children }) {
|
|
const [user, setUser] = useState(null);
|
|
const [loading, setLoading] = useState(true);
|
|
const [token, setToken] = useState(localStorage.getItem('auth_token'));
|
|
|
|
useEffect(() => {
|
|
if (token) {
|
|
api.setAuthToken(token);
|
|
verifyToken();
|
|
} else {
|
|
setLoading(false);
|
|
}
|
|
}, [token]);
|
|
|
|
const verifyToken = async () => {
|
|
try {
|
|
const response = await api.verifyToken();
|
|
setUser(response.data.user);
|
|
} catch (error) {
|
|
console.error('Token verification failed:', error);
|
|
logout();
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
const login = (authToken) => {
|
|
setToken(authToken);
|
|
localStorage.setItem('auth_token', authToken);
|
|
api.setAuthToken(authToken);
|
|
};
|
|
|
|
const logout = () => {
|
|
setToken(null);
|
|
setUser(null);
|
|
localStorage.removeItem('auth_token');
|
|
api.setAuthToken(null);
|
|
};
|
|
|
|
const value = {
|
|
user,
|
|
token,
|
|
loading,
|
|
login,
|
|
logout,
|
|
isAuthenticated: !!user
|
|
};
|
|
|
|
return (
|
|
<AuthContext.Provider value={value}>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
);
|
|
}
|