From f6dc33edb4b3db329485b0cd8d812b891da49e7a Mon Sep 17 00:00:00 2001 From: Nicolai Ort Date: Wed, 11 Dec 2024 17:55:29 +0100 Subject: [PATCH] feat(v1): header auth for all endpoints --- main.go | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index 3420d5a..d527e75 100644 --- a/main.go +++ b/main.go @@ -1,20 +1,34 @@ package main import ( + "crypto/sha256" + "crypto/subtle" "flag" "log" "git.odit.services/lfk/document-server/docs" // Correct import path for docs "git.odit.services/lfk/document-server/handlers" "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/middleware/keyauth" "github.com/gofiber/swagger" ) var ( - port = flag.String("port", ":3000", "Port to listen on") - prod = flag.Bool("prod", false, "Enable prefork in Production") + port = flag.String("port", ":3000", "Port to listen on") + prod = flag.Bool("prod", false, "Enable prefork in Production") + apiKey = flag.String("apikey", "lfk", "API key for incoming authentication") ) +func validateAPIKey(c *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 + } + return false, keyauth.ErrMissingOrMalformedAPIKey +} + // @title LfK Document Server API // @description This is the API documentation for the LfK Document Server - a tool for pdf generation. func main() { @@ -30,6 +44,10 @@ func main() { app.Get("/swagger/*", swagger.HandlerDefault) v1 := app.Group("/v1") + v1.Use(keyauth.New(keyauth.Config{ + KeyLookup: "header:Authorization", + Validator: validateAPIKey, + })) v1.Get("/", func(c *fiber.Ctx) error { return c.SendString("Hello, World!")