You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
fms/functions/token.ts

131 lines
2.9 KiB

export interface TokenData<T=any> {
payload: T
headers: Record<string, any>
}
const isClient = () => {
return typeof window !== 'undefined'
}
export const storeToken = (token: string) => {
if (!isClient()) {
return;
}
let tokenData = grabTokenData(token)
let tokenId = tokenData?.payload?.id;
if (!tokenId) {
return;
}
let tokens: string | null = window.localStorage.getItem('tokens')
let tokensData: string[] = JSON.parse(tokens || '[]');
if (!tokensData) {
return
}
window.localStorage.setItem('token', tokenId)
window.localStorage.setItem(tokenId, token)
tokensData.push(tokenId)
window.localStorage.setItem('tokens', JSON.stringify(tokensData))
}
export const cleanToken = (id: string) => {
if (!isClient()) {
return;
}
let tokens: string | null = window.localStorage.getItem('tokens')
let tokensData: string[] = JSON.parse(tokens || '[]');
if (!tokensData) {
return
}
tokensData = tokensData.filter((storedTokenId: string) => storedTokenId !== id)
window.localStorage.setItem('tokens', JSON.stringify(tokensData))
window.localStorage.removeItem(id)
// Чистим текущий токен
let activeTokenId: string | null = window.localStorage.getItem('token')
if (id === activeTokenId) {
window.localStorage.removeItem('token')
}
}
export const selectToken = (id: string) => {
if (!isClient()) {
return;
}
window.localStorage.setItem('token', id)
}
export const grabTokenData = (token: string): TokenData|null => {
if (!isClient()) {
return null
}
const parts = token.split('.')
if (parts.length !== 3) {
return null
}
let payload = JSON.parse(window.atob(parts[1]))
if (!payload){
return null
}
let headers = JSON.parse(window.atob(parts[0]))
if (!headers){
return null
}
return {
payload,
headers,
};
}
export const grabRawToken = (): string | null => {
if (!isClient()) {
return null
}
const tokenId = window.localStorage.getItem('token')
if (!tokenId) {
return null
}
return window.localStorage.getItem(tokenId)
}
export const grabToken = (): TokenData | null => {
const token = grabRawToken()
if (!token) {
return null
}
return grabTokenData(token);
}
export const grabTokens = (): TokenData[] => {
if (!isClient()) {
return []
}
const storedTokens = window.localStorage.getItem('tokens')
let tokens: string[] = JSON.parse(storedTokens || '[]');
if (!tokens) {
return []
}
let result: TokenData[] = []
tokens.forEach((tokenId) => {
let token = window.localStorage.getItem(tokenId)
if (!token) {
return true
}
let tokenData = grabTokenData(token)
if (tokenData) {
result.push(tokenData)
}
})
return result
}