williamcruzme / vue-gates

🔒 A Vue.js & Nuxt.js plugin that allows you to use roles and permissions in your components or DOM elements, also compatible as middleware and methods.
https://williamcruzme.github.io/vue-gates/
MIT License
264 stars 31 forks source link

As Middleware? #6

Closed ruelluna closed 4 years ago

ruelluna commented 5 years ago

Great stuff you got here!

A question though, I'm trying to make a middleware on Nuxt.js that is role-based. It is basically easier to have like,

 export default {
    name: 'dashboard',
    middleware: ['auth', 'role-admin']
  }

rather than checking each and every component of what role the user has

mounted(){
  if(this.$laravel.hasRole('admin') {
    // redirect
  }
}

So far, I've created a role-admin.js middeware with

export default function(context) {
  if (!process.server) {
    if( context.app.$laravel.hasRole('admin') {
       // redirect to their default page
    }
  }
}

But the thing is, context.app.$laravel is undefined.

Am I missing something? Thanks for your help!

ruelluna commented 5 years ago

Seems like if I treat it as a middleware, it will hit in every route. So instead, I had it as a plugin:

export default ({ store, redirect, $laravel }, inject) => {
  inject('isAdmin', () => {
    if( !$laravel.hasRole('admin') ) {
      redirect('/')
    }
  })
}

..and called into each component like this.$isAdmin.

But then again, $laravel seems to be undefined.

williamcruzme commented 4 years ago

@ruelluna Laravel Permissions in injected into the Vue instance, try to access it by:

import Vue from 'vue'

export default ({ store, redirect }, inject) => {
  inject('isAdmin', () => {
    if( !Vue.prototype.$laravel.hasRole('admin') ) {
      redirect('/')
    }
  })
}
wit3 commented 4 years ago

Hi William,

can you provide a cleary example for use hasRole as middleware in page?

Thanks

williamcruzme commented 4 years ago

@Wit3 I invite you to try the new version of Vue Gates! 🎉