forked from labex-labs/python-cheatsheet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseAuth.ts
More file actions
75 lines (65 loc) · 1.76 KB
/
useAuth.ts
File metadata and controls
75 lines (65 loc) · 1.76 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
import { ref } from 'vue'
interface UserInfo {
id?: number
name?: string
nick_name?: string
email?: string
img_url?: string
[key: string]: unknown
}
interface UserData {
user?: UserInfo
[key: string]: unknown
}
const user = ref<UserInfo | null>(null)
const isLoading = ref(false)
const isAuthenticated = ref(false)
export function useAuth() {
const checkAuth = async (): Promise<void> => {
if (typeof window === 'undefined') {
return
}
isLoading.value = true
try {
const basePath = import.meta.env.BASE_URL || '/pythoncheatsheet/'
const apiPath = basePath.endsWith('/') ? `${basePath}api/user/me` : `${basePath}/api/user/me`
const response = await fetch(apiPath, {
method: 'GET',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
})
if (response.ok) {
const userData = await response.json() as UserData
user.value = userData.user || null
isAuthenticated.value = true
} else {
user.value = null
isAuthenticated.value = false
}
} catch (error) {
console.error('Error checking auth status:', error)
user.value = null
isAuthenticated.value = false
} finally {
isLoading.value = false
}
}
const login = () => {
if (typeof window !== 'undefined') {
const currentPath = window.location.pathname
// Ensure we have a valid path to redirect back to
const redirectPath = currentPath && currentPath !== '/' ? currentPath : '/pythoncheatsheet/'
const rd = encodeURIComponent(redirectPath)
window.open(`https://labex.io/register?rd=${rd}`, '_blank')
}
}
return {
user,
isLoading,
isAuthenticated,
checkAuth,
login,
}
}