Skip to content

Commit

Permalink
feat(router): extract auth guard in a seperate file
Browse files Browse the repository at this point in the history
  • Loading branch information
NicolasRichel committed Jan 29, 2021
1 parent ac1d1a7 commit 6b86f51
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 13 deletions.
17 changes: 17 additions & 0 deletions src/router/guards.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { useGlobalState } from '@/state/globalState';

const authGuard = async (to, from, next) => {
const { isAuthenticated, authenticate } = useGlobalState();
if (isAuthenticated.value) {
next();
} else if (to.matched.some(r => r.meta.requiresAuth)) {
await authenticate(to.path);
next();
} else {
next();
}
};

export {
authGuard
};
20 changes: 7 additions & 13 deletions src/router/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createRouter, createWebHistory } from 'vue-router';
import { useGlobalState } from '@/state/globalState';
import { authGuard } from './guards';
import { dashboardResolver, projectsResolver, spacesResolver } from './resolvers';
// Components
import Layout from '@/Layout';
Expand All @@ -15,6 +15,7 @@ const routes = [
name: 'root',
component: Layout,
meta: {
// Protect this route and all its children with authentication
requiresAuth: true
},
children: [
Expand Down Expand Up @@ -67,23 +68,16 @@ const router = createRouter({
routes
});

router.beforeEach(async (to, from, next) => {
const { isAuthenticated, authenticate } = useGlobalState();
if (isAuthenticated.value) {
next();
} else if (to.matched.some(r => r.meta.requiresAuth)) {
await authenticate(to.path);
next();
} else {
next();
}
});
router.beforeEach( authGuard );

router.beforeResolve(to => {
to.matched.filter(
r => r.meta && r.meta.resolver
).reduce(
(chain, r) => chain.then(() => r.meta.resolver(to)), Promise.resolve()
(chain, r) => chain.then(
() => r.meta.resolver(to)
),
Promise.resolve()
);
});

Expand Down

0 comments on commit 6b86f51

Please sign in to comment.