Vue-based website front-end permission management (frontend and backend separation practices) and vue permission management

Source: Internet
Author: User

Vue-based website front-end permission management (frontend and backend separation practices) and vue permission management

As a popular language, Javascript is widely used. It can be seen everywhere from the front-end to the back-end, this technology is also widely used in our project to develop front-end pages such as CMS and other data analysis systems, for this reason, I am very interested in and use it as an extension of the hat card for my spare time study.
The Javascript framework is similar to each other, but its basic principles are roughly the same. Therefore, we chose vue. js developed by Chinese people for a preliminary attempt. Learn vue. js has been around for more than a week. Let's talk about the main usage of vue, similar to Declarative Rendering, Component System, Client-side Routing, Vue-resource, Axios, and Vuex that depends on the project size. Learning vue is minor and it mainly changes the mindset, component-based web development for front-end and back-end separation is really intended for practice.

My personal website CodeSheep is about to develop background management recently, so it is easy to use vue. When it comes to background management, the biggest problem is permission management. Since we want to practice the idea of frontend and backend separation, all web Front-ends managed in the background should be independently completed by the front-end, this includes important front-end controls based on permissions. What we want to do is: Different permissions correspond to different routes. At the same time, the page sidebar should generate corresponding menus asynchronously based on different permissions, to put it bluntly, users with different permissions in the background management can see different interface menus, so there is a set of procedures for implementing logon and permission verification here.
Implementation

1. Click "Log on" to trigger a logon event.

This. $ store. dispatch ('loginbyemail ', this. loginForm ). then () => {this. $ router. push ({path: '/'}); // redirect to the homepage after successful logon }). catch (err => {this. $ message. error (err); // logon Failure prompt error });

The processing content of the asynchronous triggering actions LoginByEmail is as follows:

LoginByEmail ({ commit }, userInfo) {   const email = userInfo.email.trim()   return new Promise((resolve, reject) => {    loginByEmail(email, userInfo.password).then(response => {     const data = response.data     setToken(response.data.token)     commit('SET_TOKEN', data.token)     resolve()    }).catch(error => {     reject(error)    })   })  }

It is easy to see that the token obtained from the server (uniquely indicating the user identity) is put into the local Cookie of the browser.

2. Intercept routing in global hook router. beforeEach

This step is the core. The specific process is shown as follows:

Route interception Process

The Code is as follows:

Router. beforeEach (to, from, next) => {if (getToken () {// determine whether token if (. path = '/login') {next ({path:'/'})} else {if (store. getters. roles. length = 0) {// determine whether the current user has obtained the user_info Information store. dispatch ('getinfo '). then (res => {// get user_info const roles = res. data. role store. dispatch ('generateeroutes ', {roles }). then () => {// generate the accessible route table router. addRoutes (store. getters. addRouters) // dynamically add Access route table next ({... to}) // allow route })}). catch () => {store. dispatch ('fedlogout '). then () =>{ next ({path: '/login'})} else {next () // allow this route }}else {if (whiteList. indexOf (. path )! =-1) {// In the login-free whitelist, continue to let it access next ()} else {// redirect all other paths not in the whitelist to the logon page! Next ('/login') alert ('not in white list, now go to the login page ')}}})

Several important steps in the flowchart are described as follows:

Determine whether the front-end has obtained the token: getToken ()

The operation is very simple. It is mainly obtained from the Cookie to see if the token has been obtained:

export function getToken () { return Cookies.get(TokenKey)}

Vuex Asynchronous Operation store. dispatch ('getinfo'): Get user information

  GetInfo ({ commit, state }) {   return new Promise((resolve, reject) => {    getInfo(state.token).then(response => {     const data = response.data     console.log(data)     commit('SET_ROLES', data.role)     commit('SET_NAME', data.name)     resolve(response)    }).catch(error => {     reject(error)    })   })  }

The operation is also very simple. get the user's role and name from the server using a get restful api

Vuex Asynchronous Operation store. dispatch ('generateeroutes ', {roles}): generate different foreground routes based on different roles.

  GenerateRoutes ({ commit }, data) {   return new Promise(resolve => {    const { roles } = data    let accessedRouters    if (roles.indexOf('admin') >= 0) {     accessedRouters = asyncRouter    } else {     accessedRouters = filterAsyncRouter(asyncRouter, roles)    }    commit('SET_ROUTERS', accessedRouters)    resolve()   })  }

It can be seen from the code that I only distinguish the admin role from other common users (that is, non-Aadmin permissions)

This series of practices will be further explored in the future and will be written in a series. I am also a beginner, and I have a long way to go...

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.