dingdanquanliucheng/frontend/mini-app/utils/auth.js
2026-06-22 14:59:51 +08:00

69 lines
1.5 KiB
JavaScript
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.

/**
* 统一登录态管理模块
* 职责Token 和用户信息的存取、角色查询、退出登录清理。
*/
const TOKEN_KEY = "auth_token";
const USER_KEY = "user_info";
const TOKEN_EXP_KEY = "auth_token_exp";
function getToken() {
return wx.getStorageSync(TOKEN_KEY) || "";
}
function setToken(token, expiresInSeconds) {
wx.setStorageSync(TOKEN_KEY, token);
if (expiresInSeconds) {
// 计算过期时间戳(毫秒)
var expTime = Date.now() + expiresInSeconds * 1000;
wx.setStorageSync(TOKEN_EXP_KEY, expTime);
}
}
function getUser() {
return wx.getStorageSync(USER_KEY) || null;
}
function setUser(user) {
wx.setStorageSync(USER_KEY, user);
}
function getUserRole() {
var user = getUser();
return user ? user.role_code || "" : "";
}
function isLoggedIn() {
var token = getToken();
if (!token) return false;
// 检查本地记录的过期时间
var expTime = wx.getStorageSync(TOKEN_EXP_KEY);
if (expTime && Date.now() > expTime) {
// token 已过期,清理登录态
logout();
return false;
}
return true;
}
function logout() {
wx.removeStorageSync(TOKEN_KEY);
wx.removeStorageSync(USER_KEY);
wx.removeStorageSync(TOKEN_EXP_KEY);
var app = getApp();
if (app) {
app.globalData.authToken = "";
app.globalData.userRole = "";
}
}
module.exports = {
getToken: getToken,
setToken: setToken,
getUser: getUser,
setUser: setUser,
getUserRole: getUserRole,
isLoggedIn: isLoggedIn,
logout: logout,
};