✨ 新增功能: - 全局路由守卫模块 (route-guard.js) - 多层次权限验证 (登录状态+Token存在+Token过期检查) - 自动拦截机制 (页面级+跳转级+HTTP级+应用级) - 401响应自动处理和跳转 - 路由守卫测试页面 🔧 技术实现: - checkPageAccess() 全局页面权限检查 - guardedNavigate/guardedSwitchTab 带权限检查的跳转 - handleUnauthorized() HTTP拦截器401处理 - 公开页面配置管理 - 优雅的错误提示和跳转逻辑 📱 页面集成: - App.vue 初始化路由守卫 - profile/workbench 页面添加权限检查 - index 页面优化跳转逻辑 - 新增测试页面验证功能 📚 文档完善: - 移动端路由守卫使用指南 - 详细的变更记录和技术说明 - 最佳实践和注意事项 🎯 核心效果: 用户登录失效或未登录时,访问任何需要权限的页面都自动跳转到登录页,提升安全性和用户体验。
393 lines
13 KiB
JavaScript
393 lines
13 KiB
JavaScript
import { encryptLoginData } from './encrypt-pure.js';
|
|
|
|
// API请求配置
|
|
const baseURL =
|
|
process.env.NODE_ENV === 'development'
|
|
? '/api' // 开发环境使用代理
|
|
: 'https://your-api-domain.com';
|
|
|
|
// 统一请求方法
|
|
export const request = (options) => {
|
|
return new Promise((resolve, reject) => {
|
|
// 获取token
|
|
const token = getToken();
|
|
|
|
uni.request({
|
|
url: baseURL + options.url,
|
|
method: options.method || 'GET',
|
|
data: options.data || {},
|
|
header: {
|
|
'Content-Type': 'application/json',
|
|
authorization: token,
|
|
clientid: 'e5cd7e4891bf95d1d19206ce24a7b32e',
|
|
referer: 'http://localhost/login?redirect=/index',
|
|
...options.header,
|
|
},
|
|
success: (res) => {
|
|
// 处理响应
|
|
if (res.statusCode === 200) {
|
|
// 检查业务状态码
|
|
if (res.data && res.data.code !== undefined) {
|
|
if (res.data.code === 200) {
|
|
resolve(res.data);
|
|
} else if (res.data.code === 401) {
|
|
// 401未授权,跳转到登录页
|
|
console.log('🔒 Token失效,自动跳转到登录页');
|
|
handleUnauthorized(res.data.msg || '登录已失效,请重新登录');
|
|
reject(res.data);
|
|
} else {
|
|
// 其他业务错误
|
|
uni.showToast({
|
|
title: res.data.msg || '请求失败',
|
|
icon: 'none',
|
|
});
|
|
reject(res.data);
|
|
}
|
|
} else {
|
|
resolve(res.data);
|
|
}
|
|
} else if (res.statusCode === 401) {
|
|
// HTTP 401未授权
|
|
console.log('🔒 HTTP 401未授权,自动跳转到登录页');
|
|
handleUnauthorized('登录已失效,请重新登录');
|
|
reject(res);
|
|
} else {
|
|
// 其他HTTP状态码错误
|
|
uni.showToast({
|
|
title: `请求失败: ${res.statusCode}`,
|
|
icon: 'none',
|
|
});
|
|
reject(res);
|
|
}
|
|
},
|
|
fail: (error) => {
|
|
uni.showToast({
|
|
title: '网络请求失败',
|
|
icon: 'none',
|
|
});
|
|
reject(error);
|
|
},
|
|
});
|
|
});
|
|
};
|
|
|
|
// 获取token
|
|
function getToken() {
|
|
try {
|
|
const token = uni.getStorageSync('access_token');
|
|
console.log(
|
|
'🔍 获取Token:',
|
|
token ? `Bearer ${token.substring(0, 20)}...` : '❌ Token为空',
|
|
);
|
|
return token ? `Bearer ${token}` : '';
|
|
} catch (e) {
|
|
console.error('❌ 获取Token失败:', e);
|
|
return '';
|
|
}
|
|
}
|
|
|
|
// 处理401未授权响应
|
|
function handleUnauthorized(message = '登录已失效,请重新登录') {
|
|
console.log('🔒 处理401未授权响应:', message);
|
|
|
|
// 清除登录信息
|
|
try {
|
|
uni.removeStorageSync('access_token');
|
|
uni.removeStorageSync('userInfo');
|
|
uni.removeStorageSync('isLoggedIn');
|
|
console.log('📤 已清除本地登录信息');
|
|
} catch (e) {
|
|
console.error('❌ 清除登录信息失败:', e);
|
|
}
|
|
|
|
// 显示提示信息
|
|
uni.showToast({
|
|
title: message,
|
|
icon: 'none',
|
|
duration: 2000,
|
|
});
|
|
|
|
// 延迟跳转,确保Toast显示
|
|
setTimeout(() => {
|
|
// 获取当前页面路径
|
|
const pages = getCurrentPages();
|
|
const currentPage = pages[pages.length - 1];
|
|
const currentPath = '/' + currentPage.route;
|
|
|
|
// 如果当前不是登录页,则跳转到登录页
|
|
if (currentPath !== '/pages/login/index') {
|
|
console.log('🔄 从', currentPath, '跳转到登录页');
|
|
uni.reLaunch({
|
|
url: '/pages/login/index',
|
|
fail: (error) => {
|
|
console.error('❌ 跳转登录页失败:', error);
|
|
// 如果reLaunch失败,尝试其他方式
|
|
uni.redirectTo({
|
|
url: '/pages/login/index',
|
|
});
|
|
},
|
|
});
|
|
}
|
|
}, 500);
|
|
}
|
|
|
|
// API方法封装
|
|
export const api = {
|
|
// 用户登录
|
|
login: async (data) => {
|
|
try {
|
|
console.log('🔐 开始加密登录流程...');
|
|
|
|
// 加密登录数据
|
|
const encryptResult = encryptLoginData({
|
|
username: data.username,
|
|
password: data.password,
|
|
tenantId: data.tenantId || '000000',
|
|
clientId: data.clientId || 'e5cd7e4891bf95d1d19206ce24a7b32e',
|
|
grantType: data.grantType || 'password',
|
|
});
|
|
|
|
// 如果encryptLoginData返回的是Promise,需要await
|
|
const actualEncryptResult = encryptResult.then ? await encryptResult : encryptResult;
|
|
|
|
if (!actualEncryptResult.success) {
|
|
console.error('❌ 登录数据加密失败:', actualEncryptResult.error);
|
|
throw new Error(actualEncryptResult.error);
|
|
}
|
|
|
|
console.log('✅ 登录数据加密成功,发送加密请求...');
|
|
|
|
// 使用加密数据和自定义header发送请求
|
|
return new Promise((resolve, reject) => {
|
|
uni.request({
|
|
url: baseURL + '/auth/login',
|
|
method: 'POST',
|
|
data: actualEncryptResult.encryptedData, // 发送加密字符串,不是JSON对象
|
|
header: {
|
|
...actualEncryptResult.headers,
|
|
referer: 'http://localhost/login?redirect=/index', // 添加正确格式的referer
|
|
},
|
|
success: (res) => {
|
|
console.log('🔐 加密登录响应:', res);
|
|
if (res.statusCode === 200) {
|
|
if (res.data && res.data.code !== undefined) {
|
|
if (res.data.code === 200) {
|
|
console.log('✅ 加密登录成功');
|
|
resolve(res.data);
|
|
} else {
|
|
console.log('❌ 登录失败:', res.data.msg);
|
|
uni.showToast({
|
|
title: res.data.msg || '登录失败',
|
|
icon: 'none',
|
|
});
|
|
reject(res.data);
|
|
}
|
|
} else {
|
|
resolve(res.data);
|
|
}
|
|
} else {
|
|
console.log('❌ HTTP状态错误:', res.statusCode);
|
|
uni.showToast({
|
|
title: `请求失败: ${res.statusCode}`,
|
|
icon: 'none',
|
|
});
|
|
reject(res);
|
|
}
|
|
},
|
|
fail: (error) => {
|
|
console.log('❌ 登录请求失败:', error);
|
|
uni.showToast({
|
|
title: '网络请求失败',
|
|
icon: 'none',
|
|
});
|
|
reject(error);
|
|
},
|
|
});
|
|
});
|
|
} catch (error) {
|
|
console.error('❌ 登录加密处理失败:', error);
|
|
console.error('❌ 错误详情:', error.message);
|
|
console.error('❌ 错误堆栈:', error.stack);
|
|
uni.showToast({
|
|
title: '登录处理失败: ' + error.message,
|
|
icon: 'none',
|
|
});
|
|
return Promise.reject(error);
|
|
}
|
|
},
|
|
|
|
// 获取用户信息
|
|
getUserInfo: () => {
|
|
const token = getToken();
|
|
console.log(
|
|
'🎫 获取用户信息,当前token:',
|
|
token ? token.substring(0, 20) + '...' : '无token',
|
|
);
|
|
|
|
return request({
|
|
url: '/system/user/getInfo',
|
|
method: 'GET',
|
|
header: {
|
|
authorization: token,
|
|
clientid: 'e5cd7e4891bf95d1d19206ce24a7b32e',
|
|
referer: 'http://localhost/login?redirect=/index',
|
|
},
|
|
});
|
|
},
|
|
|
|
// 获取租户列表
|
|
getTenantList: (isToken = false) =>
|
|
request({
|
|
url: '/auth/tenant/list',
|
|
method: 'GET',
|
|
header: {
|
|
isToken: isToken,
|
|
},
|
|
}),
|
|
|
|
// 注销登录
|
|
logout: () =>
|
|
request({
|
|
url: '/auth/logout',
|
|
method: 'POST',
|
|
}),
|
|
};
|
|
|
|
// 用户信息缓存工具
|
|
export const userStorage = {
|
|
// 保存登录信息
|
|
saveLoginInfo: (loginResult, userInfo) => {
|
|
try {
|
|
// 保存token
|
|
uni.setStorageSync('access_token', loginResult.access_token);
|
|
|
|
// 保存用户信息(增加登录时间)
|
|
if (userInfo) {
|
|
const enhancedUserInfo = {
|
|
...userInfo,
|
|
loginTime: new Date().toISOString(), // 记录登录时间
|
|
tokenExpireTime: loginResult.expires_in
|
|
? new Date(Date.now() + loginResult.expires_in * 1000).toISOString()
|
|
: null,
|
|
};
|
|
uni.setStorageSync('userInfo', JSON.stringify(enhancedUserInfo));
|
|
}
|
|
|
|
// 保存登录状态
|
|
uni.setStorageSync('isLoggedIn', true);
|
|
|
|
// 保存其他token信息
|
|
if (loginResult.refresh_token) {
|
|
uni.setStorageSync('refresh_token', loginResult.refresh_token);
|
|
}
|
|
|
|
console.log('用户登录信息已保存', {
|
|
hasToken: !!loginResult.access_token,
|
|
hasUserInfo: !!userInfo,
|
|
loginTime: new Date().toLocaleString(),
|
|
});
|
|
} catch (e) {
|
|
console.error('保存登录信息失败:', e);
|
|
}
|
|
},
|
|
|
|
// 获取用户信息
|
|
getUserInfo: () => {
|
|
try {
|
|
const userInfo = uni.getStorageSync('userInfo');
|
|
return userInfo ? JSON.parse(userInfo) : null;
|
|
} catch (e) {
|
|
console.error('获取用户信息失败:', e);
|
|
return null;
|
|
}
|
|
},
|
|
|
|
// 获取token
|
|
getToken: () => {
|
|
try {
|
|
return uni.getStorageSync('access_token') || '';
|
|
} catch (e) {
|
|
return '';
|
|
}
|
|
},
|
|
|
|
// 检查登录状态
|
|
isLoggedIn: () => {
|
|
try {
|
|
const isLoggedIn = uni.getStorageSync('isLoggedIn');
|
|
const token = uni.getStorageSync('access_token');
|
|
return !!(isLoggedIn && token);
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
},
|
|
|
|
// 清除登录信息
|
|
clearLoginInfo: () => {
|
|
try {
|
|
uni.removeStorageSync('access_token');
|
|
uni.removeStorageSync('userInfo');
|
|
uni.removeStorageSync('isLoggedIn');
|
|
console.log('用户登录信息已清除');
|
|
} catch (e) {
|
|
console.error('清除登录信息失败:', e);
|
|
}
|
|
},
|
|
};
|
|
|
|
// 数据缓存工具
|
|
export const storage = {
|
|
// 设置缓存
|
|
set: (key, value, expire) => {
|
|
try {
|
|
const data = {
|
|
value,
|
|
timestamp: Date.now(),
|
|
expire: expire ? Date.now() + expire * 1000 : null,
|
|
};
|
|
uni.setStorageSync(key, JSON.stringify(data));
|
|
} catch (e) {
|
|
console.error('缓存设置失败:', e);
|
|
}
|
|
},
|
|
|
|
// 获取缓存
|
|
get: (key) => {
|
|
try {
|
|
const data = uni.getStorageSync(key);
|
|
if (!data) return null;
|
|
|
|
const parsed = JSON.parse(data);
|
|
|
|
// 检查是否过期
|
|
if (parsed.expire && Date.now() > parsed.expire) {
|
|
uni.removeStorageSync(key);
|
|
return null;
|
|
}
|
|
|
|
return parsed.value;
|
|
} catch (e) {
|
|
console.error('缓存获取失败:', e);
|
|
return null;
|
|
}
|
|
},
|
|
|
|
// 删除缓存
|
|
remove: (key) => {
|
|
try {
|
|
uni.removeStorageSync(key);
|
|
} catch (e) {
|
|
console.error('缓存删除失败:', e);
|
|
}
|
|
},
|
|
|
|
// 清空缓存
|
|
clear: () => {
|
|
try {
|
|
uni.clearStorageSync();
|
|
} catch (e) {
|
|
console.error('缓存清空失败:', e);
|
|
}
|
|
},
|
|
};
|