unified-login.js 1.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 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 98
const {
  checkLoginUserRecord,
  postLogin
} = require('./login')
const {
  postRegister
} = require('./register')
const {
  findUser
} = require('./account')
const {
  ERROR
} = require('../../common/error')

async function realPreUnifiedLogin (params = {}) {
  const {
    user,
    type
  } = params
  const appId = this.getClientInfo().appId
  const userMatched = await findUser({
    userQuery: user,
    authorizedApp: appId
  })
  if (userMatched.length === 0) {
    if (type === 'login') {
      throw {
        errCode: ERROR.ACCOUNT_NOT_EXISTS
      }
    }
    return {
      type: 'register',
      user
    }
  } if (userMatched.length === 1) {
    if (type === 'register') {
      throw {
        errCode: ERROR.ACCOUNT_EXISTS
      }
    }
    const userRecord = userMatched[0]
    checkLoginUserRecord(userRecord)
    return {
      type: 'login',
      user: userRecord
    }
  } else if (userMatched.length > 1) {
    throw {
      errCode: ERROR.ACCOUNT_CONFLICT
    }
  }
}

async function preUnifiedLogin (params = {}) {
  try {
    const result = await realPreUnifiedLogin.call(this, params)
    return result
  } catch (error) {
    await this.middleware.uniIdLog({
      success: false
    })
    throw error
  }
}

async function postUnifiedLogin (params = {}) {
  const {
    user,
    extraData = {},
    isThirdParty = false,
    type,
    inviteCode
  } = params
  let result
  if (type === 'login') {
    result = await postLogin.call(this, {
      user,
      extraData,
      isThirdParty
    })
  } else if (type === 'register') {
    result = await postRegister.call(this, {
      user,
      extraData,
      isThirdParty,
      inviteCode
    })
  }
  return {
    ...result,
    type
  }
}

module.exports = {
  preUnifiedLogin,
  postUnifiedLogin
}