-
-
Notifications
You must be signed in to change notification settings - Fork 190
Expand file tree
/
Copy pathcommonAuthState.ts
More file actions
59 lines (49 loc) · 1.34 KB
/
commonAuthState.ts
File metadata and controls
59 lines (49 loc) · 1.34 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
import { computed } from 'vue'
import type { SessionLastRefreshedAt, SessionStatus } from '../types'
import type { AuthError } from '../utils/authError'
import { useState } from '#imports'
export function makeCommonAuthState<SessionData>() {
const data = useState<SessionData | undefined | null>('auth:data', () => undefined)
const hasInitialSession = computed(() => !!data.value)
// If session exists, initialize as already synced
const lastRefreshedAt = useState<SessionLastRefreshedAt>('auth:lastRefreshedAt', () => {
if (hasInitialSession.value) {
return new Date()
}
return undefined
})
// If session exists, initialize as not loading
const loading = useState<boolean>('auth:loading', () => false)
// Error state for tracking authentication errors
const error = useState<AuthError | null>('auth:error', () => null)
const status = computed<SessionStatus>(() => {
if (loading.value) {
return 'loading'
}
if (data.value) {
return 'authenticated'
}
return 'unauthenticated'
})
/**
* Set error state
*/
function setError(authError: AuthError | null) {
error.value = authError
}
/**
* Clear error state
*/
function clearError() {
error.value = null
}
return {
data,
loading,
lastRefreshedAt,
status,
error,
setError,
clearError
}
}