2021-07-09 20:10:57 +02:00
|
|
|
import {HTTPFactory} from '@/http-common'
|
2021-07-25 11:49:15 +02:00
|
|
|
import {AxiosResponse} from 'axios'
|
2021-07-09 20:10:57 +02:00
|
|
|
|
2021-07-25 11:49:15 +02:00
|
|
|
let savedToken: string | null = null
|
2021-07-09 20:10:57 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Saves a token while optionally saving it to lacal storage. This is used when viewing a link share:
|
|
|
|
* It enables viewing multiple link shares indipendently from each in multiple tabs other without overriding any other open ones.
|
|
|
|
* @param token
|
|
|
|
* @param persist
|
|
|
|
*/
|
2021-07-25 11:49:15 +02:00
|
|
|
export const saveToken = (token: string, persist: boolean) => {
|
2021-07-09 20:10:57 +02:00
|
|
|
savedToken = token
|
|
|
|
if (persist) {
|
|
|
|
localStorage.setItem('token', token)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns a saved token. If there is one saved in memory it will use that before anything else.
|
|
|
|
* @returns {string|null}
|
|
|
|
*/
|
2021-07-25 11:49:15 +02:00
|
|
|
export const getToken = (): string | null => {
|
2021-07-09 20:10:57 +02:00
|
|
|
if (savedToken !== null) {
|
|
|
|
return savedToken
|
|
|
|
}
|
|
|
|
|
|
|
|
savedToken = localStorage.getItem('token')
|
|
|
|
return savedToken
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Removes all tokens everywhere.
|
|
|
|
*/
|
|
|
|
export const removeToken = () => {
|
|
|
|
savedToken = null
|
|
|
|
localStorage.removeItem('token')
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Refreshes an auth token while ensuring it is updated everywhere.
|
|
|
|
* @returns {Promise<AxiosResponse<any>>}
|
|
|
|
*/
|
2021-07-25 11:49:15 +02:00
|
|
|
export const refreshToken = (persist: boolean): Promise<AxiosResponse> => {
|
2021-07-09 20:10:57 +02:00
|
|
|
const HTTP = HTTPFactory()
|
|
|
|
return HTTP.post('user/token', null, {
|
|
|
|
headers: {
|
|
|
|
Authorization: `Bearer ${getToken()}`,
|
|
|
|
},
|
|
|
|
})
|
|
|
|
.then(r => {
|
2021-07-25 11:49:15 +02:00
|
|
|
saveToken(r.data.token, persist)
|
2021-07-09 20:10:57 +02:00
|
|
|
return Promise.resolve(r)
|
|
|
|
})
|
|
|
|
.catch(e => {
|
|
|
|
// eslint-disable-next-line
|
|
|
|
console.log('Error renewing token: ', e)
|
|
|
|
return Promise.reject(e)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|