UNPKG

@hperchec/scorpion-ui-template-default

Version:
56 lines (52 loc) 1.78 kB
/** * @vuepress * --- * title: Router - AuthMiddleware * headline: Router - AuthMiddleware * sidebarTitle: .AuthMiddleware * sidebarDepth: 0 # To disable auto sidebar links * prev: false # Disable prev link * next: false # Disable prev link * --- */ import { Core } from '@hperchec/scorpion-ui' const log = (...args) => Core.context.services['router'].options.log(...args) // eslint-disable-line dot-notation /** * @name AuthMiddleware * @static * @type {Function} * @return {void} * @description * > {@link ../../../ context}.{@link ../../ router}.{@link ../ middlewares}.{@link ./ AuthMiddleware} * * See also [vue-router beforeEnter guard documentation](https://v3.router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards) * * Authentication middleware. * * Check if route `meta.requiresAuth` is `true` and redirect to `/login` if user is not authenticated. */ export default async (to, from, next) => { if (to.matched.some(record => record.meta.requiresAuth)) { log(`[AuthMiddleware] Route "${to.fullPath}" requires authentication`, { type: 'router', prod: false }) // this route requires auth, check if logged in if (!Core.service('store').state.Core.Auth.currentUser) { log('[AuthMiddleware] Not authenticated ❌ Redirect to login page', { type: 'router' }) // If target '/' -> no redirect if (to.fullPath === '/') { next({ path: '/login' }) // Else, get to.fullPath to redirect after login } else { next({ path: '/login', query: { redirect: to.fullPath } }) } } else { next() } } else { next() // make sure to always call next()! } }