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
2=>src/store/modules/user.jshandleLogin() { 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; } }); },
3=>src/api/login.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); }); }); },
4 = > Src / mock / index.jsimport 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 }); }
5=>src/mock/login.jsimport 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;
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
6=>src/store/modules/user.jsadmin: { role: ['admin'], token: 'admin', introduction: 'I'm super administrator', name: 'Super Admin', uid: '001' },
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)
Do this today, and get out tomorrowimport 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 });