npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@this-dot/vue-route-guard

v1.0.0

Published

Vuejs helper library for adding guards to route

Downloads

17

Readme

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:

| Field | Description | Required | Type | | ------------ | ----------------------------------------------------- | -------- | -------- | | requiresAuth | Describes if the page requires authentication | true | boolean | | access | Describes the access permissions needed for the route | false | string[] |

Guard Config

setupGuard requires to pass an object with the following fields:

| Field | Description | Required | Type | | ---------------------------- | ----------------------------------------------------------------------------------------------------------------- | -------- | ---------------- | | router | The router instance used in your vue app | true | Router | | token.name | The name used to store and retrieve the token | true | string | | token.storage | Storage type (This defaults to session storage) | false | StorageType | | redirect.noAuthentication | page to redirect to if no token found or fetchAuthentication fails | false | RouteLocationRaw | | redirect.noPermission | page to redirect to if permission is not in route meta access (redirects to noAuthentication if it is not passed) | false | RouteLocationRaw | | redirect.clearAuthentication | page to redirect to after clearing authentication (redirects to noAuthentication if it is not passed) | false | RouteLocationRaw | | options.fetchAuthentication | This is expects function that returns an object with the authentication information | true | Promise<{}> | | options.permissionKey | Describes the field that holds the authentication permission in fetchAuthentication (default permission) | false | string |

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>