login-by-sms.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. const {
  2. getNeedCaptcha,
  3. verifyCaptcha
  4. } = require('../../lib/utils/captcha')
  5. const {
  6. verifyMobileCode
  7. } = require('../../lib/utils/verify-code')
  8. const {
  9. preUnifiedLogin,
  10. postUnifiedLogin
  11. } = require('../../lib/utils/unified-login')
  12. const {
  13. CAPTCHA_SCENE,
  14. SMS_SCENE,
  15. LOG_TYPE
  16. } = require('../../common/constants')
  17. /**
  18. * 短信验证码登录
  19. * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#login-by-sms
  20. * @param {Object} params
  21. * @param {String} params.mobile 手机号
  22. * @param {String} params.code 短信验证码
  23. * @param {String} params.captcha 图形验证码
  24. * @param {String} params.inviteCode 邀请码
  25. * @returns
  26. */
  27. module.exports = async function (params = {}) {
  28. const schema = {
  29. mobile: 'mobile',
  30. code: 'string',
  31. captcha: {
  32. required: false,
  33. type: 'string'
  34. },
  35. inviteCode: {
  36. required: false,
  37. type: 'string'
  38. }
  39. }
  40. this.middleware.validate(params, schema)
  41. const {
  42. mobile,
  43. code,
  44. captcha,
  45. inviteCode
  46. } = params
  47. const needCaptcha = await getNeedCaptcha.call(this, {
  48. mobile
  49. })
  50. if (needCaptcha) {
  51. await verifyCaptcha.call(this, {
  52. captcha,
  53. scene: CAPTCHA_SCENE.LOGIN_BY_SMS
  54. })
  55. }
  56. try {
  57. await verifyMobileCode({
  58. mobile,
  59. code,
  60. scene: SMS_SCENE.LOGIN_BY_SMS
  61. })
  62. } catch (error) {
  63. console.log(error, {
  64. mobile,
  65. code,
  66. type: SMS_SCENE.LOGIN_BY_SMS
  67. })
  68. await this.middleware.uniIdLog({
  69. success: false,
  70. data: {
  71. mobile
  72. },
  73. type: LOG_TYPE.LOGIN
  74. })
  75. throw error
  76. }
  77. const {
  78. type,
  79. user
  80. } = await preUnifiedLogin.call(this, {
  81. user: {
  82. mobile
  83. }
  84. })
  85. return postUnifiedLogin.call(this, {
  86. user,
  87. extraData: {
  88. mobile_confirmed: 1
  89. },
  90. isThirdParty: false,
  91. type,
  92. inviteCode
  93. })
  94. }