@@ -12,8 +12,23 @@ export type User = {
12
12
}
13
13
14
14
export const useAuthStore = defineStore ( 'auth' , ( ) => {
15
+ const config = useRuntimeConfig ( ) ;
16
+
17
+ const tokenCookie = useCookie ( 'token' , {
18
+ path : '/' ,
19
+ sameSite : 'strict' ,
20
+ secure : config . public . apiBase . startsWith ( 'https://' ) ,
21
+ maxAge : 60 * 60 * 24 * 365
22
+ } ) ;
23
+
24
+ const loggedCookie = useCookie ( 'logged' , {
25
+ path : '/' ,
26
+ sameSite : 'strict' ,
27
+ secure : config . public . apiBase . startsWith ( 'https://' ) ,
28
+ maxAge : 60 * 60 * 24 * 365
29
+ } ) ;
30
+
15
31
const user = ref ( < User > { } ) ;
16
- const logged = computed ( ( ) => ! ! user . value ?. ulid ) ;
17
32
18
33
const { refresh : logout } = useHttp < any > ( 'logout' , {
19
34
method : 'POST' ,
@@ -35,13 +50,45 @@ export const useAuthStore = defineStore('auth', () => {
35
50
}
36
51
} ) ;
37
52
53
+ function fetchCsrf ( ) : void {
54
+ $http ( '/sanctum/csrf-cookie' , {
55
+ baseURL : config . public . apiBase ,
56
+ credentials : 'include' ,
57
+ headers : { Accept : 'application/json' }
58
+ } ) ;
59
+ }
60
+
61
+ async function login ( token ?: string | null ) : Promise < void > {
62
+ if ( config . public . authGuard === 'api' ) {
63
+ tokenCookie . value = token || null ;
64
+ }
65
+
66
+ loggedCookie . value = '1' ;
67
+ await fetchUser ( ) ;
68
+ }
69
+
38
70
function reset ( ) : void {
71
+ if ( config . public . authGuard === 'api' ) {
72
+ tokenCookie . value = null ;
73
+ }
74
+
75
+ loggedCookie . value = null ;
39
76
user . value = < User > { }
40
77
}
41
78
42
79
function hasRole ( name : string ) : boolean {
43
- return user . value . roles ? .includes ( name ) ;
80
+ return ( user . value . roles ?? [ ] ) . includes ( name ) ;
44
81
}
45
82
46
- return { user, logged, logout, fetchUser, reset, hasRole }
83
+ return {
84
+ user,
85
+ token : tokenCookie ,
86
+ logged : loggedCookie ,
87
+ login,
88
+ logout,
89
+ fetchUser,
90
+ fetchCsrf,
91
+ reset,
92
+ hasRole,
93
+ }
47
94
} )
0 commit comments