From b0ec1761fbe976374155b647d7b37671cbd660dd Mon Sep 17 00:00:00 2001 From: nikurasu Date: Tue, 17 Oct 2023 15:52:33 +0200 Subject: [PATCH] Add Bearer Auth Middleware --- src/app/routes/private_routes.go | 13 ++++++++----- src/app/routes/public_routes.go | 3 ++- src/config/middleware.go | 24 ++++++++++++++++++++++++ src/main.go | 1 + 4 files changed, 35 insertions(+), 6 deletions(-) create mode 100644 src/config/middleware.go diff --git a/src/app/routes/private_routes.go b/src/app/routes/private_routes.go index a0c6051..81740a4 100644 --- a/src/app/routes/private_routes.go +++ b/src/app/routes/private_routes.go @@ -3,14 +3,17 @@ package routes import ( "github.com/gofiber/fiber/v2" "ulmer-furs.de/pretix-proxy/v2/app/controller" + "ulmer-furs.de/pretix-proxy/v2/config" ) func PrivateRoutes(app *fiber.App) { apiv1 := app.Group("/api/v1") + event := apiv1.Group("/event") + event.Use(config.AuthMiddleware) //app.Get("/events", controller.ReturnEventsTableView) - apiv1.Get("/event", controller.ReturnAllEvents) - apiv1.Get("/event/:id", controller.ReturnEventById) - apiv1.Delete("/event/:id", controller.DeleteEventById) - apiv1.Put("/event/:id", controller.UpdateEventById) - apiv1.Put("/event", controller.CreateEvent) + event.Get("", controller.ReturnAllEvents) + event.Get("/:id", controller.ReturnEventById) + event.Delete("/:id", controller.DeleteEventById) + event.Put("/:id", controller.UpdateEventById) + event.Put("", controller.CreateEvent) } diff --git a/src/app/routes/public_routes.go b/src/app/routes/public_routes.go index 7c71ea5..256e8ad 100644 --- a/src/app/routes/public_routes.go +++ b/src/app/routes/public_routes.go @@ -7,6 +7,7 @@ import ( func PublicRoutes(app *fiber.App) { apiv1 := app.Group("/api/v1") + attendies := apiv1.Group("/attendies") apiv1.Get("/ping", controller.Ping) - apiv1.Get("/attendies/:name", controller.GetAttendiesByEvent) + attendies.Get("/:name", controller.GetAttendiesByEvent) } diff --git a/src/config/middleware.go b/src/config/middleware.go new file mode 100644 index 0000000..1bdc32a --- /dev/null +++ b/src/config/middleware.go @@ -0,0 +1,24 @@ +package config + +import ( + "crypto/sha256" + "crypto/subtle" + + "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/middleware/keyauth" +) + +var AuthMiddleware fiber.Handler + +func SetupMiddlewares() { + AuthMiddleware = keyauth.New(keyauth.Config{ + Validator: func(c *fiber.Ctx, key string) (bool, error) { + hashedAPIKey := sha256.Sum256([]byte(Env.ApiKey)) + hashedKey := sha256.Sum256([]byte(key)) + if subtle.ConstantTimeCompare(hashedAPIKey[:], hashedKey[:]) == 1 { + return true, nil + } + return false, keyauth.ErrMissingOrMalformedAPIKey + }, + }) +} diff --git a/src/main.go b/src/main.go index 157e19b..83b9986 100644 --- a/src/main.go +++ b/src/main.go @@ -16,6 +16,7 @@ func main() { config.LoadEnv() config.Connect() config.SetupValidator() + config.SetupMiddlewares() config.SetupFiber(viewFS) if config.Env.Debug {