activityPub.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package middleware
  2. import (
  3. "net/http"
  4. "strings"
  5. "github.com/owncast/owncast/core/data"
  6. "github.com/owncast/owncast/utils"
  7. )
  8. // RequireActivityPubOrRedirect will validate the requested content types and
  9. // redirect to the main Owncast page if it doesn't match.
  10. func RequireActivityPubOrRedirect(handler http.HandlerFunc) http.HandlerFunc {
  11. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  12. if !data.GetFederationEnabled() {
  13. w.WriteHeader(http.StatusMethodNotAllowed)
  14. return
  15. }
  16. handleAccepted := func() {
  17. handler(w, r)
  18. }
  19. acceptedContentTypes := []string{"application/json", "application/json+ld", "application/activity+json", `application/ld+json; profile="https://www.w3.org/ns/activitystreams"`}
  20. var accept []string
  21. for _, a := range r.Header.Values("Accept") {
  22. accept = append(accept, strings.Split(a, ",")...)
  23. }
  24. for _, singleType := range accept {
  25. if _, accepted := utils.FindInSlice(acceptedContentTypes, strings.TrimSpace(singleType)); accepted {
  26. handleAccepted()
  27. return
  28. }
  29. }
  30. contentTypeString := r.Header.Get("Content-Type")
  31. contentTypes := strings.Split(contentTypeString, ",")
  32. for _, singleType := range contentTypes {
  33. if _, accepted := utils.FindInSlice(acceptedContentTypes, strings.TrimSpace(singleType)); accepted {
  34. handleAccepted()
  35. return
  36. }
  37. }
  38. http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
  39. })
  40. }