ai-clone/frontend-ai/utils/auth.js
2026-03-05 14:29:21 +08:00

121 lines
2.6 KiB
JavaScript
Raw Permalink 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.

/**
* 认证工具函数
*/
/**
* 检查用户是否已登录
* @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') || ''
};
}