login.js 1.8 KB
Newer Older
study夏羽's avatar
study夏羽 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
const {
  preLoginWithPassword,
  postLogin
} = require('../../lib/utils/login')
const {
  getNeedCaptcha,
  verifyCaptcha
} = require('../../lib/utils/captcha')
const {
  CAPTCHA_SCENE
} = require('../../common/constants')
const {
  ERROR
} = require('../../common/error')

/**
 * 用户名密码登录
 * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#login
 * @param {Object} params
 * @param {String} params.username  用户名
 * @param {String} params.mobile    手机号
 * @param {String} params.email     邮箱
 * @param {String} params.password  密码
 * @param {String} params.captcha   图形验证码
 * @returns
 */
module.exports = async function (params = {}) {
  const schema = {
    username: {
      required: false,
      type: 'username'
    },
    mobile: {
      required: false,
      type: 'mobile'
    },
    email: {
      required: false,
      type: 'email'
    },
    password: 'password',
    captcha: {
      required: false,
      type: 'string'
    }
  }
  this.middleware.validate(params, schema)
  const {
    username,
    mobile,
    email,
    password,
    captcha
  } = params
  if (!username && !mobile && !email) {
    throw {
      errCode: ERROR.INVALID_USERNAME
    }
  } else if (
    (username && email) ||
    (username && mobile) ||
    (email && mobile)
  ) {
    throw {
      errCode: ERROR.INVALID_PARAM
    }
  }
  const needCaptcha = await getNeedCaptcha.call(this, {
    username,
    mobile,
    email
  })
  if (needCaptcha) {
    await verifyCaptcha.call(this, {
      captcha,
      scene: CAPTCHA_SCENE.LOGIN_BY_PWD
    })
  }
  const {
    user,
    extraData
  } = await preLoginWithPassword.call(this, {
    user: {
      username,
      mobile,
      email
    },
    password
  })
  return postLogin.call(this, {
    user,
    extraData
  })
}