diff options
Diffstat (limited to 'src/rest-api/handler/handler.go')
-rw-r--r-- | src/rest-api/handler/handler.go | 30 |
1 files changed, 25 insertions, 5 deletions
diff --git a/src/rest-api/handler/handler.go b/src/rest-api/handler/handler.go index 558e773..4b9a426 100644 --- a/src/rest-api/handler/handler.go +++ b/src/rest-api/handler/handler.go @@ -27,17 +27,33 @@ func NewHandler(db *sqlx.DB, kafka_writer *kafka.Writer) Handler { } func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + api_key := r.Header.Get("API_KEY") + + log.Println("API KEY: ", api_key) + + user_id, err := h.db.GetUserIDByAPIKey(r.Context(), api_key) + if err != nil { + http.Error(w, fmt.Sprintf("Internal server error: %s", err), http.StatusInternalServerError) + return + } + if user_id == "" { + http.Error(w, "Unauthorized", http.StatusUnauthorized) + return + } + + log.Println("User ID: ", user_id) + switch r.Method { case http.MethodGet: - h.handleGet(w, r) + h.handleGet(w, r, user_id) case http.MethodPost: - h.handlePost(w, r) + h.handlePost(w, r, user_id) default: http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } } -func (h Handler) handleGet(w http.ResponseWriter, r *http.Request) { +func (h Handler) handleGet(w http.ResponseWriter, r *http.Request, user_id string) { _, filePath, ok := strings.Cut(r.URL.Path, "/file/") if !ok { http.Error(w, "Invalid file path", http.StatusBadRequest) @@ -48,7 +64,7 @@ func (h Handler) handleGet(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) defer cancel() - file, err := h.db.GetLatestFileByPath(ctx, filePath) + file, err := h.db.GetLatestFileByPath(ctx, filePath, user_id) if err != nil { http.Error(w, fmt.Sprintf("Internal server error: %s", err), http.StatusInternalServerError) return @@ -57,7 +73,7 @@ func (h Handler) handleGet(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "File: ", file) } -func (h Handler) handlePost(w http.ResponseWriter, r *http.Request) { +func (h Handler) handlePost(w http.ResponseWriter, r *http.Request, user_id string) { bytes, err := io.ReadAll(io.Reader(r.Body)) if err != nil { log.Fatal(err) @@ -69,6 +85,10 @@ func (h Handler) handlePost(w http.ResponseWriter, r *http.Request) { err = h.kafka_writer.WriteMessages(ctx, kafka.Message{ Key: []byte("key"), //TODO:This routes to a partition. We should probably route by agent UUID TODO: wont this negate having multiple topics Value: bytes, + Headers: []kafka.Header{{ + Key: "user_id", + Value: []byte(user_id), + }}, }) if err != nil { log.Fatal(err) |