login.js 1.4 KB
Newer Older
DCloud_JSON's avatar
DCloud_JSON 已提交
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
const { preLogin, postLogin } = require('../../lib/utils/login')
const { EXTERNAL_DIRECT_CONNECT_PROVIDER } = require('../../common/constants')
const { ERROR } = require('../../common/error')

/**
 * 外部用户登录
 * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#external-login
 * @param {object} params
 * @param {string} params.uid  uni-id体系用户id
 * @param {string} params.externalUid   业务系统的用户id
 * @returns {object}
 */
module.exports = async function (params = {}) {
  const schema = {
    uid: {
      required: false,
      type: 'string'
    },
    externalUid: {
      required: false,
      type: 'string'
    }
  }

  this.middleware.validate(params, schema)

  const {
    uid,
    externalUid
  } = params

  if (!uid && !externalUid) {
    throw {
      errCode: ERROR.PARAM_REQUIRED,
      errMsgValue: {
        param: 'uid or externalUid'
      }
    }
  }

  let query
  if (uid) {
    query = {
      _id: uid
    }
  } else {
    query = {
      identities: {
        provider: EXTERNAL_DIRECT_CONNECT_PROVIDER,
        uid: externalUid
      }
    }
  }

  const user = await preLogin.call(this, {
    user: query
  })

  const result = await postLogin.call(this, {
    user
  })

  return {
    errCode: result.errCode,
    newToken: result.newToken,
    uid: result.uid
  }
}