Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@this-dot/vue-route-guard

Package Overview
Dependencies
Maintainers
6
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@this-dot/vue-route-guard

Vuejs helper library for adding guards to route

  • 1.0.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
6
Created
Source

Vue Route Guard 🛡️

Vue Route Guard is an Vue library that wraps around the vue-router and extends it to provide helpful methods to handle page guards via token authorization and permissions.

It supports:

✅  Adding guards to pages
✅  Ability to choose between different storage options for storing token
✅  Storing and Retrieving authentication data (user details and token)
✅  Exposes method for checking matching page permission within components and pages


Installation

Install the package:
npm install @this-dot/vue-route-guard
or
yarn add @this-dot/vue-route-guard

Usage

To get started, we will need to register Vue Route Guard.

Register using Vue.use

It is very simple to add route guard to your Vue app:

Just import the setupGuard module

import { setupGuard } from '@this-dot/vue-route-guard';

Install the plugin

vue.use(setupGuard(guardConfig));

Router Meta

We extended the default router meta to accept the following fields:

FieldDescriptionRequiredType
requiresAuthDescribes if the page requires authenticationtrueboolean
accessDescribes the access permissions needed for the routefalsestring[]

Guard Config

setupGuard requires to pass an object with the following fields:

FieldDescriptionRequiredType
routerThe router instance used in your vue apptrueRouter
token.nameThe name used to store and retrieve the tokentruestring
token.storageStorage type (This defaults to session storage)falseStorageType
redirect.noAuthenticationpage to redirect to if no token found or fetchAuthentication failsfalseRouteLocationRaw
redirect.noPermissionpage to redirect to if permission is not in route meta access (redirects to noAuthentication if it is not passed)falseRouteLocationRaw
redirect.clearAuthenticationpage to redirect to after clearing authentication (redirects to noAuthentication if it is not passed)falseRouteLocationRaw
options.fetchAuthenticationThis is expects function that returns an object with the authentication informationtruePromise<{}>
options.permissionKeyDescribes the field that holds the authentication permission in fetchAuthentication (default permission)falsestring
Example

Create a sample router and guard configuration:

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/HomeView.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
      meta: { requiresAuth: false },
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('../views/AboutView.vue'),
      meta: {
        requiresAuth: true,
        access: ['admin'],
      },
    },
    {
      path: '/no-permission',
      name: 'no-permission',
      component: () => import('../views/NoPermissionView.vue'),
      meta: {
        requiresAuth: false,
      },
    },
  ],
});
const guardConfig = {
  router: router,
  token: {
    name: 'XSRF-TOKEN',
  },
  redirect: {
    noAuthentication: '/login',
    clearAuthentication: '/login',
    noPermission: '/no-permission',
  },
  options: {
    fetchAuthentication: () => {
      return new Promise(function (resolve, reject) {
        return resolve({
          firstName: 'firstName',
          lastName: 'lastName',
          login: true,
          permission: ['user'],
        });
      });
    },
  },
};
vue.use(setupGuard(guardConfig));

Create a guard config using token. expires: it can be a valid date string or a number to represent the days path: page path for cookie

const guardConfig = {
  router: router,
  token: {
    name: 'XSRF-TOKEN',
    storage: StorageType.cookieStorage,
    attributes: {
      path: '/',
      expires: 2, // cookie to expire in 2 days
    },
  },
  redirect: {
    noAuthentication: '/login',
    clearAuthentication: '/login',
    noPermission: '/no-permission',
  },
  options: {
    fetchAuthentication: () => {
      return new Promise(function (resolve, reject) {
        return resolve({
          firstName: 'firstName',
          lastName: 'lastName',
          login: true,
          permission: ['user'],
        });
      });
    },
  },
};

Access Authentication State

<template>
  <div>{{ auth.$store.state.authentication }}</div>
</template>
<script setup lang="ts">
  import { useGuard } from '@this-dot/vue-route-guard';

  const auth = useGuard();
</script>

Clear Authentication

<script setup lang="ts">
  import { useGuard } from '@this-dot/vue-route-guard';

  const auth = useGuard();

  const logout = () => {
    auth.clearAuthentication().then(() => {
      console.log('cleared authentication');
    });
  };
</script>

Refresh Authentication

This calls fetch authentication and updates the state with the new authentication details

<template>
  <div>
    <span>{{ auth.$store.state.authentication }}</span>
    <button @click="updateAuthentiationInformation">Update</button>
  </div>
</template>
<script setup lang="ts">
  import { useGuard } from '@this-dot/vue-route-guard';

  const auth = useGuard();

  const updateAuthentiationInformation = () => {
    auth.refreshAuthentication();
  };
</script>

Check if user has access

hasAuthenticationAccess can be accessed from useGuard and called to check if user has access to specific permission

<template>
  <header>
    <div class="wrapper">
      <nav>
        <RouterLink to="/">Home</RouterLink>
        <RouterLink v-if="auth.hasAuthenticationAccess(['admin'])" to="/about">About</RouterLink>
      </nav>
    </div>
  </header>

  <RouterView />
</template>

<script setup lang="ts">
  import { useGuard } from '@ds-library/ui';

  const auth = useGuard();
</script>

Keywords

FAQs

Package last updated on 03 Nov 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc