Last active
July 8, 2020 02:25
-
-
Save james0r/5a0c8f40167a9ae2ed5e9574906b85ad to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"; | |
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment