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.

117 lines
2.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// utils/token.js - Token管理工具
const TOKEN_KEY = 'token';
const USER_INFO_KEY = 'userInfo';
/**
* 保存token到本地存储
* @param {string} token - 认证令牌
*/
const setToken = (token) => {
try {
wx.setStorageSync(TOKEN_KEY, token);
} catch (error) {
console.error('保存token失败:', error);
}
};
/**
* 获取本地存储的token
* @returns {string} token值
*/
const getToken = () => {
try {
return wx.getStorageSync(TOKEN_KEY) || '';
} catch (error) {
console.error('获取token失败:', error);
return '';
}
};
/**
* 删除本地存储的token
*/
const removeToken = () => {
try {
wx.removeStorageSync(TOKEN_KEY);
} catch (error) {
console.error('删除token失败:', error);
}
};
/**
* 保存用户信息到本地存储
* @param {Object} userInfo - 用户信息对象
*/
const setUserInfo = (userInfo) => {
try {
wx.setStorageSync(USER_INFO_KEY, userInfo);
} catch (error) {
console.error('保存用户信息失败:', error);
}
};
/**
* 获取本地存储的用户信息
* @returns {Object} 用户信息对象
*/
const getUserInfo = () => {
try {
return wx.getStorageSync(USER_INFO_KEY) || null;
} catch (error) {
console.error('获取用户信息失败:', error);
return null;
}
};
/**
* 删除本地存储的用户信息
*/
const removeUserInfo = () => {
try {
wx.removeStorageSync(USER_INFO_KEY);
} catch (error) {
console.error('删除用户信息失败:', error);
}
};
/**
* 清除所有认证相关信息
*/
const clearAuthData = () => {
removeToken();
removeUserInfo();
};
/**
* 检查是否已登录是否有有效token
* @returns {boolean} 是否已登录
*/
const isAuthenticated = () => {
const token = getToken();
return !!token;
};
/**
* 获取完整的认证头信息
* @returns {Object} 包含认证信息的header对象
*/
const getAuthHeader = () => {
const token = getToken();
return {
'Content-Type': 'application/json',
'Authorization': token ? `Bearer ${token}` : ''
};
};
module.exports = {
setToken,
getToken,
removeToken,
setUserInfo,
getUserInfo,
removeUserInfo,
clearAuthData,
isAuthenticated,
getAuthHeader
};