Add Bearer Auth Middleware

This commit is contained in:
nikurasu 2023-10-17 15:52:33 +02:00
parent ae014d1950
commit b0ec1761fb
Signed by: Nikurasu
SSH key fingerprint: SHA256:FIJQPK9c6Hjb3ZyIZoH+OwVq+tdNoLJzBcU6mGuLYwY
4 changed files with 35 additions and 6 deletions

View file

@ -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)
}

View file

@ -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)
}

24
src/config/middleware.go Normal file
View file

@ -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
},
})
}

View file

@ -16,6 +16,7 @@ func main() {
config.LoadEnv()
config.Connect()
config.SetupValidator()
config.SetupMiddlewares()
config.SetupFiber(viewFS)
if config.Env.Debug {