useAuth.ts
1.78 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
import type { AuthUser } from '~/types'
import { createSharedComposable } from '@vueuse/core'
const AUTH_TOKEN_COOKIE_KEY = 'auth-token'
const _useAuth = () => {
const tokenCookie = useCookie<string | null>(AUTH_TOKEN_COOKIE_KEY, {
default: () => null,
sameSite: 'lax'
})
const token = useState<string | null>('auth-token', () => tokenCookie.value ?? null)
const user = useState<AuthUser | null>('auth-user', () => null)
const isLoadingUser = useState<boolean>('auth-loading-user', () => false)
const authApi = useAuthApi()
watch(token, (value) => {
tokenCookie.value = value
}, { immediate: true })
const isAuthenticated = computed(() => Boolean(token.value))
const clearSession = () => {
token.value = null
user.value = null
tokenCookie.value = null
}
const login = async (credentials: { username: string, password: string }) => {
const result = await authApi.login(credentials)
if (!result.success || !result.token || !result.user) {
clearSession()
return result
}
token.value = result.token
user.value = result.user
return result
}
const fetchCurrentUser = async () => {
if (!token.value) {
return null
}
isLoadingUser.value = true
try {
const result = await authApi.me()
if (!result.success || !result.user) {
clearSession()
return null
}
user.value = result.user
return result.user
} catch {
clearSession()
return null
} finally {
isLoadingUser.value = false
}
}
const logout = () => {
clearSession()
}
return {
token,
user,
isAuthenticated,
isLoadingUser,
login,
logout,
fetchCurrentUser,
clearSession
}
}
export const useAuth = createSharedComposable(_useAuth)