UniLoginClient.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. const axios = require('axios')
  2. const https = require('https')
  3. const { getRuntimeConfig } = require('./RuntimeConfig')
  4. const VALID_SOCIAL_TYPES = ['qq', 'wx']
  5. function normalizeSocialType(type) {
  6. const socialType = type || 'qq'
  7. return VALID_SOCIAL_TYPES.includes(socialType) ? socialType : null
  8. }
  9. async function fetchUniLoginProfile(type, code) {
  10. const socialType = normalizeSocialType(type)
  11. if (!socialType)
  12. throw new Error('不支持的第三方登录类型')
  13. const uniConfig = await getRuntimeConfig('unilogin', { required: false, defaultValue: null })
  14. if (!uniConfig || !uniConfig.url || !uniConfig.appid || !uniConfig.appkey) {
  15. throw new Error('聚合登录暂未配置')
  16. }
  17. const url = `${uniConfig.url}/connect.php?act=callback&appid=${uniConfig.appid}&appkey=${uniConfig.appkey}&type=${socialType}&code=${code}`
  18. const r = await axios.get(url, {
  19. httpsAgent: new https.Agent({
  20. rejectUnauthorized: false
  21. }),
  22. proxy: false
  23. })
  24. if (!r || r.data?.code !== 0)
  25. throw new Error(r.data?.msg || 'api接口错误')
  26. return {
  27. ...r.data,
  28. social_type: socialType
  29. }
  30. }
  31. module.exports = {
  32. VALID_SOCIAL_TYPES,
  33. normalizeSocialType,
  34. fetchUniLoginProfile
  35. }