login.js 1.3 KB
Newer Older
DCloud_JSON's avatar
DCloud_JSON 已提交
1
const { preLogin, postLogin } = require('../../lib/utils/login')
DCloud_JSON's avatar
2.1.2  
DCloud_JSON 已提交
2 3
const { EXTERNAL_DIRECT_CONNECT_PROVIDER } = require('../../common/constants')
const { ERROR } = require('../../common/error')
DCloud_JSON's avatar
DCloud_JSON 已提交
4

DCloud_JSON's avatar
2.1.2  
DCloud_JSON 已提交
5 6 7 8 9 10 11 12
/**
 * 外部用户登录
 * @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}
 */
DCloud_JSON's avatar
DCloud_JSON 已提交
13 14
module.exports = async function (params = {}) {
  const schema = {
DCloud_JSON's avatar
2.1.2  
DCloud_JSON 已提交
15 16 17 18 19 20 21 22
    uid: {
      required: false,
      type: 'string'
    },
    externalUid: {
      required: false,
      type: 'string'
    }
DCloud_JSON's avatar
DCloud_JSON 已提交
23 24 25 26 27
  }

  this.middleware.validate(params, schema)

  const {
DCloud_JSON's avatar
2.1.2  
DCloud_JSON 已提交
28 29
    uid,
    externalUid
DCloud_JSON's avatar
DCloud_JSON 已提交
30 31
  } = params

DCloud_JSON's avatar
2.1.2  
DCloud_JSON 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44
  if (!uid && !externalUid) {
    throw {
      errCode: ERROR.PARAM_REQUIRED,
      errMsgValue: {
        param: 'uid or externalUid'
      }
    }
  }

  let query
  if (uid) {
    query = {
      _id: uid
DCloud_JSON's avatar
DCloud_JSON 已提交
45
    }
DCloud_JSON's avatar
2.1.2  
DCloud_JSON 已提交
46 47 48 49 50 51 52 53 54 55 56
  } else {
    query = {
      identities: {
        provider: EXTERNAL_DIRECT_CONNECT_PROVIDER,
        uid: externalUid
      }
    }
  }

  const user = await preLogin.call(this, {
    user: query
DCloud_JSON's avatar
DCloud_JSON 已提交
57 58 59 60 61 62 63 64 65
  })

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

  return {
    errCode: result.errCode,
    newToken: result.newToken,
DCloud_JSON's avatar
2.1.2  
DCloud_JSON 已提交
66
    uid: result.uid
DCloud_JSON's avatar
DCloud_JSON 已提交
67 68
  }
}