1
1
import axios from '@/lib/axios' ;
2
2
import { useParams , useRouter } from 'next/navigation' ;
3
- import { useEffect } from 'react' ;
3
+ import { useCallback , useEffect } from 'react' ;
4
4
import useSWR from 'swr' ;
5
5
6
6
export const useAuth = ( { middleware, redirectIfAuthenticated } = { } ) => {
@@ -21,12 +21,20 @@ export const useAuth = ({ middleware, redirectIfAuthenticated } = {}) => {
21
21
} ) ,
22
22
) ;
23
23
24
- // Add role checking utilities
25
24
const isAdmin = user ?. role === 'admin' ;
26
25
const isUser = user ?. role === 'user' ;
27
26
28
27
const csrf = ( ) => axios . get ( '/sanctum/csrf-cookie' ) ;
29
28
29
+ // Wrap logout in useCallback
30
+ const logout = useCallback ( async ( ) => {
31
+ if ( ! error ) {
32
+ await axios . post ( '/logout' ) . then ( ( ) => mutate ( ) ) ;
33
+ }
34
+
35
+ window . location . pathname = '/login' ;
36
+ } , [ error , mutate ] ) ;
37
+
30
38
const register = async ( { setErrors, ...props } ) => {
31
39
await csrf ( ) ;
32
40
@@ -94,22 +102,23 @@ export const useAuth = ({ middleware, redirectIfAuthenticated } = {}) => {
94
102
axios . post ( '/email/verification-notification' ) . then ( ( response ) => setStatus ( response . data . status ) ) ;
95
103
} ;
96
104
97
- const logout = async ( ) => {
98
- if ( ! error ) {
99
- await axios . post ( '/logout' ) . then ( ( ) => mutate ( ) ) ;
105
+ useEffect ( ( ) => {
106
+ if ( middleware === 'guest' && redirectIfAuthenticated && user ) {
107
+ router . push ( redirectIfAuthenticated ) ;
100
108
}
101
109
102
- window . location . pathname = '/login' ;
103
- } ;
104
-
105
- useEffect ( ( ) => {
106
- if ( middleware === 'guest' && redirectIfAuthenticated && user ) router . push ( redirectIfAuthenticated ) ;
110
+ if ( middleware === 'auth' && ! user ?. email_verified_at ) {
111
+ router . push ( '/verify-email' ) ;
112
+ }
107
113
108
- if ( middleware === 'auth' && ! user ?. email_verified_at ) router . push ( '/verify-email' ) ;
114
+ if ( window . location . pathname === '/verify-email' && user ?. email_verified_at ) {
115
+ router . push ( redirectIfAuthenticated ) ;
116
+ }
109
117
110
- if ( window . location . pathname === '/verify-email' && user ?. email_verified_at ) router . push ( redirectIfAuthenticated ) ;
111
- if ( middleware === 'auth' && error ) logout ( ) ;
112
- } , [ user , error ] ) ;
118
+ if ( middleware === 'auth' && error ) {
119
+ logout ( ) ;
120
+ }
121
+ } , [ user , error , router , middleware , redirectIfAuthenticated , logout ] ) ;
113
122
114
123
return {
115
124
user,
0 commit comments