first time include all file
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
|
||||
import type { ReactNode } from 'react';
|
||||
import { createContext, useContext, useState } from 'react';
|
||||
import { AdminRole, type AuthContextType, type AuthenticateResponse } from '../models';
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
||||
// Initialize state directly from localStorage to prevent screen flicker on refresh
|
||||
const [user, setUser] = useState<AuthenticateResponse | null>(() => {
|
||||
const savedUser = sessionStorage.getItem('auth_user');
|
||||
if (savedUser)
|
||||
return savedUser ? JSON.parse(savedUser) : null;
|
||||
else
|
||||
return null;
|
||||
});
|
||||
|
||||
const login = (userData: AuthenticateResponse) => {
|
||||
setUser(userData);
|
||||
sessionStorage.setItem('auth_user', JSON.stringify(userData));
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
setUser(null);
|
||||
sessionStorage.removeItem('auth_user');
|
||||
};
|
||||
|
||||
const isAuthenticated = !!user;
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, login, logout, isAuthenticated }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
// Custom hook for consuming the context cleanly
|
||||
export const useAuth = () => {
|
||||
const context = useContext(AuthContext);
|
||||
if (!context) {
|
||||
throw new Error('useAuth must be used within an AuthProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
export const Utils = {
|
||||
getLogin: () : AuthenticateResponse =>{
|
||||
const empty: AuthenticateResponse ={
|
||||
id: 0,
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
username: '',
|
||||
role: AdminRole.Normal,
|
||||
validationPointId: 0,
|
||||
token: '',
|
||||
email: ''
|
||||
};
|
||||
const savedUser = sessionStorage.getItem('auth_user');
|
||||
if (savedUser)
|
||||
{
|
||||
const obj = JSON.parse(savedUser);
|
||||
console.log('the obj in get login ', obj);
|
||||
if (obj != null) {
|
||||
let myItem: AuthenticateResponse ={
|
||||
id: obj.id,
|
||||
firstName: obj.firstName,
|
||||
lastName: obj.lastName,
|
||||
username: obj.username,
|
||||
role: obj.role,
|
||||
validationPointId: obj.validationPointId,
|
||||
token: obj.token,
|
||||
email: obj.email
|
||||
};
|
||||
console.log(' return the obj in get login ', myItem, obj);
|
||||
return myItem;
|
||||
}
|
||||
return empty;
|
||||
}
|
||||
else
|
||||
return empty;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user