diff --git a/auth/authorization.go b/auth/authorization.go new file mode 100644 index 0000000..5e058eb --- /dev/null +++ b/auth/authorization.go @@ -0,0 +1,19 @@ +package auth + +import "net/http" + +type AuthenticationMiddleware struct { + Secret string +} + +func (middleware AuthenticationMiddleware) Middleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + authToken := r.Header.Get("Authorization") + + if authToken == "" || authToken != middleware.Secret { + http.Error(w, "Forbidden", http.StatusForbidden) + } else { + next.ServeHTTP(w, r) + } + }) +} diff --git a/auth/authorization_test.go b/auth/authorization_test.go new file mode 100644 index 0000000..a8fc6c8 --- /dev/null +++ b/auth/authorization_test.go @@ -0,0 +1,50 @@ +package auth + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestAuthorizationMiddleware(t *testing.T) { + t.Run("AuthorizationMiddleware returns 403 response when authorization header is incorrect", func(t *testing.T) { + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + }) + + middleware := AuthenticationMiddleware{ + Secret: "foo", + } + + middlewareHandler := middleware.Middleware(handler) + + request, _ := http.NewRequest("GET", "/", nil) + responseRecorder := httptest.NewRecorder() + + middlewareHandler.ServeHTTP(responseRecorder, request) + + assert.Equal(t, responseRecorder.Code, 403) + }) + + t.Run("AuthorizationMiddleware continues when authorization header is correct", func(t *testing.T) { + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + }) + + middleware := AuthenticationMiddleware{ + Secret: "foo", + } + + middlewareHandler := middleware.Middleware(handler) + + request, _ := http.NewRequest("GET", "/", nil) + request.Header.Set("Authorization", "foo") + responseRecorder := httptest.NewRecorder() + + middlewareHandler.ServeHTTP(responseRecorder, request) + + assert.Equal(t, responseRecorder.Code, 200) + }) +} diff --git a/main.go b/main.go index 1afeb91..cb25943 100644 --- a/main.go +++ b/main.go @@ -4,6 +4,7 @@ import ( "encoding/json" "net/http" + "github.com/geplauder/lithium/auth" "github.com/geplauder/lithium/pipelines" "github.com/geplauder/lithium/settings" "github.com/geplauder/lithium/storage" @@ -56,7 +57,12 @@ func main() { pipes := pipelines.LoadPipelines() + authMiddleware := auth.AuthenticationMiddleware{ + Secret: settings.Token, + } + r := mux.NewRouter() + r.Use(authMiddleware.Middleware) r.HandleFunc("/", IndexHandler) RegisterPipelineRoutes(r, pipes, storageProvider)