From 1de6441ed43a103051d58bd4d828b38be2bd4ef4 Mon Sep 17 00:00:00 2001 From: Daniel Heidemann Date: Thu, 4 Jul 2024 16:18:09 +0200 Subject: [PATCH] check valid api key (#22) --- .env | 2 ++ server/server.go | 15 +++++++++++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/.env b/.env index 7d8d53e..33f97e3 100644 --- a/.env +++ b/.env @@ -9,3 +9,5 @@ SMTP_PORT= FROM_ADDRESS= API_URL=http://localhost:8080 + +API_KEY= diff --git a/server/server.go b/server/server.go index 3cb937d..07e6d02 100644 --- a/server/server.go +++ b/server/server.go @@ -18,7 +18,10 @@ import ( "github.com/rs/cors" ) -const defaultPort = "8080" +const ( + defaultPort = "8080" + apiKeyHeader = "X-API-Key" +) func main() { ctx := context.Background() @@ -66,7 +69,15 @@ func main() { gqlResolvers := graph.Resolver{DB: db} srv := handler.NewDefaultServer(graph.NewExecutableSchema(graph.Config{Resolvers: &gqlResolvers})) - router.Handle("/api", srv) + router.With(func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get(apiKeyHeader) != os.Getenv("API_KEY") { + http.Error(w, "Invalid API Key", http.StatusUnauthorized) + return + } + h.ServeHTTP(w, r) + }) + }).Handle("/api", srv) router.Handle("/", playground.Handler("GraphQL playground", "/api"))