update-pwd.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. const {
  2. userCollection
  3. } = require('../../common/constants')
  4. const {
  5. ERROR
  6. } = require('../../common/error')
  7. const PasswordUtils = require('../../lib/utils/password')
  8. /**
  9. * 更新密码
  10. * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#update-pwd
  11. * @param {object} params
  12. * @param {string} params.oldPassword 旧密码
  13. * @param {string} params.newPassword 新密码
  14. * @returns {object}
  15. */
  16. module.exports = async function (params = {}) {
  17. const schema = {
  18. oldPassword: 'string', // 防止密码规则调整导致旧密码无法更新
  19. newPassword: 'password'
  20. }
  21. this.middleware.validate(params, schema)
  22. const uid = this.authInfo.uid
  23. const getUserRes = await userCollection.doc(uid).get()
  24. const userRecord = getUserRes.data[0]
  25. if (!userRecord) {
  26. throw {
  27. errCode: ERROR.ACCOUNT_NOT_EXISTS
  28. }
  29. }
  30. const {
  31. oldPassword,
  32. newPassword
  33. } = params
  34. const passwordUtils = new PasswordUtils({
  35. passwordSecret: this.config.passwordSecret
  36. })
  37. const {
  38. success: checkPasswordSuccess
  39. } = passwordUtils.checkUserPassword({
  40. password: oldPassword,
  41. passwordHash: userRecord.password,
  42. passwordSecretVersion: userRecord.password_secret_version,
  43. autoRefresh: false
  44. })
  45. if (!checkPasswordSuccess) {
  46. throw {
  47. errCode: ERROR.PASSWORD_ERROR
  48. }
  49. }
  50. const {
  51. passwordHash,
  52. version
  53. } = passwordUtils.generatePasswordHash({
  54. password: newPassword
  55. })
  56. await userCollection.doc(uid).update({
  57. password: passwordHash,
  58. password_secret_version: version,
  59. valid_token_date: Date.now() // refreshToken时会校验,如果创建token时间在此时间点之前,则拒绝下发新token,返回token失效错误码
  60. })
  61. // 执行更新密码操作后客户端应将用户退出重新登录
  62. return {
  63. errCode: 0
  64. }
  65. }