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

vue-router-user-roles

v0.1.92

Published

A Vue.js plugin that protects routes based on user roles

Downloads

123

Readme

vue-router-user-roles

Build status Coverage Status

npm vue2

A plugin for Vue.js SPAs that protects routes depending on user role. Add your own authentication.

:book: Usage

Check out the demo here.

Installation

$ npm i vue-router-user-roles -D

First create a Vue Router instance. It's best to do this in a dedicated file and export as a module e.g.

// router.js

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

export default new VueRouter(...);

Now you can add this plugin in your main file. You must pass in a router instance as an option router.

// main.js

import Vue from "vue";
import router from "./router";
import VueRouterUserRoles from "vue-router-user-roles";

Vue.use(VueRouterUserRoles, { router });

Protecting routes

To protect a route, add a permissions property to each route configuration object under the meta property.

Assign an array of objects to this, with each object defining the permissions for a different user role.

The three properties required for permissions objects are:

  • role - the user role being configured for this route.
  • access - either a boolean, or function returning a boolean, that defines access for the user. A function will have access to two objects: the user object and the route being accessed.
  • redirect - a route name you wish to redirect to if the user does not have access.
let opts = {
  routes: [
    {
      path: "/protected",
      name: "protected",
      component: Protected,
      meta: {
        permissions: [
          {
            role: "guest",
            access: false,
            redirect: "login"
          }
        ]
      }
    },
    {
      path: "/profile/:id",
      name: "profile",
      component: Profile,
      meta: {
        permissions: [
          {
            role: "registered",
            access: (user, to) => user.id === to.params.id,
            redirect: "login"
          },
          {
            role: "guest",
            access: false,
            redirect: "login"
          }
        ]
      }
    }
  ]
};

const router = new VueRouter(opts);

User

A "user" is an object with one required property: role. Typically this would be set to a string e.g. "guest", "admin" etc.

You can add other properties to this object. You may want to do that if route access is determined by a function, since the function is passed this object. For example, you may create an id property that could be compared to a route parameter e.g /user/:id

Once the plugin is installed, you can access user from within your Vue instance or any component as this.$user.

Set the user

You can set a user with the set method. Here's an example of setting the user before the first instance of Vue is created:

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import VueRouterUserRoles from "vue-router-user-roles";

Vue.use(VueRouterUserRoles, router);

// This would usually be an AJAX call to the server or a cookie check
// Let's assume the user hasn't logged in yet so they're a guest for now.
let authenticate = Promise.resolve({ role: "guest" });

authenticate.then(user => {
  Vue.prototype.$user.set(user);
  new Vue({
    render: h => h(App),
    router
  }).$mount("#app");
});

You'll probably set the user again during the lifecycle of the app. For example, a user may start as a guest, but once they're authenticated their role and permissions will change.

You can access user from within the app as this.$user e.g.

export default {
  methods: {
    logIn(username, password) {
      authenticate("/api/user", { username, password })
        .then(user => {
          this.$user.set(Object.assign(user, { role: "registered" }));
        });
    },
    logOut() {
      this.$user.set({ role: "guest" });
    }
  }
}

The user object is reactive, so each time you set the user, permissions will be reassessed and will potentially redirect the page if the user no longer has access to the current route.

The other API method available is get:

<template>
  <div v-if="$user.get().role === 'guest'">...</div>
</template>

:scroll: Changelog

Details changes for each release are documented in the CHANGELOG.md.

:exclamation: Issues

Please make sure to read the Issue Reporting Checklist before opening an issue. Issues not conforming to the guidelines may be closed immediately.

:muscle: Contribution

Please make sure to read the Contributing Guide before making a pull request.

:copyright: License

MIT