set-pwd.js 2.0 KB
Newer Older
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
const { userCollection, SMS_SCENE, LOG_TYPE, CAPTCHA_SCENE } = require('../../common/constants')
const { ERROR } = require('../../common/error')
const { verifyMobileCode } = require('../../lib/utils/verify-code')
const PasswordUtils = require('../../lib/utils/password')
const { getNeedCaptcha, verifyCaptcha } = require('../../lib/utils/captcha')

module.exports = async function (params = {}) {
  const schema = {
    password: 'password',
    code: 'string',
    captcha: {
      required: false,
      type: 'string'
    }
  }
  this.middleware.validate(params, schema)

  const { password, code, captcha } = params
  const uid = this.authInfo.uid
  const getUserRes = await userCollection.doc(uid).get()
  const userRecord = getUserRes.data[0]
  if (!userRecord) {
    throw {
      errCode: ERROR.ACCOUNT_NOT_EXISTS
    }
  }

  const needCaptcha = await getNeedCaptcha.call(this, {
    mobile: userRecord.mobile
  })

  if (needCaptcha) {
    await verifyCaptcha.call(this, {
      captcha,
      scene: CAPTCHA_SCENE.SET_PWD_BY_SMS
    })
  }

  try {
    // 验证手机号验证码,验证不通过时写入失败日志
    await verifyMobileCode({
      mobile: userRecord.mobile,
      code,
      scene: SMS_SCENE.SET_PWD_BY_SMS
    })
  } catch (error) {
    await this.middleware.uniIdLog({
      data: {
        mobile: userRecord.mobile
      },
      type: LOG_TYPE.SET_PWD_BY_SMS,
      success: false
    })
    throw error
  }

  const {
    passwordHash,
    version
  } = new PasswordUtils({
    clientInfo: this.getUniversalClientInfo(),
    passwordSecret: this.config.passwordSecret
  }).generatePasswordHash({
    password
  })

  // 更新用户密码
  await userCollection.doc(uid).update({
    password: passwordHash,
    password_secret_version: version
  })

  await this.middleware.uniIdLog({
    data: {
      mobile: userRecord.mobile
    },
    type: LOG_TYPE.SET_PWD_BY_SMS
  })

  return {
    errCode: 0
  }
}