Detailed explanation of wz framework login function demo1

Keywords: Vue JSON github mockjs

The purpose of this article is not to introduce how to use it, but to analyze the existing login process and the corresponding adjustments to be made in later formal development.

wz framework (let's promote the technology)

Introduction: Introduction to wz framework

Online experience: Online experience

github: vue-framework-wz


At the beginning of the year, we started to use vue for internal projects of the group. After simply reading the code, we found it convenient for development and then modified it. Because the technology is largely modeled by mock, the login part should be adjusted during project development. After reading the code again, sort out the code flow designed by login. It's not necessary for Daniel to see it, but for Xiaobai development, it's still necessary to understand it, especially for Xiaobai, who is black all over and white in technology.


Start! This is the landing page of technology sense ↓↓↓


1=>src/login/index.vue

handleLogin() {
                this.$refs.loginForm.validate(valid => {
                    if (valid) {
                        this.loading = true;
                        this.$store.dispatch('LoginByEmail', this.loginForm).then(() => {
                            this.$Message.success('Login successful');

                            this.loading = false;
                            this.$router.push({path: '/'});
                        }).catch(err => {
                            this.$message.error(err);
                            this.loading = false;
                        });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
2=>src/store/modules/user.js

// Email login
        LoginByEmail({commit}, userInfo) {
            const email = userInfo.email.trim();
            return new Promise((resolve, reject) => {
                loginByEmail(email, userInfo.password).then(response => {       //Return account information to the front end
                    const data = response.data;

                    console.log(response.data.token,"Deposited token");
                    Cookies.set('Admin-Token', response.data.token);        //Store account information in cookie
                    commit('SET_TOKEN', data.token);
                    commit('SET_EMAIL', email);
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            });
        },
3=>src/api/login.js

import fetch from 'utils/fetch';

export function loginByEmail(email, password) {
    const data = {      //Email and password information
        email,
        password
    };
    return fetch({
        url: '/login/loginbyemail',     //server address
        method: 'post',
        data
    });
}
4 = > Src / mock / index.js

import Mock from 'mockjs';
import loginAPI from './login';

// Login related
Mock.mock(/\/login\/loginbyemail/, 'post', loginAPI.loginByEmail);
Mock.mock(/\/login\/logout/, 'post', loginAPI.logout);
Mock.mock(/\/user\/info\.*/, 'get', loginAPI.getInfo);

export default Mock;
5=>src/mock/login.js

import {param2Obj} from 'utils';

const userMap = {
    admin: {
        role: ['admin'],
        token: 'admin',
        introduction: 'I'm super administrator',
        name: 'Super Admin',
        uid: '001'
    },
    editor: {
        role: ['editor'],
        token: 'editor',
        introduction: 'I'm an editor',
        name: 'Normal Editor',
        uid: '002'
    },
    developer: {
        role: ['develop'],
        token: 'develop',
        introduction: 'I'm developer',
        name: 'Engineer Xiao Wang',
        uid: '003'
    }
}

export default {
    loginByEmail: config => {
        const {email} = JSON.parse(config.body);
        console.log(JSON.parse(config.body),"Login information");
        return userMap[email.split('@')[0]];
    },
    getInfo: config => {
        const {token} = param2Obj(config.url);
        if (userMap[token]) {
            return userMap[token];
        } else {
            return Promise.reject('a');
        }
    },
    logout: () => 'success'
};

This data is returned

admin: {
        role: ['admin'],
        token: 'admin',
        introduction: 'I'm super administrator',
        name: 'Super Admin',
        uid: '001'
    },
6=>src/store/modules/user.js

 LoginByEmail({commit}, userInfo) {
            const email = userInfo.email.trim();
            return new Promise((resolve, reject) => {
                loginByEmail(email, userInfo.password).then(response => {       //Return account information to the front end
                    const data = response.data;

                    console.log(response.data.token,"Deposited token");
                    Cookies.set('Admin-Token', response.data.token);        //Deposit account information into cookie
                    commit('SET_TOKEN', data.token);
                    commit('SET_EMAIL', email);
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            });
        },

Save token, login completed

7 = > Src / login.js (used for jump permission judgment)

import router from './router'
import store from './store'
import vue from 'vue'
import NProgress from 'nprogress'   //Progress progress bar
import 'nprogress/nprogress.css'    //Progress progress bar style

// permissiom judge
function hasPermission(roles, permissionRoles) {
    if (roles.indexOf('admin') >= 0) return true;    //Direct access to admin
    if (!permissionRoles) return true;
    return roles.some(role => permissionRoles.indexOf(role) >= 0)
}

//next() is different from next('xxx '). The difference is that the former will not call router.beforeEach() again and the latter will!!!
const whiteList = ['/login', '/authredirect'];        //Do not redirect whitelist
router.beforeEach((to, from, next) => {     //To the target to enter, from the target to leave
    NProgress.start();              //Open Progress
    console.warn(store.getters.token,"existence token,Route can continue");
    if (store.getters.token) {      //Judge whether there is a token
        if (to.path === '/login') {
            next({path: '/'});
        } else {
            if (store.getters.roles.length === 0) {         //Judge whether the current user has pulled the user? Info information
                store.dispatch('GetInfo').then(res => {     //Pull user info
                    const roles = res.data.role;

                    store.dispatch('GenerateRoutes', {roles}).then(() => {  //Generate accessible routing table
                        console.log(store.getters.addRouters,"What is accessible");
                        router.addRoutes(store.getters.addRouters);         //Dynamically add accessible routing table
                        next({...to})       //The hack method ensures that addRoutes is complete
                    })
                }).catch(() => {
                    store.dispatch('FedLogOut').then(() => {
                        next({path: '/login'})
                    })
                })
            } else {
                store.dispatch('getNowRoutes', to);

                if (hasPermission(store.getters.roles, to.meta.role)) {
                    next();
                    // console.log("has userinfo")
                } else {
                    next({path: '/', query: {noGoBack: true}})
                }
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {    //In the no login white list, enter directly
            next()
        } else {
            next('/login');                         //Otherwise, there is no token. All tokens are redirected to the login page
            // NProgress.done() / / changing the hash redirection manually in hash mode will not trigger afterEach temporary hack SCHEME ps: no problem in history mode. You can delete this line!
        }
    }
});

router.afterEach(() => {
    NProgress.done()                                //End Progress
});
Do this today, and get out tomorrow

















Posted by zachrose on Fri, 01 May 2020 21:00:19 -0700