bind-mobile-by-sms.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. const {
  2. getNeedCaptcha,
  3. verifyCaptcha
  4. } = require('../../lib/utils/captcha')
  5. const {
  6. LOG_TYPE,
  7. SMS_SCENE,
  8. CAPTCHA_SCENE
  9. } = require('../../common/constants')
  10. const {
  11. verifyMobileCode
  12. } = require('../../lib/utils/verify-code')
  13. const {
  14. preBind,
  15. postBind
  16. } = require('../../lib/utils/relate')
  17. /**
  18. * 通过短信验证码绑定手机号
  19. * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#bind-mobile-by-sms
  20. * @param {Object} params
  21. * @param {String} params.mobile 手机号
  22. * @param {String} params.code 短信验证码
  23. * @param {String} params.captcha 图形验证码
  24. * @returns
  25. */
  26. module.exports = async function (params = {}) {
  27. const schema = {
  28. mobile: 'mobile',
  29. code: 'string',
  30. captcha: {
  31. type: 'string',
  32. required: false
  33. }
  34. }
  35. const {
  36. mobile,
  37. code,
  38. captcha
  39. } = params
  40. this.middleware.validate(params, schema)
  41. const uid = this.authInfo.uid
  42. // 判断是否需要验证码
  43. const needCaptcha = await getNeedCaptcha.call(this, {
  44. uid,
  45. type: LOG_TYPE.BIND_MOBILE
  46. })
  47. if (needCaptcha) {
  48. await verifyCaptcha.call(this, {
  49. captcha,
  50. scene: CAPTCHA_SCENE.BIND_MOBILE_BY_SMS
  51. })
  52. }
  53. try {
  54. // 验证手机号验证码,验证不通过时写入失败日志
  55. await verifyMobileCode({
  56. mobile,
  57. code,
  58. scene: SMS_SCENE.BIND_MOBILE_BY_SMS
  59. })
  60. } catch (error) {
  61. await this.middleware.uniIdLog({
  62. data: {
  63. user_id: uid
  64. },
  65. type: LOG_TYPE.BIND_MOBILE,
  66. success: false
  67. })
  68. throw error
  69. }
  70. const bindAccount = {
  71. mobile
  72. }
  73. await preBind.call(this, {
  74. uid,
  75. bindAccount,
  76. logType: LOG_TYPE.BIND_MOBILE
  77. })
  78. await postBind.call(this, {
  79. uid,
  80. bindAccount,
  81. extraData: {
  82. mobile_confirmed: 1
  83. },
  84. logType: LOG_TYPE.BIND_MOBILE
  85. })
  86. return {
  87. errCode: 0
  88. }
  89. }