account.js 2.6 KB
Newer Older
DCloud_JSON's avatar
DCloud_JSON 已提交
1 2 3 4 5 6 7 8 9 10
const {
  db,
  dbCmd,
  userCollection
} = require('../../common/constants')
const {
  USER_IDENTIFIER
} = require('../../common/constants')
const {
  batchFindObjctValue,
11 12
  getType,
  isMatchUserApp
DCloud_JSON's avatar
DCloud_JSON 已提交
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
} = require('../../common/utils')

/**
 * 查询满足条件的用户
 * @param {Object} params
 * @param {Object} params.userQuery 用户唯一标识组成的查询条件
 * @param {Object} params.authorizedApp 用户允许登录的应用
 * @returns userMatched 满足条件的用户列表
 */
async function findUser (params = {}) {
  const {
    userQuery,
    authorizedApp = []
  } = params
  const condition = getUserQueryCondition(userQuery)
  if (condition.length === 0) {
    throw new Error('Invalid user query')
  }
  const authorizedAppType = getType(authorizedApp)
32
  if (authorizedAppType !== 'string' && authorizedAppType !== 'array') {
DCloud_JSON's avatar
DCloud_JSON 已提交
33 34 35 36 37 38
    throw new Error('Invalid authorized app')
  }

  let finalQuery

  if (condition.length === 1) {
39
    finalQuery = condition[0]
DCloud_JSON's avatar
DCloud_JSON 已提交
40
  } else {
41
    finalQuery = dbCmd.or(condition)
DCloud_JSON's avatar
DCloud_JSON 已提交
42 43
  }
  const userQueryRes = await userCollection.where(finalQuery).get()
44 45 46 47 48 49
  return {
    total: userQueryRes.data.length,
    userMatched: userQueryRes.data.filter(item => {
      return isMatchUserApp(item.dcloud_appid, authorizedApp)
    })
  }
DCloud_JSON's avatar
DCloud_JSON 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
}

function getUserIdentifier (userRecord = {}) {
  const keys = Object.keys(USER_IDENTIFIER)
  return batchFindObjctValue(userRecord, keys)
}

function getUserQueryCondition (userRecord = {}) {
  const userIdentifier = getUserIdentifier(userRecord)
  const condition = []
  for (const key in userIdentifier) {
    const value = userIdentifier[key]
    if (!value) {
      // 过滤所有value为假值的条件,在查询用户时没有意义
      continue
    }
    const queryItem = {
      [key]: value
    }
    // 为兼容用户老数据用户名及邮箱需要同时查小写及原始大小写数据
    if (key === 'mobile') {
      queryItem.mobile_confirmed = 1
    } else if (key === 'email') {
      queryItem.email_confirmed = 1
      const email = userIdentifier.email
      if (email.toLowerCase() !== email) {
        condition.push({
          email: email.toLowerCase(),
          email_confirmed: 1
        })
      }
    } else if (key === 'username') {
      const username = userIdentifier.username
      if (username.toLowerCase() !== username) {
        condition.push({
          username: username.toLowerCase()
        })
      }
    }
    condition.push(queryItem)
  }
  return condition
}

module.exports = {
  findUser,
  getUserIdentifier
}