0
0
Fork 0

FEAT: SETiNTERVAL WITH RENEWpERIOD

This commit is contained in:
Javier Segarra 2024-04-22 07:37:35 +02:00
parent aecea5f273
commit 2b24e18f75
4 changed files with 64 additions and 26 deletions

View File

@ -10,6 +10,7 @@ const TOKEN = 'token';
export function useSession() { export function useSession() {
const { notify } = useNotify(); const { notify } = useNotify();
let isCheckingToken = false; let isCheckingToken = false;
let intervalId = null;
function getToken() { function getToken() {
const localToken = localStorage.getItem(TOKEN); const localToken = localStorage.getItem(TOKEN);
@ -24,14 +25,25 @@ export function useSession() {
return localTokenMultimedia || sessionTokenMultimedia || ''; return localTokenMultimedia || sessionTokenMultimedia || '';
} }
function setToken(data) { function setSession(data) {
let keepLogin = data.keepLogin ?? sessionStorage.getItem('keepLogin'); let keepLogin = data.keepLogin;
if (!keepLogin) keepLogin = false;
const storage = keepLogin ? localStorage : sessionStorage; const storage = keepLogin ? localStorage : sessionStorage;
storage.setItem(TOKEN, data.token); storage.setItem(TOKEN, data.token);
storage.setItem(TOKEN_MULTIMEDIA, data.tokenMultimedia); storage.setItem(TOKEN_MULTIMEDIA, data.tokenMultimedia);
storage.setItem('created', data.created);
storage.setItem('ttl', data.ttl);
sessionStorage.setItem('keepLogin', keepLogin); sessionStorage.setItem('keepLogin', keepLogin);
} }
function keepLogin() {
return sessionStorage.getItem('keepLogin');
}
function setToken({ token, tokenMultimedia }) {
const storage = keepLogin() ? localStorage : sessionStorage;
storage.setItem(TOKEN, token);
storage.setItem(TOKEN_MULTIMEDIA, tokenMultimedia);
}
async function destroyToken(url, storage, key) { async function destroyToken(url, storage, key) {
if (storage.getItem(key)) { if (storage.getItem(key)) {
try { try {
@ -50,11 +62,15 @@ export function useSession() {
tokenMultimedia: 'Accounts/logout', tokenMultimedia: 'Accounts/logout',
token: 'VnUsers/logout', token: 'VnUsers/logout',
}; };
const storage = keepLogin() ? localStorage : sessionStorage;
for (const [key, url] of Object.entries(tokens)) { for (const [key, url] of Object.entries(tokens)) {
await destroyToken(url, localStorage, key); await destroyToken(url, storage, key);
await destroyToken(url, sessionStorage, key);
} }
localStorage.clear();
sessionStorage.clear();
const { setUser } = useState(); const { setUser } = useState();
setUser({ setUser({
@ -68,25 +84,33 @@ export function useSession() {
stopRenewer(); stopRenewer();
} }
async function login(token, tokenMultimedia, keepLogin) { async function login(data) {
setToken({ token, tokenMultimedia, keepLogin }); setSession(data);
await useRole().fetch(); await useRole().fetch();
await useUserConfig().fetch(); await useUserConfig().fetch();
await useTokenConfig().fetch(); await useTokenConfig().fetch();
startInterval();
await checkValidity();
} }
function isLoggedIn() { function isLoggedIn() {
const localToken = localStorage.getItem(TOKEN); const localToken = localStorage.getItem(TOKEN);
const sessionToken = sessionStorage.getItem(TOKEN); const sessionToken = sessionStorage.getItem(TOKEN);
startInterval();
return !!(localToken || sessionToken); return !!(localToken || sessionToken);
} }
function startInterval() {
stopRenewer();
const renewPeriod = +sessionStorage.getItem('renewPeriod');
if (!renewPeriod) return;
intervalId = setInterval(() => checkValidity(), renewPeriod * 1000);
// JUST FOR TEST
// checkValidity();
}
function stopRenewer() { function stopRenewer() {
clearInterval(this.intervalId); clearInterval(intervalId);
} }
async function renewToken() { async function renewToken() {
@ -98,24 +122,32 @@ export function useSession() {
const tokenMultimedia = await axios.post('VnUsers/renewToken', { const tokenMultimedia = await axios.post('VnUsers/renewToken', {
headers: { Authorization: _tokenMultimedia }, headers: { Authorization: _tokenMultimedia },
}); });
setToken({ token, tokenMultimedia }); setToken({ token: token.data.id, tokenMultimedia: tokenMultimedia.data.id });
} }
async function checkValidity() { async function checkValidity() {
const { getTokenConfig } = useState(); const { getTokenConfig } = useState();
const tokenConfig = getTokenConfig(); const tokenConfig = getTokenConfig() ?? sessionStorage.getItem('tokenConfig');
const created = +localStorage.getItem('created'); const storage = keepLogin() ? localStorage : sessionStorage;
const ttl = localStorage.getItem('ttl');
const created = +storage.getItem('created');
const ttl = +storage.getItem('ttl');
if (isCheckingToken || !created) return; if (isCheckingToken || !created) return;
isCheckingToken = true; isCheckingToken = true;
const renewPeriodInSeconds = Math.min(ttl, tokenConfig.value.renewPeriod) * 1000; const renewPeriodInSeconds = Math.min(ttl, tokenConfig.value.renewPeriod) * 1000;
const maxDate = created + renewPeriodInSeconds;
const now = new Date();
if (now.getTime() <= maxDate) return (isCheckingToken = false); const maxDate = created + renewPeriodInSeconds;
const now = new Date().getTime();
//COMMENT THIS IF JUST FOR TEST
if (isNaN(renewPeriodInSeconds) || now <= maxDate) {
console.error('Token not renewed');
return (isCheckingToken = false);
}
console.error('Token renewed');
await renewToken(); await renewToken();
isCheckingToken = false; isCheckingToken = false;

View File

@ -8,15 +8,13 @@ export function useTokenConfig() {
async function fetch() { async function fetch() {
try { try {
let tokenConfigState = state.getTokenConfig(); const { data } = await axios.get('AccessTokenConfigs/findOne', {
if (tokenConfigState) return tokenConfigState;
const tokenConfig = await axios.get('AccessTokenConfigs/findOne', {
filter: { fields: ['renewInterval', 'renewPeriod'] }, filter: { fields: ['renewInterval', 'renewPeriod'] },
}); });
if (!tokenConfig) return; if (!data) return;
state.setTokenConfig(tokenConfig); state.setTokenConfig(data);
return tokenConfig; sessionStorage.setItem('renewPeriod', data.renewPeriod);
return data;
} catch (error) { } catch (error) {
notify('errors.tokenConfig', 'negative'); notify('errors.tokenConfig', 'negative');
console.error('Error fetching token config:', error); console.error('Error fetching token config:', error);

View File

@ -38,7 +38,13 @@ async function onSubmit() {
if (!multimediaToken) return; if (!multimediaToken) return;
await session.login(data.token, multimediaToken.id, keepLogin.value); const login = {
...data,
created: Date.now(),
tokenMultimedia: multimediaToken.id,
keepLogin: keepLogin.value,
};
await session.login(login);
quasar.notify({ quasar.notify({
message: t('login.loginSuccess'), message: t('login.loginSuccess'),

View File

@ -12,6 +12,7 @@ import { useSession } from 'src/composables/useSession';
import { useRole } from 'src/composables/useRole'; import { useRole } from 'src/composables/useRole';
import { useUserConfig } from 'src/composables/useUserConfig'; import { useUserConfig } from 'src/composables/useUserConfig';
import { toLowerCamel } from 'src/filters'; import { toLowerCamel } from 'src/filters';
import { useTokenConfig } from 'src/composables/useTokenConfig';
const state = useState(); const state = useState();
const session = useSession(); const session = useSession();
@ -55,6 +56,7 @@ export default route(function (/* { store, ssrContext } */) {
if (stateRoles.length === 0) { if (stateRoles.length === 0) {
await useRole().fetch(); await useRole().fetch();
await useUserConfig().fetch(); await useUserConfig().fetch();
await useTokenConfig().fetch();
} }
const matches = to.matched; const matches = to.matched;
const hasRequiredRoles = matches.every((route) => { const hasRequiredRoles = matches.every((route) => {