The eladmin button permission assignment super details are very simple

preface

In the recent project, there is a need to assign different permissions to different users. In the past, the knowledge was used when writing. This time, I plan to read it myself according to login refresh verify (use element UI)

Without much to say, I'll take a look at this article in two roles

administrators

Sign in

On the login.vue page

handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        console.log(valid)
        const user = {
          username: this.loginForm.username,
          password: this.loginForm.password,
          rememberMe: this.loginForm.rememberMe,
          code: this.loginForm.code,
          uuid: this.loginForm.uuid
        }
        if (user.password !== this.cookiePass) {
          user.password = encrypt(user.password)
        }

        if (valid) {
          this.loading = true
          if (user.rememberMe) {
            Cookies.set('username', user.username, {
              expires: Config.passCookieExpires
            })
            Cookies.set('password', user.password, {
              expires: Config.passCookieExpires
            })
            Cookies.set('rememberMe', user.rememberMe, {
              expires: Config.passCookieExpires
            })
          } else {
            Cookies.remove('username')
            Cookies.remove('password')
            Cookies.remove('rememberMe')
          }
          // Send, action, verify login
          this.$store
            .dispatch('Login', user)
            .then(() => {
              this.loading = false
              this.$router.push({ path: this.redirect || '/' })
            })
            .catch(() => {
              this.loading = false
              this.getCode()
            })
        } else {
          console.log('error submit!!')
          // return false
        }
      })
    }

We can see on the login page that we first verify the form filled in by the user, and then send an action to request the login interface

It can be predicted that eladmin will store the information returned by the login interface in vuex, so the information returned by the login interface must contain the personal information of many users.

vuex modularization

The framework divides the js files that deal with different businesses
In store/modules/user.js

// Sign in
action: {
	Login({ dispatch, commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo.username, userInfo.password, userInfo.code, userInfo.uuid).then(res => {
          // The method of storing user information is called here
          setUserInfo(res.data.user, commit)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
}
export const setUserInfo = (res, commit) => {
  // If there is no permission, a default permission is given to avoid request deadlock
  if (res.roles.length === 0) {
    commit('SET_ROLES', ['ROLE_SYSTEM_DEFAULT'])
  } else {
    commit('SET_ROLES', res.roles)
  }
  commit('SET_USER', res.user)
}

mutations: {
  SET_USER: (state, user) => {
    state.user = user
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
},
state: {
  token: getToken(),
  user: {},
  roles: [],
  // Used when the menu is loaded for the first time
  loadMenus: false,
  // Message list
  notices: []
}

Here, we can see that after requesting the login interface to obtain the return information, the user information is provided through the changes
Stored in state.


This is the user information returned by the login interface. You can see that it is an array in the role field.

Check right

v-permission is a custom instruction of eladmin
You can see the v-permission field when operating the form everywhere

<el-table-column
  v-permission="['admin', 'user:edit', 'user:del']"
  label="operation"
  align="center"
  fixed="right"
>
	<template slot-scope="scope">
	<udOperation
	  :data="scope.row"
	  :permission="permission"
	  :disabled-dle="scope.row.id === user.id"
	>
	</udOperation>
	</template>
</el-table-column>

This corresponds to the permission passed to the component

It is a list of permissions defined in data

permission: {
  add: ['admin', 'user:add'],
  edit: ['admin', 'user:edit'],
  del: ['admin', 'user:del']
}

Let's look at the src/components/Permission.js file

inserted(el, binding, vnode) {
  // Deconstruct the assignment to get the value of v-permission binding
  const { value } = binding
  // Get the roles in gaters (roles under user)
  const roles = store.getters && store.getters.roles
  if (value && value instanceof Array && value.length > 0) {
    const permissionRoles = value
	// Judge whether the roles contain the value of v-permission binding
    const hasPermission = roles.some(role => {
      return permissionRoles.includes(role)
    })

    if (!hasPermission) {
      el.parentNode && el.parentNode.removeChild(el)
    }
  } else {
    throw new Error(`Usage: v-permission="['admin','editor']"`)
  }
}

What did v-permission do

Compare the v-permission and custom permission below. Let's take a look at what this custom instruction does

<el-table-column
  v-permission="['admin', 'user:edit', 'user:del']"
  label="operation"
  align="center"
  fixed="right"
>
	<template slot-scope="scope">
	<udOperation
	  :data="scope.row"
	  :permission="permission"
	>
	</udOperation>
	</template>
</el-table-column>
permission: {
  add: ['admin', 'user:add'],
  edit: ['admin', 'user:edit'],
  del: ['admin', 'user:del']
}

Here, I print v-permission and get

Print again to see the user's roles

We found that when logging in to the administrator, the above figure is printed.

conclusion

Therefore, if you want the administrator to have the permission to add, delete and modify a table
Just add the 'admin' field to the table v-permission list.

user

User role

For ordinary users, we print their user.role as shown in the figure below

In the login status of ordinary users, all records of buttons that can be operated by the current user are stored in the database.

User conclusion

When checking whether the user's permission can operate the current button, all button permissions of the current user will be obtained, and then compared with the value of the currently bound v-permission. When matched, it means that the user can operate this permission.

Therefore, to assign a button permission to a user:

  1. You need to write the current permission ID in v-permission.
  2. Then, on the menu page, add a button and write the corresponding permission ID.
  3. Then assign this permission to the corresponding user on the role management page.

Tags: node.js Vue.js element

Posted on Sun, 03 Oct 2021 16:08:04 -0400 by THW