• Stars
    star
    241
  • Rank 167,643 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 6 years ago
  • Updated almost 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Vue.js plugin that protects routes based on user roles. Add your own authentication.

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.

📖 Usage

Check out the demo here.

Installation

$ npm i vue-router-user-roles

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>

📜 Changelog

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

❗ Issues

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

đŸ’Ē Contribution

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

Šī¸ License

MIT

More Repositories

1

vue-laravel-crud

Full-stack Vue + Laravel + Axios CRUD example
PHP
380
star
2

vuex-undo-redo

Undo/Redo plugin for Vuex
JavaScript
174
star
3

vue-clock-simple

Repo for the article How To Publish Your Vue.js Component On NPM
JavaScript
88
star
4

vue-js-laravel-ssr

Source code for the article "Server-Side Rendering With Laravel & Vue.js 2.5"
PHP
70
star
5

vue-casl-demo

Repo for the article "Managing User Permissions in a VueJS App"
JavaScript
60
star
6

vue-js-laravel-multi-ssr

Source code for the article "Advanced Server-Side Rendering With Laravel & Vue: Multi-Page App"
PHP
37
star
7

vue-cli-plugin-critical

JavaScript
29
star
8

vue-dynamic-import

Repo for the article "Build A Lazy-Load Router With Vue.js And The Latest Browser Features"
JavaScript
28
star
9

vue-web-component

An example web component createed with Vue CLI 3
Vue
18
star
10

fake-ssr-vue-laravel

Fake server-side rendering with Vue.js and Laravel
PHP
18
star
11

vue-single-file-js-components

JavaScript
12
star
12

vue-webpack-brunch

Comparison of Webpack and Brunch using Vue.js
JavaScript
11
star
13

hcwp-demo

Demo of HTML Critical Webpack Plugin
JavaScript
10
star
14

oldtime-cars-vue-laravel

PHP
10
star
15

vue-router-user-roles-demo

A demo of vue-router-user-roles plugin
JavaScript
9
star
16

vuex-undo-redo-example

Repo for the article "Create A Vuex Undo/Redo For VueJS"
JavaScript
6
star
17

vue-template-extension-loader

A Webpack loader for extending Vue templates
6
star
18

liveframe

Javascript library to help with manipulation of an iframe
JavaScript
6
star
19

vue-course

Vue
6
star
20

awesomer-vue

Vue
4
star
21

vuejs-chat

CSS
3
star
22

vue-apollo-hasura-infinite-scroll

JavaScript
1
star
23

vue3-component-library

JavaScript
1
star
24

react-course

Source code for the article Build an Online Course with React.
JavaScript
1
star
25

vue-vagrant-headless-chrome

Run Nightwatch E2E tests on headless chrome in a Vagrant box
Vue
1
star
26

statamic-courses-starter-kit

Antlers
1
star