0
0
Fork 0

refs #7190 feat: renewToken

This commit is contained in:
Javier Segarra 2024-04-19 12:26:43 +02:00
parent fb26219354
commit aecea5f273
2 changed files with 50 additions and 1 deletions

View File

@ -3,11 +3,13 @@ import { useRole } from './useRole';
import { useUserConfig } from './useUserConfig';
import axios from 'axios';
import useNotify from './useNotify';
import { useTokenConfig } from './useTokenConfig';
const TOKEN_MULTIMEDIA = 'tokenMultimedia';
const TOKEN = 'token';
export function useSession() {
const { notify } = useNotify();
let isCheckingToken = false;
function getToken() {
const localToken = localStorage.getItem(TOKEN);
@ -23,9 +25,12 @@ export function useSession() {
}
function setToken(data) {
const storage = data.keepLogin ? localStorage : sessionStorage;
let keepLogin = data.keepLogin ?? sessionStorage.getItem('keepLogin');
if (!keepLogin) keepLogin = false;
const storage = keepLogin ? localStorage : sessionStorage;
storage.setItem(TOKEN, data.token);
storage.setItem(TOKEN_MULTIMEDIA, data.tokenMultimedia);
sessionStorage.setItem('keepLogin', keepLogin);
}
async function destroyToken(url, storage, key) {
if (storage.getItem(key)) {
@ -59,6 +64,8 @@ export function useSession() {
lang: '',
darkMode: null,
});
stopRenewer();
}
async function login(token, tokenMultimedia, keepLogin) {
@ -66,6 +73,9 @@ export function useSession() {
await useRole().fetch();
await useUserConfig().fetch();
await useTokenConfig().fetch();
await checkValidity();
}
function isLoggedIn() {
@ -75,6 +85,42 @@ export function useSession() {
return !!(localToken || sessionToken);
}
function stopRenewer() {
clearInterval(this.intervalId);
}
async function renewToken() {
const _token = getToken();
const token = await axios.post('VnUsers/renewToken', {
headers: { Authorization: _token },
});
const _tokenMultimedia = getTokenMultimedia();
const tokenMultimedia = await axios.post('VnUsers/renewToken', {
headers: { Authorization: _tokenMultimedia },
});
setToken({ token, tokenMultimedia });
}
async function checkValidity() {
const { getTokenConfig } = useState();
const tokenConfig = getTokenConfig();
const created = +localStorage.getItem('created');
const ttl = localStorage.getItem('ttl');
if (isCheckingToken || !created) return;
isCheckingToken = true;
const renewPeriodInSeconds = Math.min(ttl, tokenConfig.value.renewPeriod) * 1000;
const maxDate = created + renewPeriodInSeconds;
const now = new Date();
if (now.getTime() <= maxDate) return (isCheckingToken = false);
await renewToken();
isCheckingToken = false;
}
return {
getToken,
getTokenMultimedia,

View File

@ -8,6 +8,9 @@ export function useTokenConfig() {
async function fetch() {
try {
let tokenConfigState = state.getTokenConfig();
if (tokenConfigState) return tokenConfigState;
const tokenConfig = await axios.get('AccessTokenConfigs/findOne', {
filter: { fields: ['renewInterval', 'renewPeriod'] },
});