feat: add authentication and database middleware

- Add JWT authentication middleware for protected routes
- Add database middleware for request-scoped database access
- Include proper error handling and response formatting
- Support for role-based access control
This commit is contained in:
Björn Benouarets
2025-09-25 23:24:23 +02:00
parent f509f6e524
commit 4ee00d0b97
2 changed files with 168 additions and 0 deletions

29
middlewares/database.go Normal file
View File

@@ -0,0 +1,29 @@
package middlewares
import (
"git.secnex.io/secnex/idp-api/db"
"github.com/gofiber/fiber/v2"
"gorm.io/gorm"
)
// DatabaseMiddleware injects the database connection into the fiber context
func DatabaseMiddleware() fiber.Handler {
return func(c *fiber.Ctx) error {
// Get the global database instance
database := db.GetDB()
// Store the database connection in the context
c.Locals("db", database)
return c.Next()
}
}
// GetDBFromContext retrieves the database connection from the fiber context
func GetDBFromContext(c *fiber.Ctx) *gorm.DB {
if db, ok := c.Locals("db").(*gorm.DB); ok {
return db
}
// Fallback to global instance if not found in context
return db.GetDB()
}