如何在 Nuxtjs 中创建用于检查角色的中间件

Jer*_*emy 4 javascript vue.js nuxt.js

我正在尝试创建一个中间件来检查我的用户的角色。

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

  if ( user.role !== 'admin' ) {
    return context.redirect('/errors/403')
  }
}
Run Code Online (Sandbox Code Playgroud)

在我的.vue文件中,我把这个放在:

middleware: [ 'is-admin' ]
Run Code Online (Sandbox Code Playgroud)

有用。

现在,我想检查用户是否还有另一个角色。所以,我创建了一个新的中间件:

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

  if ( user.role !== 'consultant' ) {
    return context.redirect('/errors/403')
  }
}
Run Code Online (Sandbox Code Playgroud)

在我的.vue文件中:

middleware: [ 'is-admin', 'is-consultant' ]
Run Code Online (Sandbox Code Playgroud)

不幸的是,当我这样做时,如果我以管理员角色访问该路由,它将不再起作用。

你能告诉我如何创建一个使用 Nuxt.js 检查多个角色的中间件吗?

谢谢!

xtr*_*ODE 8

您可以在 Nuxt 中使用此功能

export default function ({ $auth, redirect }) {
  if (!$auth.hasScope('admin')) {
    return redirect('/')
  }
}
Run Code Online (Sandbox Code Playgroud)

范围可以是您想要的任何内容,例如顾问、编辑等。

检查文档

更新

由于您使用的是 Laravel 您可以在用户表中有一个角色列,例如
$table->enum('role', ['subscriber', 'admin', 'editor', 'consultant', 'writer'])->default('subscriber');
Run Code Online (Sandbox Code Playgroud)

然后创建一个API资源,查看文档了解更多

要创建用户资源,请运行此工匠

php artisan make:resource UserResource
Run Code Online (Sandbox Code Playgroud)

然后在你的资源中,你可以有这样的东西

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'phone' => $this->phone,
        'gender' => $this->gender,
        'country' => $this->country,
        'avatar' => $this->avatar,
        'role' => $this->role,
   ];    
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样将它导入你的控制器

use App\Http\Resources\UserResource;
Run Code Online (Sandbox Code Playgroud)

你可以这样获取资源

            $userdata = new UserResource(User::find(auth()->user()->id));
            return response()->json(array(
                'user' => $userdata,
            ));
Run Code Online (Sandbox Code Playgroud)

在 Nuxt

在 Nuxt 中进行身份验证

安装 nuxt auth 和 axios

Using YARN : yarn add @nuxtjs/auth @nuxtjs/axios
Or using NPM: npm install @nuxtjs/auth @nuxtjs/axios
Run Code Online (Sandbox Code Playgroud)

然后将它们注册到您的 nuxtconfig.js

modules: [
    '@nuxtjs/axios',
    '@nuxtjs/auth',
  ],
Run Code Online (Sandbox Code Playgroud)

在您的nuxtconfig.js,也添加这个

  axios: {
    baseURL: 'http://127.0.0.1:8000/api'
  },

auth: {
    strategies: {
      local: {
        endpoints: {
          login: { url: '/login', method: 'post', propertyName: 'access_token' },
          logout: { url: '/logout', method: 'post' },
          user: { url: '/user', method: 'get', propertyName: false }
        },
        tokenRequired: true,
        tokenType: 'Bearer',
        globalToken: true
        // autoFetchUser: true
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

URL 是端点

查看文档了解更多

将 Nuxt 中的某些页面限制为特定用户。> 创建一个中间件,例如 isadmin.js

然后添加这个

export default function ({ $auth, redirect }) {
  if (!$auth.hasScope('admin')) {
    return redirect('/')
  }
}
Run Code Online (Sandbox Code Playgroud)

然后进入Page,添加中间件

export default {
  middleware: 'isadmin'
Run Code Online (Sandbox Code Playgroud)


And*_*huk 7

这个想法是每个页面都有其权限级别。然后在中间件中,您可以将当前用户权限级别与当前页面权限级别进行比较,如果较低,则重定向用户。这是 Nuxt.js 创建者提出的非常优雅的解决方案。GitHub 问题

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

<script>
export default {
  middleware: 'auth',
  meta: {
    auth: { authority: 2 }
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

然后在您的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.'
    })
  }
}
Run Code Online (Sandbox Code Playgroud)