Skip to content

Commit b9a157f

Browse files
author
Jovert Lota Palonpon
committed
[Auth] Prevent authenticating initially #21
1 parent d91daf2 commit b9a157f

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

resources/js/Backoffice.js

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ class Backoffice extends Component {
3535
const response = await axios.post('/api/auth/refresh');
3636
const token = response.data;
3737

38-
await this.setToken(token);
38+
this.setToken(token, true);
3939

4040
this.setState(prevState => {
4141
return {
@@ -63,7 +63,7 @@ class Backoffice extends Component {
6363
const token = JSON.parse(tokenString);
6464

6565
if (token) {
66-
await this.setToken(token);
66+
this.setToken(token);
6767

6868
await this.fetchUser();
6969
}
@@ -173,17 +173,27 @@ class Backoffice extends Component {
173173
* Store the authentication object as string into a persistent storage.
174174
*
175175
* @param {object} token
176+
* @param {boolean} updateExpiry
176177
*
177178
* @return {undefined}
178179
*/
179-
setToken = token => {
180+
setToken = (token, updateExpiry = false) => {
180181
// We will set a default Authorization header, this will
181182
// eliminate the need to include the Authorization header
182183
// for almost every AJAX requests.
183184
window.axios.defaults.headers.common['Authorization'] = `Bearer ${
184185
token.auth_token
185186
}`;
186187

188+
if (updateExpiry) {
189+
// Add an expired_at timestamp based in the expired_in property in the token.
190+
// A client defined expiry time makes sense here since a server time is
191+
// not what we should depend on.
192+
token.expired_at = moment()
193+
.add(token.expires_in, 'seconds')
194+
.format('YYYY-MM-DD hh:mm:ss');
195+
}
196+
187197
// Store it locally for the authentication token to persist.
188198
window.localStorage.setItem('token', JSON.stringify(token));
189199
};
@@ -269,13 +279,10 @@ class Backoffice extends Component {
269279
// Treat it as successful response.
270280
if ([200, 201].indexOf(response.status) > -1) {
271281
this.setState({
282+
retrying: false,
272283
successfulResponse: response,
273284
});
274285
}
275-
276-
this.setState({
277-
retrying: false,
278-
});
279286
}
280287

281288
return Promise.reject(error);
@@ -296,8 +303,13 @@ class Backoffice extends Component {
296303

297304
// Authenticate via Persistent Storage.
298305
const token = this.token();
306+
let expired = false;
299307

300308
if (token) {
309+
expired = token.expired_at < moment().format('YYYY-MM-DD hh:mm:ss');
310+
}
311+
312+
if (!expired) {
301313
await this.authenticate(JSON.stringify(token));
302314
}
303315

0 commit comments

Comments
 (0)