unified-login.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. const {
  2. checkLoginUserRecord,
  3. postLogin
  4. } = require('./login')
  5. const {
  6. postRegister
  7. } = require('./register')
  8. const {
  9. findUser
  10. } = require('./account')
  11. const {
  12. ERROR
  13. } = require('../../common/error')
  14. async function realPreUnifiedLogin (params = {}) {
  15. const {
  16. user,
  17. type
  18. } = params
  19. const appId = this.getUniversalClientInfo().appId
  20. const {
  21. total,
  22. userMatched
  23. } = await findUser({
  24. userQuery: user,
  25. authorizedApp: appId
  26. })
  27. if (userMatched.length === 0) {
  28. if (type === 'login') {
  29. if (total > 0) {
  30. throw {
  31. errCode: ERROR.ACCOUNT_NOT_EXISTS_IN_CURRENT_APP
  32. }
  33. }
  34. throw {
  35. errCode: ERROR.ACCOUNT_NOT_EXISTS
  36. }
  37. }
  38. return {
  39. type: 'register',
  40. user
  41. }
  42. } if (userMatched.length === 1) {
  43. if (type === 'register') {
  44. throw {
  45. errCode: ERROR.ACCOUNT_EXISTS
  46. }
  47. }
  48. const userRecord = userMatched[0]
  49. checkLoginUserRecord(userRecord)
  50. return {
  51. type: 'login',
  52. user: userRecord
  53. }
  54. } else if (userMatched.length > 1) {
  55. throw {
  56. errCode: ERROR.ACCOUNT_CONFLICT
  57. }
  58. }
  59. }
  60. async function preUnifiedLogin (params = {}) {
  61. try {
  62. const result = await realPreUnifiedLogin.call(this, params)
  63. return result
  64. } catch (error) {
  65. await this.middleware.uniIdLog({
  66. success: false
  67. })
  68. throw error
  69. }
  70. }
  71. async function postUnifiedLogin (params = {}) {
  72. const {
  73. user,
  74. extraData = {},
  75. isThirdParty = false,
  76. type,
  77. inviteCode
  78. } = params
  79. let result
  80. if (type === 'login') {
  81. result = await postLogin.call(this, {
  82. user,
  83. extraData,
  84. isThirdParty
  85. })
  86. } else if (type === 'register') {
  87. result = await postRegister.call(this, {
  88. user,
  89. extraData,
  90. isThirdParty,
  91. inviteCode
  92. })
  93. }
  94. return {
  95. ...result,
  96. type
  97. }
  98. }
  99. module.exports = {
  100. preUnifiedLogin,
  101. postUnifiedLogin
  102. }