82 lines
1.9 KiB
JavaScript
82 lines
1.9 KiB
JavaScript
/**
|
|
* 用户授权工具
|
|
* 登录检查、授权跳转、退出登录
|
|
*
|
|
* 新流程:
|
|
* - App.vue 检查 JWT,无则跳转 /pages/auth/loading
|
|
* - loading 页发起 OAuth → 获取 code → 调用 /login
|
|
* - 未注册用户跳转 /pages/register/register
|
|
*/
|
|
|
|
/**
|
|
* 检查是否已登录
|
|
* @returns {boolean}
|
|
*/
|
|
export function isLoggedIn() {
|
|
return !!uni.getStorageSync('token');
|
|
}
|
|
|
|
/**
|
|
* 检查登录状态,未登录时弹窗引导
|
|
* @param {string} scene - 触发场景:'order' | 'mine' | 'pay'
|
|
* @returns {boolean} 是否已登录
|
|
*/
|
|
export function checkLoginWithPrompt(scene = '') {
|
|
if (isLoggedIn()) return true;
|
|
|
|
const SCENE_TIPS = {
|
|
order: '登录后即可查看订单',
|
|
mine: '登录后即可查看个人信息',
|
|
pay: '登录后即可下单购买',
|
|
};
|
|
|
|
uni.showModal({
|
|
title: '提示',
|
|
content: SCENE_TIPS[scene] || '需要登录后操作',
|
|
confirmText: '去登录',
|
|
cancelText: '暂不',
|
|
success: (res) => {
|
|
if (res.confirm) {
|
|
// 跳转到授权 Loading 页
|
|
uni.redirectTo({ url: '/pages/auth/loading' });
|
|
}
|
|
},
|
|
});
|
|
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* 检查登录状态,未登录时静默跳转
|
|
* @returns {boolean} 是否已登录
|
|
*/
|
|
export function requireLogin() {
|
|
if (isLoggedIn()) return true;
|
|
uni.redirectTo({ url: '/pages/auth/loading' });
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* 退出登录
|
|
*/
|
|
export function logout() {
|
|
uni.removeStorageSync('token');
|
|
uni.removeStorageSync('user_info');
|
|
uni.removeStorageSync('auth_info');
|
|
uni.removeStorageSync('temp_token');
|
|
}
|
|
|
|
/**
|
|
* 获取缓存的用户信息
|
|
* @returns {Object|null}
|
|
*/
|
|
export function getCachedUserInfo() {
|
|
try {
|
|
const userInfo = uni.getStorageSync('user_info');
|
|
console.log('[auth-guard] getCachedUserInfo raw:', JSON.stringify(userInfo, null, 2));
|
|
return userInfo || null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|