@@ -4,6 +4,7 @@ import history from '../history';
44
55export default class Auth {
66 userProfile ;
7+ tokenRenewalTimeout ;
78
89 auth0 = new auth0 . WebAuth ( {
910 domain : AUTH_CONFIG . domain ,
@@ -21,6 +22,7 @@ export default class Auth {
2122 this . isAuthenticated = this . isAuthenticated . bind ( this ) ;
2223 this . getAccessToken = this . getAccessToken . bind ( this ) ;
2324 this . getProfile = this . getProfile . bind ( this ) ;
25+ this . scheduleRenewal ( ) ;
2426 }
2527
2628 login ( ) {
@@ -49,6 +51,10 @@ export default class Auth {
4951 localStorage . setItem ( 'access_token' , authResult . accessToken ) ;
5052 localStorage . setItem ( 'id_token' , authResult . idToken ) ;
5153 localStorage . setItem ( 'expires_at' , expiresAt ) ;
54+
55+ // schedule a token renewal
56+ this . scheduleRenewal ( ) ;
57+
5258 // navigate to the home route
5359 history . replace ( '/home' ) ;
5460 }
@@ -78,6 +84,7 @@ export default class Auth {
7884 localStorage . removeItem ( 'expires_at' ) ;
7985 localStorage . removeItem ( 'scopes' ) ;
8086 this . userProfile = null ;
87+ clearTimeout ( this . tokenRenewalTimeout ) ;
8188 // navigate to the home route
8289 history . replace ( '/home' ) ;
8390 }
@@ -90,17 +97,32 @@ export default class Auth {
9097 }
9198
9299 renewToken ( ) {
93- this . auth0 . renewAuth ( {
94- audience : AUTH_CONFIG . apiUrl ,
95- redirectUri : 'http://localhost:3001/silent' ,
96- usePostMessage : true
97- } , ( err , result ) => {
98- if ( err ) {
99- alert ( `Could not get a new token using silent authentication (${ err . error } ).` ) ;
100- } else {
101- alert ( `Successfully renewed auth!` ) ;
102- this . setSession ( result ) ;
100+ this . auth0 . renewAuth (
101+ {
102+ audience : AUTH_CONFIG . apiUrl ,
103+ redirectUri : AUTH_CONFIG . silentAuthRedirect ,
104+ usePostMessage : true
105+ } ,
106+ ( err , result ) => {
107+ if ( err ) {
108+ alert (
109+ `Could not get a new token using silent authentication (${ err . error } ).`
110+ ) ;
111+ } else {
112+ this . setSession ( result ) ;
113+ alert ( `Successfully renewed auth!` ) ;
114+ }
103115 }
104- } ) ;
116+ ) ;
117+ }
118+
119+ scheduleRenewal ( ) {
120+ const expiresAt = JSON . parse ( localStorage . getItem ( 'expires_at' ) ) ;
121+ const delay = expiresAt - Date . now ( ) ;
122+ if ( delay > 0 ) {
123+ this . tokenRenewalTimeout = setTimeout ( ( ) => {
124+ this . renewToken ( ) ;
125+ } , delay ) ;
126+ }
105127 }
106128}
0 commit comments