package middleware import ( "net/http" "net/http/httptest" "testing" ) func TestAPIKeyAuth_ValidKey(t *testing.T) { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("OK")) }) mw := APIKeyAuth("test-api-key-12345") wrapped := mw(handler) req := httptest.NewRequest("GET", "/api/v1/admin/licenses", nil) req.Header.Set("X-API-Key", "test-api-key-12345") w := httptest.NewRecorder() wrapped.ServeHTTP(w, req) if w.Code != http.StatusOK { t.Errorf("validan kljuc mora proci, dobijen status %d", w.Code) } } func TestAPIKeyAuth_MissingKey(t *testing.T) { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }) mw := APIKeyAuth("test-api-key-12345") wrapped := mw(handler) req := httptest.NewRequest("GET", "/api/v1/admin/licenses", nil) // No X-API-Key header w := httptest.NewRecorder() wrapped.ServeHTTP(w, req) if w.Code != http.StatusUnauthorized { t.Errorf("bez kljuca mora biti 401, dobijen %d", w.Code) } } func TestAPIKeyAuth_WrongKey(t *testing.T) { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }) mw := APIKeyAuth("correct-key") wrapped := mw(handler) req := httptest.NewRequest("GET", "/api/v1/admin/licenses", nil) req.Header.Set("X-API-Key", "wrong-key") w := httptest.NewRecorder() wrapped.ServeHTTP(w, req) if w.Code != http.StatusUnauthorized { t.Errorf("pogresan kljuc mora biti 401, dobijen %d", w.Code) } }