Skip to content

Commit

Permalink
[Auth] Prevent authenticating initially #21
Browse files Browse the repository at this point in the history
  • Loading branch information
Jovert Lota Palonpon committed Mar 29, 2019
1 parent d91daf2 commit b9a157f
Showing 1 changed file with 19 additions and 7 deletions.
26 changes: 19 additions & 7 deletions resources/js/Backoffice.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class Backoffice extends Component {
const response = await axios.post('/api/auth/refresh');
const token = response.data;

await this.setToken(token);
this.setToken(token, true);

this.setState(prevState => {
return {
Expand Down Expand Up @@ -63,7 +63,7 @@ class Backoffice extends Component {
const token = JSON.parse(tokenString);

if (token) {
await this.setToken(token);
this.setToken(token);

await this.fetchUser();
}
Expand Down Expand Up @@ -173,17 +173,27 @@ class Backoffice extends Component {
* Store the authentication object as string into a persistent storage.
*
* @param {object} token
* @param {boolean} updateExpiry
*
* @return {undefined}
*/
setToken = token => {
setToken = (token, updateExpiry = false) => {
// We will set a default Authorization header, this will
// eliminate the need to include the Authorization header
// for almost every AJAX requests.
window.axios.defaults.headers.common['Authorization'] = `Bearer ${
token.auth_token
}`;

if (updateExpiry) {
// Add an expired_at timestamp based in the expired_in property in the token.
// A client defined expiry time makes sense here since a server time is
// not what we should depend on.
token.expired_at = moment()
.add(token.expires_in, 'seconds')
.format('YYYY-MM-DD hh:mm:ss');
}

// Store it locally for the authentication token to persist.
window.localStorage.setItem('token', JSON.stringify(token));
};
Expand Down Expand Up @@ -269,13 +279,10 @@ class Backoffice extends Component {
// Treat it as successful response.
if ([200, 201].indexOf(response.status) > -1) {
this.setState({
retrying: false,
successfulResponse: response,
});
}

this.setState({
retrying: false,
});
}

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

// Authenticate via Persistent Storage.
const token = this.token();
let expired = false;

if (token) {
expired = token.expired_at < moment().format('YYYY-MM-DD hh:mm:ss');
}

if (!expired) {
await this.authenticate(JSON.stringify(token));
}

Expand Down

0 comments on commit b9a157f

Please sign in to comment.