template-demo/utils/auth.js

270 lines
5.8 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} 是否已登录
*/
function isLoggedIn() {
const userId = wx.getStorageSync('userId')
const token = wx.getStorageSync('token')
return !!(userId && token)
}
/**
* 获取用户信息
* @returns {Object|null} 用户信息对象或null
*/
function getUserInfo() {
if (!isLoggedIn()) {
return null
}
const userInfo = wx.getStorageSync('userInfo')
return userInfo || null
}
/**
* 获取用户ID
* @returns {String|null} 用户ID或null
*/
function getUserId() {
return wx.getStorageSync('userId') || null
}
/**
* 获取Token
* @returns {String|null} Token或null
*/
function getToken() {
return wx.getStorageSync('token') || null
}
/**
* 检查登录状态,未登录则跳转登录页
* @param {Object} options 配置项
* @param {String} options.returnUrl 登录成功后返回的页面URL
* @param {String} options.returnType 返回类型: navigateTo/redirectTo/switchTab
* @param {Function} options.success 已登录时的回调
* @param {Function} options.fail 未登录时的回调
* @returns {Boolean} 是否已登录
*/
function checkLogin(options = {}) {
const {
returnUrl = '',
returnType = 'navigateTo',
success,
fail
} = options
if (isLoggedIn()) {
// 已登录
success && success()
return true
} else {
// 未登录,跳转登录页
fail && fail()
// 保存返回信息
if (returnUrl) {
wx.setStorageSync('returnTo', {
url: returnUrl,
type: returnType
})
}
wx.navigateTo({
url: '/pages/login/login'
})
return false
}
}
/**
* 要求登录后执行操作
* @param {Function} callback 登录后执行的回调
* @param {Object} options 配置项
*/
function requireLogin(callback, options = {}) {
return checkLogin({
...options,
success: callback,
fail: () => {
wx.showToast({
title: '请先登录',
icon: 'none',
duration: 2000
})
}
})
}
/**
* 保存用户信息到本地
* @param {Object} data 用户数据
* @param {String} data.userId 用户ID
* @param {String} data.token Token
* @param {Object} data.userInfo 用户信息
*/
function saveUserData(data) {
const { userId, token, userInfo } = data
if (userId) {
wx.setStorageSync('userId', userId)
}
if (token) {
wx.setStorageSync('token', token)
}
if (userInfo) {
wx.setStorageSync('userInfo', userInfo)
}
}
/**
* 清除用户登录信息
*/
function clearUserData() {
wx.removeStorageSync('userId')
wx.removeStorageSync('token')
wx.removeStorageSync('userInfo')
}
/**
* 跳转到登录页面(带返回功能)
* 参考 checkin.js 的实现,显示弹窗确认后跳转登录页
* @param {Object} options 配置项
* @param {String} options.message 提示信息
* @param {String} options.returnUrl 登录成功后返回的页面URL不传则自动获取当前页面
* @param {String} options.returnType 返回类型: navigateTo/redirectTo/switchTab
* @param {Boolean} options.showCancel 是否显示取消按钮
* @param {Function} options.onCancel 取消回调
*/
function navigateToLogin(options = {}) {
const {
message = '请先登录',
returnUrl = '',
returnType = 'navigateTo',
showCancel = true,
onCancel = null
} = options
// 自动获取当前页面路径
let finalReturnUrl = returnUrl
if (!finalReturnUrl) {
const pages = getCurrentPages()
if (pages.length > 0) {
const currentPage = pages[pages.length - 1]
finalReturnUrl = '/' + currentPage.route
// 添加页面参数
if (currentPage.options && Object.keys(currentPage.options).length > 0) {
const params = Object.keys(currentPage.options)
.map(key => `${key}=${currentPage.options[key]}`)
.join('&')
finalReturnUrl += '?' + params
}
}
}
wx.showModal({
title: '提示',
content: message,
confirmText: '去登录',
cancelText: '返回',
showCancel: showCancel,
success: (res) => {
if (res.confirm) {
// 保存返回信息,登录成功后返回当前页面
if (finalReturnUrl) {
wx.setStorageSync('returnTo', {
type: returnType,
url: finalReturnUrl
})
}
wx.redirectTo({
url: '/pages/login/login'
})
} else {
// 点击取消
if (onCancel) {
onCancel()
}
}
}
})
}
/**
* 退出登录
* @param {Object} options 配置项
* @param {String} options.redirectUrl 退出后跳转的页面
* @param {Boolean} options.confirm 是否需要确认
* @param {Function} options.success 成功回调
*/
function logout(options = {}) {
const {
redirectUrl = '/pages/home/home',
confirm = true,
success
} = options
const doLogout = () => {
clearUserData()
wx.showToast({
title: '已退出登录',
icon: 'success',
duration: 1500
})
setTimeout(() => {
success && success()
// 跳转到指定页面
if (redirectUrl.startsWith('/pages/home/') ||
redirectUrl.startsWith('/pages/index/') ||
redirectUrl.startsWith('/pages/record/') ||
redirectUrl.startsWith('/pages/settings/')) {
wx.reLaunch({
url: redirectUrl
})
} else {
wx.redirectTo({
url: redirectUrl
})
}
}, 1500)
}
if (confirm) {
wx.showModal({
title: '退出登录',
content: '确定要退出登录吗?',
success: (res) => {
if (res.confirm) {
doLogout()
}
}
})
} else {
doLogout()
}
}
module.exports = {
isLoggedIn,
getUserInfo,
getUserId,
getToken,
checkLogin,
requireLogin,
navigateToLogin,
saveUserData,
clearUserData,
logout
}