Skip to content

Instantly share code, notes, and snippets.

@james0r
Last active July 8, 2020 02:25
Show Gist options
  • Select an option

  • Save james0r/5a0c8f40167a9ae2ed5e9574906b85ad to your computer and use it in GitHub Desktop.

Select an option

Save james0r/5a0c8f40167a9ae2ed5e9574906b85ad to your computer and use it in GitHub Desktop.

Revisions

  1. james0r revised this gist Jul 8, 2020. 1 changed file with 0 additions and 1 deletion.
    1 change: 0 additions & 1 deletion router
    Original file line number Diff line number Diff line change
    @@ -5,7 +5,6 @@ import Signin from "./views/Signin.vue";
    import Home from "./components/ClientsComponent";
    import axios from "axios";
    import { API_URL } from "./constants";
    // import router from "../../server/routes/api/v1/providers";

    const url = API_URL + "secret";

  2. james0r created this gist Jul 8, 2020.
    69 changes: 69 additions & 0 deletions router
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,69 @@
    import Vue from "vue";
    import Router from "vue-router";
    import Signup from "./views/Signup.vue";
    import Signin from "./views/Signin.vue";
    import Home from "./components/ClientsComponent";
    import axios from "axios";
    import { API_URL } from "./constants";
    // import router from "../../server/routes/api/v1/providers";

    const url = API_URL + "secret";

    Vue.use(Router);

    async function validateJWT() {
    if (localStorage.token) {
    const config = {
    headers: { Authorization: `Bearer ${localStorage.token}` },
    };

    let validated = false;

    await axios.get(url, config).then(function(response) {
    console.log( response );
    return response.status === 200;
    });
    } else {
    return false;
    }
    }

    const router = new Router({
    mode: "history",
    routes: [
    {
    path: "/signup",
    name: "signup",
    component: Signup,
    },
    {
    path: "/signin",
    name: "signin",
    component: Signin,
    },
    {
    path: "/",
    name: "Home",
    component: Home,
    },
    ],
    });

    // protect the access
    router.beforeEach((to, from, next) => {
    const publicPages = ['/signin', '/signup'];
    const authRequired = !publicPages.includes(to.path);
    const token = localStorage.getItem('token');

    // trying to access a restricted page + not logged in
    // redirect to login page
    if (authRequired && !token) {
    next('/signin');
    } else {
    validateJWT().then(() => {
    next();
    })
    }
    });

    export default router;