Spaces:
Sleeping
Sleeping
File size: 2,799 Bytes
d97b8f9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | import React, { createContext, useContext, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { userSessionService, LoginResponse } from './api';
interface AuthContextType {
isAuthenticated: boolean;
userData: LoginResponse | null;
logout: () => void;
checkAuthStatus: () => boolean;
login: (userData: LoginResponse) => void;
}
const AuthContext = createContext<AuthContextType>({
isAuthenticated: false,
userData: null,
logout: () => {},
checkAuthStatus: () => false,
login: () => {},
});
export const useAuth = () => useContext(AuthContext);
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState<boolean>(userSessionService.isAuthenticated());
const [userData, setUserData] = useState<LoginResponse | null>(userSessionService.getSession());
const navigate = useNavigate();
// Check session on mount
useEffect(() => {
checkAuthStatus();
}, []);
const checkAuthStatus = (): boolean => {
const isAuthValid = userSessionService.isAuthenticated();
setIsAuthenticated(isAuthValid);
setUserData(userSessionService.getSession());
return isAuthValid;
};
const login = (userData: LoginResponse) => {
userSessionService.setSession(userData);
setIsAuthenticated(true);
setUserData(userData);
// Force a refresh of the page to ensure all components update
const roleName = userData.roleName?.toLowerCase() || '';
// Check if user is a client
if (roleName === "client") {
window.location.href = "/production-bugs";
}
// Check if user has HR-related role (Admin, CEO, COO, or any role containing 'hr')
else if (roleName === "admin" || roleName === "ceo" || roleName === "coo" || roleName.includes("hr")) {
window.location.href = "/employees";
}
// Default redirect to tasks for other roles
else {
window.location.href = "/tasks";
}
};
const logout = () => {
userSessionService.clearSession();
setIsAuthenticated(false);
setUserData(null);
navigate('/login', { replace: true });
};
return (
<AuthContext.Provider value={{ isAuthenticated, userData, logout, checkAuthStatus, login }}>
{children}
</AuthContext.Provider>
);
};
// Auth guard component
export const RequireAuth: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const { isAuthenticated } = useAuth();
const navigate = useNavigate();
useEffect(() => {
if (!isAuthenticated) {
navigate('/login', { replace: true });
}
}, [isAuthenticated, navigate]);
return isAuthenticated ? <>{children}</> : null;
}; |