Skip to content

Instantly share code, notes, and snippets.

@kirkbushell
Created January 7, 2016 22:41

Revisions

  1. kirkbushell created this gist Jan 7, 2016.
    13 changes: 13 additions & 0 deletions Interceptor.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    import Unauthorised from './Unauthorised'

    export default function() {
    return {
    response: function(response) {
    switch (response.status) {
    case 401: return Unauthorised.handle();
    }

    return response;
    }
    }
    };
    34 changes: 34 additions & 0 deletions Unauthorised.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    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';
    }
    };