UniLoginClient.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. function getEnabledUniLoginTypes(uniConfig = {}) {
  10. if (!Array.isArray(uniConfig.enabledTypes)) return [...VALID_SOCIAL_TYPES]
  11. return uniConfig.enabledTypes
  12. .map(type => normalizeSocialType(type))
  13. .filter(Boolean)
  14. .filter((type, index, list) => list.indexOf(type) === index)
  15. }
  16. function isUniLoginTypeEnabled(uniConfig, type) {
  17. const socialType = normalizeSocialType(type)
  18. if (!socialType) return false
  19. return getEnabledUniLoginTypes(uniConfig).includes(socialType)
  20. }
  21. async function getUniLoginRuntimeConfig({ requireEnabledType } = {}) {
  22. const uniConfig = await getRuntimeConfig('unilogin', { required: false, defaultValue: null })
  23. if (!uniConfig || !uniConfig.url || !uniConfig.appid || !uniConfig.appkey) {
  24. throw new Error('聚合登录暂未配置')
  25. }
  26. if (requireEnabledType && !isUniLoginTypeEnabled(uniConfig, requireEnabledType)) {
  27. throw new Error('该登录方式已关闭')
  28. }
  29. return uniConfig
  30. }
  31. async function fetchUniLoginProfile(type, code) {
  32. const socialType = normalizeSocialType(type)
  33. if (!socialType)
  34. throw new Error('不支持的第三方登录类型')
  35. const uniConfig = await getUniLoginRuntimeConfig({ requireEnabledType: socialType })
  36. const url = `${uniConfig.url}/connect.php?act=callback&appid=${uniConfig.appid}&appkey=${uniConfig.appkey}&type=${socialType}&code=${code}`
  37. const r = await axios.get(url, {
  38. httpsAgent: new https.Agent({
  39. rejectUnauthorized: false
  40. }),
  41. proxy: false
  42. })
  43. if (!r || r.data?.code !== 0)
  44. throw new Error(r.data?.msg || 'api接口错误')
  45. return {
  46. ...r.data,
  47. social_type: socialType
  48. }
  49. }
  50. module.exports = {
  51. VALID_SOCIAL_TYPES,
  52. getEnabledUniLoginTypes,
  53. getUniLoginRuntimeConfig,
  54. isUniLoginTypeEnabled,
  55. normalizeSocialType,
  56. fetchUniLoginProfile
  57. }