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-and-router-guards

v1.0.1

Published

Vue-router guards for auth and access checks

Downloads

20

Readme

Vue Router Guards

This is a package with 2 vue-router guards:

  • Authorization Guard
  • Access Guard

Authorization Guard

This guard is used to check user's authorization status before resolving any route

Example


// vue-router.js

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

import cookies from 'js-cookie';
import configs from "@configs";
import store from '@store';

import {authCheckGuard} from 'vue-and-router-guards'
import routes from './routes';

Vue.use(VueRouter);

export const router = new VueRouter({routes});


/**
 * =============
 * Global hooks
 * =============
 *
 * Set global hooks for vue-router
 */

/*
 * Set guard to check authorized status
 */
router.beforeEach((to, from, next) => authCheckGuard(to, from, next, {

    // Set redirect to auth
    redirect: {name: 'system.auth', replace: true},

    // Has client session or not
    hasSession: !!cookies.get(configs.cookieSession),

    // Check if authorized or not
    isAuthorized: store.getters['account/authorized'],

    // Send action to get user data
    // Return promise
    getUser: (next, redirect) => {
        return new Promise((resolve, reject) => {
                store
                    .dispatch('account/user')
                    .then(_ => store.getters['account/authorized'] === true ? resolve() : reject())
            }
        )
    }
}));

Arguments

  • to — the target Route Object being navigated to (standard vue-router argument)
  • from — the current route being navigated away from (standard vue-router argument)
  • next — this function must be called to resolve the hook (standard vue-router argument)
  • options — object with authorization guard configuration
    • redirect - redirect to auth page for authorization check's fail (you can pass any valid location object)
    • hasSession — boolean, check if user has session (in cookies for example). If it is false — redirect to auth page
    • isAuthorized — boolean, check if user is already authorized in application (take from store or cookies for example ). If it is false — try to get user data,
    • getUser — function-Promise with resolve/reject status for fetching user data (get from API and save it in store for example). Resolve — go next(), reject — redirect to auth page

Access Guard

This guard is used to check access to route

  • You should pass user's rights
  • You should set additional meta data in your routes

It is not necessary to set access data on all your nested routes - guard will try to find missing data from parent routes and use them

Example


// vue-router.js

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

import store from '@store';

import {rightsCheckGuard} from 'vue-and-router-guards'
import routes from './routes';

Vue.use(VueRouter);

export const router = new VueRouter({routes});

/**
 * =============
 * Global hooks
 * =============
 *
 * Set global hooks for vue-router
 */

/*
 * Set guard to check rights access
 */
router.beforeEach((to, from, next) => rightsCheckGuard(to, from, next, {

    // Set redirect to 404 page
    redirect: {name: 'system.404', replace: true},

    // Check if authorized or not
    isAuthorized: store.getters['account/authorized'],
    
    // Get user's rights
    rights: store.getters['account/rights'],
}));

Arguments

  • to — the target Route Object being navigated to (standard vue-router argument)
  • from — the current route being navigated away from (standard vue-router argument)
  • next — this function must be called to resolve the hook (standard vue-router argument)
  • options — object with authorization guard configuration
    • redirect - redirect to 404 page in case of access check's fail (you can pass any valid location object)
    • isAuthorized — boolean, check if user is already authorized in application (take from store or cookies for example )
    • rights — object with user's rights

User's rights

You need to provide an object with user's rights

const rights = {
    'scheduler': { // is component key in meta.access
        'main': { // is module key in meta.access
            'show': true, // is action key in meta.access (true — access, false (or not exists) — restricted)
        },
        'tasks': {
            'results': false // (or not exists)
        }
    }
}

Route's meta


export default  [
    {
        path: '/auth',
        name: 'system.auth',
        meta: {
            public: true // public route -> access without authorization or special rights
        }, 
    },
    {
        path: '/',
        name: 'dashboard',
        meta: {
            authorized: true, // access only for authorized users but without special rights
        }
    },
    {
        path: '/scheduler',
        name: 'scheduler',
        meta: {
            access: { // special rights for this route will be used
                component: 'scheduler', 
                module: 'main', 
                action: 'show'
            },
        },
        children: [
            {
                path: 'tasks/:id(\\d+)?',
                name: 'scheduler.tasks',
                meta: {
                    // no need to set access object -> guard will use data from parent (`scheduler` route)
                },
                children: [
                    {
                        path: 'add',
                        name: 'scheduler.tasks.add',
                        meta: {
                            access: { // special rights for this route will be used
                                component: 'scheduler', 
                                module: 'tasks', 
                                action: 'add'
                            },
                        },              
                    },
                    {
                        path: 'result',
                        name: 'scheduler.tasks.result',
                        meta: {
                            // no need to set access object -> guard will use data from parent (`scheduler` route)
                        }
                    },
                ]
            }
        ]
    },    
]