account.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. const {
  2. dbCmd,
  3. userCollection
  4. } = require('../../common/constants')
  5. const {
  6. USER_IDENTIFIER
  7. } = require('../../common/constants')
  8. const {
  9. batchFindObjctValue,
  10. getType,
  11. isMatchUserApp
  12. } = require('../../common/utils')
  13. /**
  14. * 查询满足条件的用户
  15. * @param {Object} params
  16. * @param {Object} params.userQuery 用户唯一标识组成的查询条件
  17. * @param {Object} params.authorizedApp 用户允许登录的应用
  18. * @returns userMatched 满足条件的用户列表
  19. */
  20. async function findUser (params = {}) {
  21. const {
  22. userQuery,
  23. authorizedApp = []
  24. } = params
  25. const condition = getUserQueryCondition(userQuery)
  26. if (condition.length === 0) {
  27. throw new Error('Invalid user query')
  28. }
  29. const authorizedAppType = getType(authorizedApp)
  30. if (authorizedAppType !== 'string' && authorizedAppType !== 'array') {
  31. throw new Error('Invalid authorized app')
  32. }
  33. let finalQuery
  34. if (condition.length === 1) {
  35. finalQuery = condition[0]
  36. } else {
  37. finalQuery = dbCmd.or(condition)
  38. }
  39. const userQueryRes = await userCollection.where(finalQuery).get()
  40. return {
  41. total: userQueryRes.data.length,
  42. userMatched: userQueryRes.data.filter(item => {
  43. return isMatchUserApp(item.dcloud_appid, authorizedApp)
  44. })
  45. }
  46. }
  47. function getUserIdentifier (userRecord = {}) {
  48. const keys = Object.keys(USER_IDENTIFIER)
  49. return batchFindObjctValue(userRecord, keys)
  50. }
  51. function getUserQueryCondition (userRecord = {}) {
  52. const userIdentifier = getUserIdentifier(userRecord)
  53. const condition = []
  54. for (const key in userIdentifier) {
  55. const value = userIdentifier[key]
  56. if (!value) {
  57. // 过滤所有value为假值的条件,在查询用户时没有意义
  58. continue
  59. }
  60. const queryItem = {
  61. [key]: value
  62. }
  63. // 为兼容用户老数据用户名及邮箱需要同时查小写及原始大小写数据
  64. if (key === 'mobile') {
  65. queryItem.mobile_confirmed = 1
  66. } else if (key === 'email') {
  67. queryItem.email_confirmed = 1
  68. const email = userIdentifier.email
  69. if (email.toLowerCase() !== email) {
  70. condition.push({
  71. email: email.toLowerCase(),
  72. email_confirmed: 1
  73. })
  74. }
  75. } else if (key === 'username') {
  76. const username = userIdentifier.username
  77. if (username.toLowerCase() !== username) {
  78. condition.push({
  79. username: username.toLowerCase()
  80. })
  81. }
  82. } else if (key === 'identities') {
  83. queryItem.identities = dbCmd.elemMatch(value)
  84. }
  85. condition.push(queryItem)
  86. }
  87. return condition
  88. }
  89. module.exports = {
  90. findUser,
  91. getUserIdentifier
  92. }