@@ -56,8 +56,9 @@ const createAuthMiddleware = () => {
5656          }  else  { 
5757            // User was loaded - our accessToken is good 
5858            loadProfile ( accessToken ,  ( err ,  profile )  =>  { 
59-               if  ( err )  return  next ( fetchProfileFailure ( err ) ) ; 
60-               if  ( profile )  { 
59+               if  ( err )  { 
60+                 next ( fetchProfileFailure ( err ) ) ; 
61+               }  else  if  ( profile )  { 
6162                const  profileParams  =  { 
6263                  uphillMax : profile . uphill_max , 
6364                  downhillMax : profile . downhill_max , 
@@ -88,7 +89,34 @@ const createAuthMiddleware = () => {
8889          // TODO: Save "last location" in localStorage and redirect there. 
8990          // TODO: Just send a new action and let reducers / thunk handle this 
9091          next ( logIn ( access_token ,  refresh_token ) ) ; 
92+           // FIXME: this is a race condition - fetch profile in logIn action 
9193          next ( fetchProfileRequest ( ) ) ; 
94+         }  else  if  ( action . payload . route . name  ===  "signin" )  { 
95+           // Check for user credentials and redirect to appropriate location 
96+           const  {  accessToken,  refreshToken }  =  store . getState ( ) . auth ; 
97+           loadUser ( accessToken ,  err  =>  { 
98+             if  ( err )  { 
99+               // Failed to load user. Attempt to get new JWT using refresh token. 
100+               if  ( ! refreshToken )  { 
101+                 // TODO: use a less awkward redirect. 
102+                 // No refresh token - user must log in 
103+                 window . location  =  "/api/v1/auth/login" ; 
104+               } 
105+               next ( refreshTokenRequest ( ) ) ; 
106+               refresh ( refreshToken ,  ( err ,  newAccessToken )  =>  { 
107+                 if  ( err )  { 
108+                   // Refresh token is bad / otherwise failed. Need a fresh login. 
109+                   window . location  =  "/api/v1/auth/login" ; 
110+                 }  else  { 
111+                   // Refresh token worked - fire login 
112+                   next ( logIn ( newAccessToken ,  refresh_token ) ) ; 
113+                 } 
114+               } ) ; 
115+             }  else  { 
116+               // User was successfully loaded. All is well - redirect to main site. 
117+               window . location  =  "/" ; 
118+             } 
119+           } ) ; 
92120        } 
93121        break ; 
94122      } 
0 commit comments