登录

阅读: 5005    发布时间: 2018-09-04 10:31:17

登录本身是比较容易做的,无非是用户输入账号密码,然后提交给后台,是否验证通过,由于前后台分离,且不想再用session和cookie机制,我们需要模拟cookie机制,这里我们可以使用access_token

  • 用户提交账号密码登录后,后台返回一个access_token及过期时间expires;后台则将这个access_token、expires_tiem 和uid等信息存储起来(数据库或者redis等),模拟cookie机制

  • 用户端接收到access_token后,存储到Local Storage 中

  • 后续发起网络请求时,将access_token写入url或者请求header中

此外还希望实现记住密码功能,我是这样做的,用户登录时候,将账户存储在LocalStorage中,在进入登录页面时,提取出来,填充进登录表单中

部分代码:

登录代码

import config from '../../utils/config/config'
import api from '../../utils/config/api'
import network from '../../utils/base/network'
import authorize from "../../utils/base/authorize";
import {md5} from "../../utils/lib/md5";

methods:{
  login:function () {

    this.$refs.loginBtn.showLoading()   //登录按钮显示登录中...

   
    if(this.form.rememberme){
      //如果勾选了记住密码,则保存密码 
      authorize.saveAccount(this.form.username,this.form.password)
    }else {
      //否则,清除存储的密码
      authorize.clearAccount()
    }

    //将密码md5加密后再传输
    let post_data={
      username:this.form.username,
      password:md5(this.form.password)
    }

    //发起登录的网络请求
    network.post(api.login,post_data).then(res=>{

      //保存token
      authorize.saveToken(res.token,res.expires)

      //根据进入登录页面的redirect和go信息,进行跳转
      if(typeof(this.$route.query.redirect)!="undefined"){
        this.$router.push(this.$route.query.redirect)
      }else if(typeof(this.$route.query.go)!="undefined"){
        this.$router.go(this.$route.query.go)
      }else {
        this.$router.push(config.index_path)
      }

      this.$refs.loginBtn.hideLoading()

    }).catch(err=>{
      console.log(err)
      this.$toast({
        title:err,
        type:'error'
      })

      this.$refs.loginBtn.hideLoading()
    })


  }
}

其中authorize代码

//关于授权登录等基础方法
import config from '../config/config'
/*
* 保存登录信息至本地缓存
*/
function saveToken(token,expires) {
  localStorage.token=JSON.stringify({
    token:token,
    expires: expires*1000  //js的时间是毫秒,php的是秒,所以乘以1000
  })
}

function getToken() {
  if(localStorage.token){
    let token=JSON.parse(localStorage.token)

    if(token.expires < Date.parse(new Date())){
      return false
    }

    return token.token
  }else{
    return false
  }
}

function clearToken() {
  localStorage.removeItem("token")
}

function checkLogin() {
  if(getToken()){
    return true
  }else{
    return false
  }
}

function saveAccount(username,password) {
  localStorage.setItem('account',JSON.stringify({
    username:username,
    password: password
  }))
}

function getAccount() {
  if(localStorage.account){
    return JSON.parse(localStorage.account)
  }else {
    return false
  }
}

function clearAccount() {
  localStorage.removeItem("account")
}

export default {
  saveToken,
  getToken,
  clearToken,
  checkLogin,
  saveAccount,
  getAccount,
  clearAccount
}