login.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. const {
  2. preLoginWithPassword,
  3. postLogin
  4. } = require('../../lib/utils/login')
  5. const {
  6. getNeedCaptcha,
  7. verifyCaptcha
  8. } = require('../../lib/utils/captcha')
  9. const {
  10. CAPTCHA_SCENE
  11. } = require('../../common/constants')
  12. const {
  13. ERROR
  14. } = require('../../common/error')
  15. /**
  16. * 用户名密码登录
  17. * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#login
  18. * @param {Object} params
  19. * @param {String} params.username 用户名
  20. * @param {String} params.mobile 手机号
  21. * @param {String} params.email 邮箱
  22. * @param {String} params.password 密码
  23. * @param {String} params.captcha 图形验证码
  24. * @returns
  25. */
  26. module.exports = async function (params = {}) {
  27. const schema = {
  28. username: {
  29. required: false,
  30. type: 'username'
  31. },
  32. mobile: {
  33. required: false,
  34. type: 'mobile'
  35. },
  36. email: {
  37. required: false,
  38. type: 'email'
  39. },
  40. password: 'password',
  41. captcha: {
  42. required: false,
  43. type: 'string'
  44. }
  45. }
  46. this.middleware.validate(params, schema)
  47. const {
  48. username,
  49. mobile,
  50. email,
  51. password,
  52. captcha
  53. } = params
  54. if (!username && !mobile && !email) {
  55. throw {
  56. errCode: ERROR.INVALID_USERNAME
  57. }
  58. } else if (
  59. (username && email) ||
  60. (username && mobile) ||
  61. (email && mobile)
  62. ) {
  63. throw {
  64. errCode: ERROR.INVALID_PARAM
  65. }
  66. }
  67. const needCaptcha = await getNeedCaptcha.call(this, {
  68. username,
  69. mobile,
  70. email
  71. })
  72. if (needCaptcha) {
  73. await verifyCaptcha.call(this, {
  74. captcha,
  75. scene: CAPTCHA_SCENE.LOGIN_BY_PWD
  76. })
  77. }
  78. const {
  79. user,
  80. extraData
  81. } = await preLoginWithPassword.call(this, {
  82. user: {
  83. username,
  84. mobile,
  85. email
  86. },
  87. password
  88. })
  89. return postLogin.call(this, {
  90. user,
  91. extraData
  92. })
  93. }