GetLoginUrl.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. const API = require("../../../lib/API")
  2. const axios = require('axios')
  3. const config = require('../../../config.json')
  4. const { BaseStdResponse } = require("../../../BaseStdResponse");
  5. const https = require("https")
  6. const { normalizeSocialType } = require('../../../lib/UniLoginClient')
  7. class GetLoginUrl extends API {
  8. constructor() {
  9. super();
  10. this.setPath('/UniLogin/GetLoginUrl')
  11. this.setMethod('GET')
  12. }
  13. async onRequest(req, res) {
  14. let { type, device, action, from, mode } = req.query
  15. type = normalizeSocialType(type)
  16. if (!type)
  17. return res.json({
  18. ...BaseStdResponse.ERR,
  19. msg: '不支持的第三方登录类型'
  20. })
  21. const uniConfig = config.unilogin
  22. const appendQuery = (redirectUrl) => {
  23. const params = []
  24. if (mode && !redirectUrl.includes('mode='))
  25. params.push(`mode=${encodeURIComponent(mode)}`)
  26. if (action)
  27. params.push(`action=${encodeURIComponent(action)}`)
  28. if (from)
  29. params.push(`from=${encodeURIComponent(from)}`)
  30. if (params.length === 0)
  31. return redirectUrl
  32. return `${redirectUrl}${redirectUrl.includes('?') ? '&' : '?'}${params.join('&')}`
  33. }
  34. let redirectUri = appendQuery(uniConfig.return_url)
  35. let url = `${uniConfig.url}/connect.php?act=login&appid=${uniConfig.appid}&appkey=${uniConfig.appkey}&type=${type}&redirect_uri=${encodeURIComponent(redirectUri)}`
  36. if (device && device === 'uniapp')
  37. url = `${uniConfig.url}/connect.php?act=login&appid=${uniConfig.appid}&appkey=${uniConfig.appkey}&type=${type}&redirect_uri=${encodeURIComponent(appendQuery(uniConfig.uni_return_url))}`
  38. try {
  39. const r = await axios.get(url, {
  40. proxy: false,
  41. httpsAgent: new https.Agent({
  42. rejectUnauthorized: false
  43. })
  44. })
  45. if (!r || r.data?.code !== 0 || !r.data?.url) {
  46. this.logger.error(`获取聚合登录链接失败!${r.data?.msg || 'api接口错误'}`)
  47. return res.json({
  48. ...BaseStdResponse.ERR,
  49. msg: '请尝试其他登录方式或稍后再试'
  50. })
  51. }
  52. res.json({
  53. ...BaseStdResponse.OK,
  54. data: r.data.url
  55. })
  56. } catch (error) {
  57. this.logger.error(`获取聚合登录链接失败!${error.message || 'api接口错误'}`)
  58. return res.json({
  59. ...BaseStdResponse.ERR,
  60. msg: '请尝试其他登录方式或稍后再试!'
  61. })
  62. }
  63. }
  64. }
  65. module.exports.GetLoginUrl = GetLoginUrl;