proxy.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2020 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package proxy // import "miniflux.app/proxy"
  5. import (
  6. "crypto/hmac"
  7. "crypto/sha256"
  8. "encoding/base64"
  9. "net/url"
  10. "path"
  11. "miniflux.app/http/route"
  12. "github.com/gorilla/mux"
  13. "miniflux.app/config"
  14. )
  15. // ProxifyURL generates a relative URL for a proxified resource.
  16. func ProxifyURL(router *mux.Router, link string) string {
  17. if link != "" {
  18. proxyImageUrl := config.Opts.ProxyImageUrl()
  19. if proxyImageUrl == "" {
  20. mac := hmac.New(sha256.New, config.Opts.ProxyPrivateKey())
  21. mac.Write([]byte(link))
  22. digest := mac.Sum(nil)
  23. return route.Path(router, "proxy", "encodedDigest", base64.URLEncoding.EncodeToString(digest), "encodedURL", base64.URLEncoding.EncodeToString([]byte(link)))
  24. }
  25. proxyUrl, err := url.Parse(proxyImageUrl)
  26. if err != nil {
  27. return ""
  28. }
  29. proxyUrl.Path = path.Join(proxyUrl.Path, base64.URLEncoding.EncodeToString([]byte(link)))
  30. return proxyUrl.String()
  31. }
  32. return ""
  33. }
  34. // AbsoluteProxifyURL generates an absolute URL for a proxified resource.
  35. func AbsoluteProxifyURL(router *mux.Router, host, link string) string {
  36. if link != "" {
  37. proxyImageUrl := config.Opts.ProxyImageUrl()
  38. if proxyImageUrl == "" {
  39. mac := hmac.New(sha256.New, config.Opts.ProxyPrivateKey())
  40. mac.Write([]byte(link))
  41. digest := mac.Sum(nil)
  42. path := route.Path(router, "proxy", "encodedDigest", base64.URLEncoding.EncodeToString(digest), "encodedURL", base64.URLEncoding.EncodeToString([]byte(link)))
  43. if config.Opts.HTTPS {
  44. return "https://" + host + path
  45. } else {
  46. return "http://" + host + path
  47. }
  48. }
  49. proxyUrl, err := url.Parse(proxyImageUrl)
  50. if err != nil {
  51. return ""
  52. }
  53. proxyUrl.Path = path.Join(proxyUrl.Path, base64.URLEncoding.EncodeToString([]byte(link)))
  54. return proxyUrl.String()
  55. }
  56. return ""
  57. }