Page permission Control What does page permission control mean?

A website has different roles, such as administrators and ordinary users, requiring different roles to access different pages. If a page is accessed by a character who is not authorized to do so, then you have to limit it.

One way to do this is to dynamically add routes and menus so that unreachable pages are not added to the routing table.

The alternative is to have all the pages in the routing table, just check the role permissions when accessing them. If you have permission to let access, no permission to reject, jump to 404 page.

Ideas:

In the meta attribute of each route, add roles with access to that route to roles. Each time a user logs in, the role of the user is returned. When the user visits the page, the meta attribute of the route is compared with the user’s role. If the user’s role is in the roles of the route, the user is allowed to access the page. If the user’s role is not in the roles of the route, the user is denied access.

Code examples:

routes: [
    {
        path: '/login',
        name: 'login',
        meta: {
            roles: ['admin'.'user']
        },
        component: () => import('.. /components/Login.vue')
    },
    {
        path: 'home',
        name: 'home',
        meta: {
            roles: ['admin']
        },
        component: () => import('.. /views/Home.vue')},]Copy the code

Page control

// We assume that there are two types of roles: admin and user const role ='user'Router. beforeEach event router.beforeEach((to, from, next) => {if (to.meta.roles.includes(role)) {
        next()
    } else {
        next({path: '/ 404'})}})Copy the code

Login authentication

The site is generally logged in once, and then the other pages of the site can be directly accessed without logging in again. We can do this by token or cookie. The following code shows how to use token to control login authentication.

Route. beforeEach((to, from, next) => {// If there is a token, the user has logged inif (localStorage.getItem('token'() {// Accessing the login page while logged in redirects to the home pageif (to.path === '/login') {
            next({path: '/'})}else {
            next({path: to.path || '/'}}})else{// Any page visited without login is redirected to the login pageif (to.path === '/login') {
            next()
        } else{ next(`/login? redirect=${to.path}`)}}})Copy the code