set-pwd.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. const { userCollection, SMS_SCENE, LOG_TYPE, CAPTCHA_SCENE } = require('../../common/constants')
  2. const { ERROR } = require('../../common/error')
  3. const { verifyMobileCode } = require('../../lib/utils/verify-code')
  4. const PasswordUtils = require('../../lib/utils/password')
  5. const { getNeedCaptcha, verifyCaptcha } = require('../../lib/utils/captcha')
  6. module.exports = async function (params = {}) {
  7. const schema = {
  8. password: 'password',
  9. code: 'string',
  10. captcha: {
  11. required: false,
  12. type: 'string'
  13. }
  14. }
  15. this.middleware.validate(params, schema)
  16. const { password, code, captcha } = params
  17. const uid = this.authInfo.uid
  18. const getUserRes = await userCollection.doc(uid).get()
  19. const userRecord = getUserRes.data[0]
  20. if (!userRecord) {
  21. throw {
  22. errCode: ERROR.ACCOUNT_NOT_EXISTS
  23. }
  24. }
  25. const needCaptcha = await getNeedCaptcha.call(this, {
  26. mobile: userRecord.mobile
  27. })
  28. if (needCaptcha) {
  29. await verifyCaptcha.call(this, {
  30. captcha,
  31. scene: CAPTCHA_SCENE.SET_PWD_BY_SMS
  32. })
  33. }
  34. try {
  35. // 验证手机号验证码,验证不通过时写入失败日志
  36. await verifyMobileCode({
  37. mobile: userRecord.mobile,
  38. code,
  39. scene: SMS_SCENE.SET_PWD_BY_SMS
  40. })
  41. } catch (error) {
  42. await this.middleware.uniIdLog({
  43. data: {
  44. mobile: userRecord.mobile
  45. },
  46. type: LOG_TYPE.SET_PWD_BY_SMS,
  47. success: false
  48. })
  49. throw error
  50. }
  51. const {
  52. passwordHash,
  53. version
  54. } = new PasswordUtils({
  55. clientInfo: this.getUniversalClientInfo(),
  56. passwordSecret: this.config.passwordSecret
  57. }).generatePasswordHash({
  58. password
  59. })
  60. // 更新用户密码
  61. await userCollection.doc(uid).update({
  62. password: passwordHash,
  63. password_secret_version: version
  64. })
  65. await this.middleware.uniIdLog({
  66. data: {
  67. mobile: userRecord.mobile
  68. },
  69. type: LOG_TYPE.SET_PWD_BY_SMS
  70. })
  71. return {
  72. errCode: 0
  73. }
  74. }