Skip to content

Instantly share code, notes, and snippets.

@vs0uz4
Forked from kirkbushell/Interceptor.js
Created October 28, 2017 07:47
Show Gist options
  • Save vs0uz4/b2bdee6e7bb34f370191fc47e0666078 to your computer and use it in GitHub Desktop.
Save vs0uz4/b2bdee6e7bb34f370191fc47e0666078 to your computer and use it in GitHub Desktop.
Handling JWT, Vue JS and token refreshes
import Unauthorised from './Unauthorised'
export default function() {
return {
response: function(response) {
switch (response.status) {
case 401: return Unauthorised.handle();
}
return response;
}
}
};
import Vue from "vue"
import JWT from "../../components/authentication/JWT"
export default {
handle: function(response) {
var retry = function() {
JWT.setToken(response.data.token);
return this.retry(response.request).then(function() {
return response;
});
}.bind(this);
// Refresh JWT, then retry previous request if successful, and catch any errors (auth fail of some kind)
return Vue.http.get('/auth/refresh')
.then(retry)
.catch(this.redirect);
},
/**
* Retries the request initially made by the app before an auth error was thrown.
*
* @param request
* @return Promise
*/
retry: function(request) {
var method = request.method.toLowerCase();
return Vue.http[method](request.url, request.params);
},
redirect: function() {
window.location.href = '/auth';
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment