update-pwd.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
const {
  userCollection
} = require('../../common/constants')
const {
  ERROR
} = require('../../common/error')
const PasswordUtils = require('../../lib/utils/password')
/**
 * 更新密码
 * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#update-pwd
 * @param {object} params
 * @param {string} params.oldPassword 旧密码
 * @param {string} params.newPassword 新密码
 * @returns {object}
 */
module.exports = async function (params = {}) {
  const schema = {
    oldPassword: 'string', // 防止密码规则调整导致旧密码无法更新
    newPassword: 'password'
  }
  this.middleware.validate(params, schema)
  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 {
    oldPassword,
    newPassword
  } = params
  const passwordUtils = new PasswordUtils({
study夏羽's avatar
study夏羽 已提交
35 36
    userRecord,
    clientInfo: this.getUniversalClientInfo(),
study夏羽's avatar
study夏羽 已提交
37 38
    passwordSecret: this.config.passwordSecret
  })
study夏羽's avatar
study夏羽 已提交
39

study夏羽's avatar
study夏羽 已提交
40 41 42 43 44 45
  const {
    success: checkPasswordSuccess
  } = passwordUtils.checkUserPassword({
    password: oldPassword,
    autoRefresh: false
  })
study夏羽's avatar
study夏羽 已提交
46

study夏羽's avatar
study夏羽 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
  if (!checkPasswordSuccess) {
    throw {
      errCode: ERROR.PASSWORD_ERROR
    }
  }

  const {
    passwordHash,
    version
  } = passwordUtils.generatePasswordHash({
    password: newPassword
  })

  await userCollection.doc(uid).update({
    password: passwordHash,
    password_secret_version: version,
    valid_token_date: Date.now() // refreshToken时会校验,如果创建token时间在此时间点之前,则拒绝下发新token,返回token失效错误码
  })
  // 执行更新密码操作后客户端应将用户退出重新登录
  return {
    errCode: 0
  }
}