auth.js
2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
* @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
const authKey = Symbol('auth')
/**
* 提供认证功能的组合式函数
*/
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) {
// 只有在token未过期的情况下才恢复用户信息
if (checkTokenExpiration()) {
currentUser.value = JSON.parse(savedUser)
}
}
loading.value = false
})
// 登录函数
const login = (userData) => {
currentUser.value = userData
if (currentUser.value) {
try {
localStorage.setItem('currentUser', JSON.stringify(userData))
localStorage.setItem('loginTimestamp', Date.now().toString())
} catch (error) {
console.error('Failed to save user data to localStorage:', error)
}
}
return true
}
// 登出函数
const logout = () => {
currentUser.value = null
localStorage.removeItem('currentUser')
localStorage.removeItem('loginTimestamp')
}
// 提供认证上下文
provide(authKey, {
currentUser,
loading,
login,
logout
})
return {
currentUser,
loading,
login,
logout
}
}
/**
* 使用认证功能的组合式函数
* @returns {Object} 认证上下文值
*/
export function useAuth() {
const auth = inject(authKey)
if (!auth) {
throw new Error('useAuth 必须在 provideAuth 的范围内使用')
}
return auth
}