Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a middleware for check role in Nuxtjs

I'm trying to create a middleware for check role of my users.

// middleware/is-admin.js
export default function (context) {
  let user = context.store.getters['auth/user']

  if ( user.role !== 'admin' ) {
    return context.redirect('/errors/403')
  }
}

In my .vue file, I'm putting this on:

middleware: [ 'is-admin' ]

It works.

Now, I'd like to check if the user also has another role. So, I create a new middleware:

// middleware/is-consultant.js
export default function (context) {
  let user = context.store.getters['auth/user']

  if ( user.role !== 'consultant' ) {
    return context.redirect('/errors/403')
  }
}

And in my .vue file:

middleware: [ 'is-admin', 'is-consultant' ]

Unfortunately, when I do that, if I visit the route with an administrator role, it does not work anymore.

Can you tell me how I can create a middleware that checks multiple roles with Nuxt.js?

Thank you!

like image 383
Jeremy Avatar asked Dec 06 '22 09:12

Jeremy


1 Answers

The idea is that every page has its authority level. Then in middleware you can compare your current user authority level with the current page authority level, and if it's lower redirect the user. It's very elegant solution that was proposed by Nuxt.js creator. GitHub issue.

<template>
  <h1>Only an admin can see this page</h1>
</template>

<script>
export default {
  middleware: 'auth',
  meta: {
    auth: { authority: 2 }
  }
}
</script>

Then in your middleware/auth.js:

export default ({ store, route, redirect }) => {
  // Check if user is connected first
  if (!store.getters['user/user'].isAuthenticated) return redirect('/login')

  // Get authorizations for matched routes (with children routes too)
  const authorizationLevels = route.meta.map((meta) => {
    if (meta.auth && typeof meta.auth.authority !== 'undefined')
      return meta.auth.authority
    return 0
  })
  // Get highest authorization level
  const highestAuthority = Math.max.apply(null, authorizationLevels)

  if (store.getters['user/user'].details.general.authority < highestAuthority) {
    return error({
      statusCode: 401,
      message: 'Du måste vara admin för att besöka denna sidan.'
    })
  }
}
like image 200
Andrew Vasilchuk Avatar answered Dec 27 '22 12:12

Andrew Vasilchuk