@@ -16,26 +16,25 @@ export const useAuth = () => {
16
16
17
17
export const AuthProvider = ( { afterLogin, children } ) => {
18
18
const navigate = useNavigate ( ) ;
19
+ const [ isAuthenticated , setAuthenticated ] = useState ( false ) ;
20
+ const location = useLocation ( ) ;
19
21
20
- const TOKEN_NAME = 'access_token' ;
22
+ const getAuthenticated = async ( ) => {
23
+ const result = await customAxios ( )
24
+ . get ( 'auth/authenticated-route' )
25
+ . then ( ( ) => true )
26
+ . catch ( ( ) => false ) ;
27
+ setAuthenticated ( result ) ;
28
+ } ;
21
29
22
- const token = useMemo ( ( ) => {
23
- return storage . get ( TOKEN_NAME ) ;
24
- } , [ storage ] ) ;
30
+ useEffect ( ( ) => {
31
+ getAuthenticated ( ) ;
32
+ } , [ location ] ) ;
25
33
26
- const [ isAuthenticated , setAuthenticated ] = useState ( false ) ;
34
+ const TOKEN_NAME = 'access_token' ;
35
+ const token = storage . get ( TOKEN_NAME ) ;
27
36
28
- useEffect ( ( ) => {
29
- customAxios ( )
30
- . get ( '/users/me' )
31
- . then ( ( res ) => {
32
- console . log ( res . response ) ;
33
- setAuthenticated ( true ) ;
34
- } )
35
- . catch ( ( ) => {
36
- setAuthenticated ( false ) ;
37
- } ) ;
38
- } , [ token ] ) ;
37
+ console . log ( '[Provider] token:' , token ) ;
39
38
40
39
const storeToken = ( accessToken ) => {
41
40
storage . set ( TOKEN_NAME , accessToken ) ;
@@ -48,7 +47,7 @@ export const AuthProvider = ({ afterLogin, children }) => {
48
47
const url = new URL ( location . href ) ;
49
48
const next = url . searchParams . get ( 'next' ) ;
50
49
const redirectUrl = afterLogin || next || '/' ;
51
- navigate ( redirectUrl === '/login' ? '/' : redirectUrl ) ;
50
+ navigate ( redirectUrl ) ;
52
51
} ;
53
52
54
53
const handleLogout = ( ) => {
@@ -67,10 +66,10 @@ export const AuthProvider = ({ afterLogin, children }) => {
67
66
} ;
68
67
69
68
export const ProtectedRoute = ( { redirectTo, children } ) => {
70
- const { token , isAuthenticated } = useAuth ( ) ;
69
+ const { isAuthenticated } = useAuth ( ) ;
71
70
const location = useLocation ( ) ;
72
71
73
- console . log ( 'token' , token , ' isAuthenticated', isAuthenticated ) ;
72
+ console . log ( 'isAuthenticated' , isAuthenticated ) ;
74
73
75
74
if ( ! isAuthenticated ) {
76
75
const origin = location ?. origin || window . location . origin ;
0 commit comments