guoyu/fronted_uniapp/utils/auth.js
xiao12feng8 015d10b3b5 清理
2026-01-30 18:23:58 +08:00

182 lines
6.6 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.

import config from './config.js'
import request from './request.js'
/**
* 认证相关工具
*/
export default {
/**
* 登录
* 适配后端登录接口(仅用户名登录,不需要密码)
* @param {string} username - 用户名
* @param {string} userType - 用户类型固定为student
* @param {string} code - 验证码
* @param {string} uuid - 验证码UUID
*/
async login(username, userType = 'student', code = '', uuid = '') {
try {
// 登录接口POST /login
// 登录接口不需要token需要明确指定
// 仅用户名登录,不传密码
const response = await request.post('/login', {
username,
userType,
code, // 验证码(如果需要)
uuid // 验证码UUID如果需要
}, {
loading: false, // 登录时使用自定义loading
header: {
isToken: false // 明确指定不需要token
}
})
// 响应格式:{ code: 200, msg: "操作成功", token: "xxx" }
if (response.code === 200 && response.token) {
// 保存token
uni.setStorageSync(config.TOKEN_KEY, response.token)
// 获取用户信息
try {
const userInfoResponse = await request.get('/getInfo')
if (userInfoResponse.code === 200 && userInfoResponse.user) {
const user = userInfoResponse.user
// 提取主要角色
const roles = userInfoResponse.roles || []
// 从角色中提取角色key固定为student
let primaryRole = 'student'
if (roles.length > 0) {
// 查找角色key只支持student
const roleKeys = roles.map(r => typeof r === 'string' ? r : (r.roleKey || r))
if (roleKeys.includes('student')) {
primaryRole = 'student'
} else if (roleKeys.includes('admin')) {
// admin角色映射为学员
primaryRole = 'student'
} else {
primaryRole = 'student'
}
}
// 映射字段名,保持前端一致性
const userInfo = {
userId: user.userId,
username: user.userName, // 映射 userName -> username
realName: user.nickName || user.userName, // 映射 nickName -> realName
nickName: user.nickName,
avatar: user.avatar,
role: primaryRole, // 添加 role 字段
roles: roles,
permissions: userInfoResponse.permissions || []
}
uni.setStorageSync(config.USER_INFO_KEY, userInfo)
// 登录新用户时,清除所有答题缓存(防止看到其他用户的答题记录)
try {
const storageInfo = uni.getStorageInfoSync()
storageInfo.keys.forEach(key => {
if (key.startsWith('exam_answers_')) {
uni.removeStorageSync(key)
console.log('清除旧答题缓存:', key)
}
})
} catch (e) {
console.error('清除旧答题缓存失败:', e)
}
return {
token: response.token,
userInfo: userInfo
}
}
} catch (e) {
console.error('获取用户信息失败:', e)
// 清除token
uni.removeStorageSync(config.TOKEN_KEY)
throw e
}
return {
token: response.token,
userInfo: {}
}
} else {
throw new Error(response.msg || '登录失败')
}
} catch (error) {
// 增强错误信息,便于调试
console.error('登录失败:', error)
if (error.message) {
throw error
} else {
throw new Error('登录失败,请检查网络连接和服务器地址')
}
}
},
/**
* 登出
* 适配后端登出接口
*/
async logout() {
try {
// 登出接口POST /logout
await request.post('/logout')
} catch (error) {
console.error('登出失败:', error)
// 即使登出接口失败,也清除本地数据
} finally {
// 清除本地存储
uni.removeStorageSync(config.TOKEN_KEY)
uni.removeStorageSync(config.USER_INFO_KEY)
// 清除所有考试答题缓存(防止不同用户看到对方的答题记录)
try {
const storageInfo = uni.getStorageInfoSync()
storageInfo.keys.forEach(key => {
if (key.startsWith('exam_answers_')) {
uni.removeStorageSync(key)
console.log('清除答题缓存:', key)
}
})
} catch (e) {
console.error('清除答题缓存失败:', e)
}
// 跳转到登录页
uni.reLaunch({
url: '/pages/login/login'
})
}
},
/**
* 检查是否已登录
*/
isLoggedIn() {
const token = uni.getStorageSync(config.TOKEN_KEY)
return !!token
},
/**
* 获取token
*/
getToken() {
return uni.getStorageSync(config.TOKEN_KEY)
},
/**
* 获取用户信息
*/
getUserInfo() {
return uni.getStorageSync(config.USER_INFO_KEY) || {}
},
/**
* 更新用户信息
*/
updateUserInfo(userInfo) {
uni.setStorageSync(config.USER_INFO_KEY, userInfo)
}
}