43 lines
1.1 KiB
TypeScript
43 lines
1.1 KiB
TypeScript
import {useContext} from 'react';
|
|
|
|
// auth provider
|
|
import AuthContext from '@/contexts/auth';
|
|
|
|
// ==============================|| AUTH HOOKS ||============================== //
|
|
|
|
const useAuth = () => {
|
|
const context = useContext(AuthContext);
|
|
|
|
if (!context) throw new Error('context must be use inside provider');
|
|
|
|
return context;
|
|
};
|
|
|
|
export const setAuthToken = (token: string | null, expiry_time = -1) => {
|
|
if (!token) {
|
|
localStorage.removeItem(AppConfig.AUTH_TOKEN_KEY);
|
|
return;
|
|
}
|
|
localStorage.setItem(AppConfig.AUTH_TOKEN_KEY, JSON.stringify({
|
|
token, expiry_time
|
|
}));
|
|
}
|
|
|
|
export const getAuthToken = () => {
|
|
const data = localStorage.getItem(AppConfig.AUTH_TOKEN_KEY);
|
|
if (!data) return;
|
|
try {
|
|
const {token, expiry_time} = JSON.parse(data) as { token: string, expiry_time: number };
|
|
if (expiry_time != -1 && expiry_time < Date.now()) {
|
|
localStorage.removeItem(AppConfig.AUTH_TOKEN_KEY);
|
|
return;
|
|
}
|
|
return token;
|
|
} catch (_e) {
|
|
return;
|
|
}
|
|
}
|
|
|
|
|
|
export default useAuth;
|