hookehuyr

fix(auth): 添加token过期检查并修复toast样式导入

在auth.js中添加了token过期检查功能,确保用户信息在token过期时不会被恢复。同时,在fn.js中修复了toast样式未导入的问题,确保toast显示正常。
/*
* @Date: 2022-05-18 22:56:08
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2023-02-10 15:13:01
* @FilePath: /data-table/src/api/fn.js
* @LastEditTime: 2025-03-21 18:05:34
* @FilePath: /mlaj/src/api/fn.js
* @Description: 文件描述
*/
import axios from '@/utils/axios';
import qs from 'Qs'
import { showSuccessToast, showFailToast } from 'vant';
import 'vant/lib/toast/style'
/**
* 网络请求功能函数
......@@ -49,7 +50,7 @@ export const uploadFn = (api) => {
// tslint:disable-next-line: no-console
console.warn(res);
if (!res.data.show) return false;
Toast({
showFailToast({
icon: 'close',
message: res.data.msg,
});
......
/*
* @Date: 2025-03-20 21:11:31
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2025-03-22 10:08:20
* @FilePath: /mlaj/src/contexts/auth.js
* @Description: 文件描述
*/
import { ref, provide, inject, onMounted } from 'vue'
// 创建认证上下文的key
......@@ -10,11 +17,29 @@ export function provideAuth() {
const currentUser = ref(null)
const loading = ref(true)
// 检查token是否过期(24小时)
const checkTokenExpiration = () => {
const loginTimestamp = localStorage.getItem('loginTimestamp')
if (loginTimestamp) {
const now = Date.now()
const diff = now - parseInt(loginTimestamp)
if (diff > 24 * 60 * 60 * 1000) { // 24小时
// 清理登录状态并返回false表示token已过期
logout()
return false
}
}
return true
}
// 初始化时检查本地存储的用户信息
onMounted(() => {
const savedUser = localStorage.getItem('currentUser')
if (savedUser) {
currentUser.value = JSON.parse(savedUser)
// 只有在token未过期的情况下才恢复用户信息
if (checkTokenExpiration()) {
currentUser.value = JSON.parse(savedUser)
}
}
loading.value = false
})
......@@ -23,6 +48,7 @@ export function provideAuth() {
const login = (userData) => {
currentUser.value = userData
localStorage.setItem('currentUser', JSON.stringify(userData))
localStorage.setItem('loginTimestamp', Date.now().toString())
return true
}
......@@ -30,6 +56,7 @@ export function provideAuth() {
const logout = () => {
currentUser.value = null
localStorage.removeItem('currentUser')
localStorage.removeItem('loginTimestamp')
}
// 提供认证上下文
......