121 lines
2.6 KiB
JavaScript
121 lines
2.6 KiB
JavaScript
/**
|
||
* 认证工具函数
|
||
*/
|
||
|
||
/**
|
||
* 检查用户是否已登录
|
||
* @returns {boolean} 是否已登录
|
||
*/
|
||
export function checkLogin() {
|
||
const token = uni.getStorageSync('token');
|
||
const userId = uni.getStorageSync('userId');
|
||
return !!(token && userId);
|
||
}
|
||
|
||
/**
|
||
* 清除所有用户登录信息
|
||
*/
|
||
export function clearLoginInfo() {
|
||
uni.removeStorageSync('token');
|
||
uni.removeStorageSync('userId');
|
||
uni.removeStorageSync('userInfo');
|
||
uni.removeStorageSync('nickname');
|
||
uni.removeStorageSync('userNickname');
|
||
uni.removeStorageSync('userPhone');
|
||
uni.removeStorageSync('username');
|
||
uni.removeStorageSync('avatarUrl');
|
||
}
|
||
|
||
/**
|
||
* 退出登录
|
||
* @param {Function} callback 退出成功后的回调
|
||
*/
|
||
export function logout(callback) {
|
||
uni.showModal({
|
||
title: '退出登录',
|
||
content: '确定要退出登录吗?',
|
||
success: (res) => {
|
||
if (res.confirm) {
|
||
// 清除所有用户数据
|
||
clearLoginInfo();
|
||
|
||
uni.showToast({
|
||
title: '已退出登录',
|
||
icon: 'success',
|
||
duration: 1500
|
||
});
|
||
|
||
// 跳转到登录页
|
||
setTimeout(() => {
|
||
uni.reLaunch({
|
||
url: '/pages/login/login'
|
||
});
|
||
|
||
if (callback) {
|
||
callback();
|
||
}
|
||
}, 1500);
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 要求用户登录
|
||
* @param {string} message 提示消息
|
||
* @param {Function} onConfirm 确认后的回调
|
||
* @param {boolean} showCancel 是否显示取消按钮,默认true
|
||
*/
|
||
export function requireLogin(message = '请先登录后再使用此功能', onConfirm, showCancel = true) {
|
||
uni.showModal({
|
||
title: '提示',
|
||
content: message,
|
||
confirmText: '去登录',
|
||
cancelText: '取消',
|
||
showCancel: showCancel,
|
||
success: (res) => {
|
||
if (res.confirm) {
|
||
if (onConfirm) {
|
||
onConfirm();
|
||
} else {
|
||
uni.navigateTo({
|
||
url: '/pages/login/login'
|
||
});
|
||
}
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 检查登录并执行操作
|
||
* @param {Function} action 需要执行的操作
|
||
* @param {string} message 未登录时的提示消息
|
||
* @returns {boolean} 是否已登录
|
||
*/
|
||
export function checkLoginAndDo(action, message = '请先登录后再使用此功能') {
|
||
if (!checkLogin()) {
|
||
requireLogin(message);
|
||
return false;
|
||
}
|
||
if (action) {
|
||
action();
|
||
}
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* 获取用户信息
|
||
* @returns {Object} 用户信息对象
|
||
*/
|
||
export function getUserInfo() {
|
||
return {
|
||
token: uni.getStorageSync('token') || '',
|
||
userId: uni.getStorageSync('userId') || '',
|
||
userPhone: uni.getStorageSync('userPhone') || '',
|
||
userNickname: uni.getStorageSync('userNickname') || '',
|
||
username: uni.getStorageSync('username') || '',
|
||
avatarUrl: uni.getStorageSync('avatarUrl') || ''
|
||
};
|
||
}
|