73 lines
2.0 KiB
JavaScript
73 lines
2.0 KiB
JavaScript
import { useEffect, useState } from 'react';
|
|
import { useDispatch } from 'react-redux';
|
|
import {
|
|
checkSession,
|
|
GenerateLogout,
|
|
} from './Features/BrachLogin/BranchLogin.js';
|
|
import {
|
|
clearSession,
|
|
getSession,
|
|
TokendecryptedValuesFun,
|
|
} from './Services/Others.js';
|
|
const commonSubDir = import.meta.env.ENV_COMMON_BASE_URL;
|
|
|
|
const useSessionManager = (dependencyTrigger) => {
|
|
const dispatch = useDispatch();
|
|
const [sessionData, setSessionData] = useState(null);
|
|
|
|
// 🔹 Load session
|
|
useEffect(() => {
|
|
const CompId = getSession('CompId');
|
|
const AppId = getSession('AppId');
|
|
const BranchId = getSession('BranchId');
|
|
const UserType = getSession('UserType');
|
|
|
|
if (CompId && AppId && BranchId) {
|
|
setSessionData({ CompId, AppId, BranchId, UserType });
|
|
}
|
|
}, []);
|
|
|
|
// 🔹 Session validity check (same logic, centralized)
|
|
useEffect(() => {
|
|
const sessionCheckFun = async () => {
|
|
const UserId = getSession('UserId');
|
|
const sessionId = getSession('SessionId');
|
|
const IsLogout = getSession('Mode');
|
|
|
|
let encryptedLoginType = TokendecryptedValuesFun(
|
|
sessionStorage.getItem('LoginType')
|
|
);
|
|
|
|
if (encryptedLoginType !== 'Kiosk') {
|
|
const res = await dispatch(
|
|
checkSession({ UserId, sessionId })
|
|
).unwrap();
|
|
if (res?.data?.statusCode === 1 && res?.data?.response === 'False') {
|
|
if (IsLogout !== 'Logout') {
|
|
alert('Session invalid. Redirecting to login...');
|
|
}
|
|
clearSession();
|
|
window.location.replace(commonSubDir);
|
|
}
|
|
}
|
|
};
|
|
|
|
sessionCheckFun();
|
|
}, [dependencyTrigger]);
|
|
|
|
// 🔹 Logout (shared everywhere)
|
|
const logout = async () => {
|
|
const UserId = getSession('UserId');
|
|
try {
|
|
await dispatch(GenerateLogout({ UserId, status: 'N' })).unwrap();
|
|
} finally {
|
|
sessionStorage.clear();
|
|
window.location.replace(commonSubDir);
|
|
}
|
|
};
|
|
|
|
return { sessionData, logout };
|
|
};
|
|
|
|
export default useSessionManager;
|