1+ "use client" ;
2+
13import React , { useState , useContext , useEffect } from "react" ;
4+ import { useRouter } from "next/navigation" ;
25
36interface AuthContextType {
47 getAccessToken : ( ) => Promise < string > ;
@@ -14,6 +17,7 @@ export function useAuth() {
1417export const AuthProvider : React . FC < { children : React . ReactNode } > = ( { children } ) => {
1518 const [ accessToken , setAccessToken ] = useState ( "" ) ;
1619 const [ expiryTime , setExpiryTime ] = useState ( 0 ) ;
20+ const [ shouldRedirect , setShouldRedirect ] = useState ( false ) ;
1721
1822 async function getAccessToken ( ) : Promise < string > {
1923 if ( Date . now ( ) >= expiryTime ) {
@@ -24,28 +28,38 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
2428 }
2529
2630 useEffect ( ( ) => {
31+ if ( typeof window === "undefined" ) return ;
2732 getAccessToken ( ) ;
2833 } , [ ] ) ;
2934
35+ const router = useRouter ( ) ;
3036 async function refreshAccessToken ( ) : Promise < string > {
3137 try {
3238 const response = await fetch ( "http://localhost:8000/refresh" , {
3339 method : "POST" ,
3440 credentials : "include" ,
3541 } ) ;
36-
37- if ( ! response . ok ) throw new Error ( "Failed to refresh token" ) ;
3842 const data = await response . json ( ) ;
39-
43+ if ( ! response . ok ) {
44+ setShouldRedirect ( true ) ;
45+ console . log ( "Failed to refresh access token" ) ;
46+ }
4047 setAccessToken ( data . access_token ) ;
4148 setExpiryTime ( Date . now ( ) + 15 * 60 * 1000 ) ; // 15 minutes
4249 return data . access_token ;
4350 } catch ( error ) {
44- console . error ( "Error refreshing access token:" , error ) ;
51+ setShouldRedirect ( true ) ;
52+ console . log ( "Error refreshing access token:" , error ) ;
4553 return "" ;
4654 }
4755 }
4856
57+ useEffect ( ( ) => {
58+ if ( shouldRedirect ) {
59+ router . push ( "/login" ) ;
60+ }
61+ } , [ shouldRedirect , router ] ) ;
62+
4963 return (
5064 < AuthContext . Provider value = { { getAccessToken } } >
5165 { children }
0 commit comments