|
| 1 | +package config |
| 2 | + |
| 3 | +import ( |
| 4 | + "aggregator/model" |
| 5 | + "encoding/json" |
| 6 | + "github.com/sirupsen/logrus" |
| 7 | + "net/http" |
| 8 | +) |
| 9 | + |
| 10 | +type ClientIdentifierDocument struct { |
| 11 | + Context []string `json:"@context,omitempty"` |
| 12 | + ClientID string `json:"client_id"` |
| 13 | +} |
| 14 | + |
| 15 | +var ( |
| 16 | + clientIdentifierJSON []byte |
| 17 | + clientIdentifierJSONLD []byte |
| 18 | +) |
| 19 | + |
| 20 | +func InitClientIdentifier(mux *http.ServeMux) { |
| 21 | + logrus.Info("Initializing client identifier endpoint") |
| 22 | + |
| 23 | + var err error |
| 24 | + |
| 25 | + // Pre-encode JSON-LD version (with context) |
| 26 | + clientDocLD := ClientIdentifierDocument{ |
| 27 | + Context: []string{"https://www.w3.org/ns/solid/oidc-context.jsonld"}, |
| 28 | + ClientID: model.ClientId, |
| 29 | + } |
| 30 | + clientIdentifierJSONLD, err = json.Marshal(clientDocLD) |
| 31 | + if err != nil { |
| 32 | + logrus.WithError(err).Fatal("Failed to marshal client identifier JSON-LD document") |
| 33 | + } |
| 34 | + |
| 35 | + // Pre-encode JSON version (without context) |
| 36 | + clientDocJSON := ClientIdentifierDocument{ |
| 37 | + ClientID: model.ClientId, |
| 38 | + } |
| 39 | + clientIdentifierJSON, err = json.Marshal(clientDocJSON) |
| 40 | + if err != nil { |
| 41 | + logrus.WithError(err).Fatal("Failed to marshal client identifier JSON document") |
| 42 | + } |
| 43 | + |
| 44 | + mux.HandleFunc("/client.json", handleClientIdentifier) |
| 45 | + logrus.Info("Client identifier endpoint initialization completed") |
| 46 | +} |
| 47 | + |
| 48 | +func handleClientIdentifier(w http.ResponseWriter, r *http.Request) { |
| 49 | + if r.Method != http.MethodGet && r.Method != http.MethodHead { |
| 50 | + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) |
| 51 | + return |
| 52 | + } |
| 53 | + |
| 54 | + accept := r.Header.Get("Accept") |
| 55 | + |
| 56 | + var contentType string |
| 57 | + var body []byte |
| 58 | + |
| 59 | + preferredType := negotiateContentType(accept, []string{"application/ld+json", "application/json"}) |
| 60 | + |
| 61 | + if preferredType == "application/json" { |
| 62 | + contentType = "application/json" |
| 63 | + body = clientIdentifierJSON |
| 64 | + } else { |
| 65 | + contentType = "application/ld+json" |
| 66 | + body = clientIdentifierJSONLD |
| 67 | + } |
| 68 | + |
| 69 | + w.Header().Set("Content-Type", contentType) |
| 70 | + |
| 71 | + if r.Method == http.MethodHead { |
| 72 | + return |
| 73 | + } |
| 74 | + |
| 75 | + if _, err := w.Write(body); err != nil { |
| 76 | + logrus.WithError(err).Error("Failed to write client identifier document") |
| 77 | + } |
| 78 | +} |
0 commit comments