Files
ckb-SuperAdmin/Backend/src/utils/auth.js
2025-03-16 17:43:30 +08:00

97 lines
1.9 KiB
JavaScript
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import JsBase64 from 'js-base64'
const USER_TOKEN = 'MANAGE_TOKEN'
const USER_INFO = 'MANAGE_USERINFO'
const USER_SETTING = 'MANAGE_SETTING'
/**
* 设置用户授权token
*
* @param {String} token - JWT令牌
* @param {Number} expires - 过期时间戳(秒)
*/
export function setToken(token, expires) {
expires = new Date().getTime() + expires * 1000
return localStorage.setItem(
USER_TOKEN,
JSON.stringify({
token,
expires,
})
)
}
/**
* 获取授权token
* @returns {String} token
*/
export function getToken() {
const result = JSON.parse(
localStorage.getItem(USER_TOKEN) ||
JSON.stringify({
token: '',
expires: 0,
})
)
// 检查token是否过期
if (result.expires > 0 && result.expires < new Date().getTime()) {
// token已过期清除token
removeAll()
return ''
}
return result.token
}
/**
* 检查用户是否登录
* @returns {Boolean}
*/
export function isLogin() {
return !!getToken()
}
/**
* 设置用户信息
*
* @param {Object} data
*/
export function setUserInfo(data) {
localStorage.setItem(USER_INFO, JsBase64.Base64.encode(JSON.stringify(data)))
}
/**
* 获取用户信息
*/
export function getUserInfo() {
const data = JsBase64.Base64.decode(localStorage.getItem(USER_INFO) || '')
return data ? JSON.parse(data) : {}
}
/**
* 获取用户本地缓存的设置信息
*/
export function getUserSettingCache() {
const data = localStorage.getItem(USER_SETTING)
return data ? JSON.parse(data) : {}
}
/**
* 用户设置保存到浏览器缓存中
*
* @param {Object} state 用户设置相关信息
*/
export function setUserSettingCache(state) {
localStorage.setItem(USER_SETTING, JSON.stringify(state))
}
/**
* 删除用户相关缓存信息
*/
export function removeAll() {
localStorage.removeItem(USER_TOKEN)
localStorage.removeItem(USER_INFO)
//localStorage.removeItem(USER_SETTING)
}