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:
29
middlewares/database.go
Normal file
29
middlewares/database.go
Normal 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()
|
||||
}
|
Reference in New Issue
Block a user