From 08c7c1f9fabe31f7f614ccbb428a1cc71f20d56e Mon Sep 17 00:00:00 2001 From: Dennis Schoepf Date: Fri, 26 Apr 2024 20:46:59 +0200 Subject: [PATCH] Refactors api key functionality - API Key is now read from env file - API routes won't be set up if no API key is given via ENV file --- internal/api/api.go | 15 +++++++++++++-- internal/api/auth.go | 16 +++++++++------- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/internal/api/api.go b/internal/api/api.go index 89aa760..df85c97 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -1,20 +1,31 @@ package api import ( + "errors" + "os" + "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/keyauth" ) -func Setup(app *fiber.App) { +func Setup(app *fiber.App) error { + apiKey := os.Getenv("API_KEY") + + if apiKey == "" { + return errors.New("Could not read API_KEY from ENV file.") + } + api := app.Group("/api", keyauth.New(keyauth.Config{ SuccessHandler: successHandler, ErrorHandler: errHandler, KeyLookup: "header:x-api-key", ContextKey: "apiKey", - Validator: validateAPIKey, + Validator: apiKeyValidator(apiKey), })) v1 := api.Group("/v1") v1.Get("/users", FetchAllUsersHandler) + + return nil } diff --git a/internal/api/auth.go b/internal/api/auth.go index 5846eaf..b8221f8 100644 --- a/internal/api/auth.go +++ b/internal/api/auth.go @@ -21,15 +21,17 @@ var ( } ) -func validateAPIKey(_ *fiber.Ctx, key string) (bool, error) { - hashedAPIKey := sha256.Sum256([]byte(apiKey)) - hashedKey := sha256.Sum256([]byte(key)) +func apiKeyValidator(apiKey string) func(*fiber.Ctx, string) (bool, error) { + return func(_ *fiber.Ctx, key string) (bool, error) { + hashedAPIKey := sha256.Sum256([]byte(apiKey)) + hashedKey := sha256.Sum256([]byte(key)) - if subtle.ConstantTimeCompare(hashedAPIKey[:], hashedKey[:]) == 1 { - return true, nil + if subtle.ConstantTimeCompare(hashedAPIKey[:], hashedKey[:]) == 1 { + return true, nil + } + + return false, keyauth.ErrMissingOrMalformedAPIKey } - - return false, keyauth.ErrMissingOrMalformedAPIKey } func protectedRoutesFilter(ctx *fiber.Ctx) bool {