webfinger.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "strings"
  6. "github.com/owncast/owncast/activitypub/apmodels"
  7. "github.com/owncast/owncast/core/data"
  8. "github.com/owncast/owncast/utils"
  9. log "github.com/sirupsen/logrus"
  10. )
  11. // WebfingerHandler will handle webfinger lookup requests.
  12. func WebfingerHandler(w http.ResponseWriter, r *http.Request) {
  13. if !data.GetFederationEnabled() {
  14. w.WriteHeader(http.StatusMethodNotAllowed)
  15. return
  16. }
  17. resource := r.URL.Query().Get("resource")
  18. resourceComponents := strings.Split(resource, ":")
  19. var account string
  20. if len(resourceComponents) == 2 {
  21. account = resourceComponents[1]
  22. } else {
  23. account = resourceComponents[0]
  24. }
  25. userComponents := strings.Split(account, "@")
  26. if len(userComponents) < 2 {
  27. return
  28. }
  29. host := userComponents[1]
  30. user := userComponents[0]
  31. if _, valid := data.GetFederatedInboxMap()[user]; !valid {
  32. // User is not valid
  33. w.WriteHeader(http.StatusNotFound)
  34. log.Debugln("webfinger request rejected")
  35. return
  36. }
  37. // If the webfinger request doesn't match our server then it
  38. // should be rejected.
  39. instanceHostString := data.GetServerURL()
  40. if instanceHostString == "" {
  41. w.WriteHeader(http.StatusNotImplemented)
  42. return
  43. }
  44. instanceHostString = utils.GetHostnameFromURLString(instanceHostString)
  45. if instanceHostString == "" || instanceHostString != host {
  46. w.WriteHeader(http.StatusNotImplemented)
  47. return
  48. }
  49. webfingerResponse := apmodels.MakeWebfingerResponse(user, user, host)
  50. w.Header().Set("Content-Type", "application/jrd+json")
  51. if err := json.NewEncoder(w).Encode(webfingerResponse); err != nil {
  52. log.Errorln("unable to write webfinger response", err)
  53. }
  54. }