ulflow_phattt2901 f4ef71b63b
Some checks failed
CI Pipeline / Security Scan (push) Failing after 5m24s
CI Pipeline / Lint (push) Failing after 5m30s
CI Pipeline / Test (push) Has been skipped
CI Pipeline / Build (push) Has been skipped
CI Pipeline / Notification (push) Successful in 1s
feat: implement user authentication system with JWT and role-based access control
2025-05-24 11:24:19 +07:00

99 lines
2.5 KiB
Go

package http
import (
"time"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"starter-kit/internal/adapter/persistence"
"starter-kit/internal/domain/role"
"starter-kit/internal/helper/config"
"starter-kit/internal/service"
"starter-kit/internal/transport/http/handler"
"starter-kit/internal/transport/http/middleware"
)
// SetupRouter cấu hình router cho HTTP server
func SetupRouter(cfg *config.Config, db *gorm.DB) *gin.Engine {
// Khởi tạo router với mode phù hợp với môi trường
if cfg.App.Environment == "production" {
gin.SetMode(gin.ReleaseMode)
}
router := gin.New()
// Logger middleware
router.Use(middleware.Logger())
// Recovery middleware
router.Use(gin.Recovery())
// CORS middleware
router.Use(middleware.CORS())
// Khởi tạo repositories
userRepo := persistence.NewUserRepository(db)
roleRepo := persistence.NewRoleRepository(db)
// Khởi tạo services
authSvc := service.NewAuthService(
userRepo,
roleRepo,
cfg.JWT.Secret,
time.Duration(cfg.JWT.Expiration)*time.Minute,
)
// Khởi tạo middleware
authMiddleware := middleware.NewAuthMiddleware(authSvc)
// Khởi tạo các handlers
healthHandler := handler.NewHealthHandler(cfg)
authHandler := handler.NewAuthHandler(authSvc)
// Public routes - Không yêu cầu xác thực
public := router.Group("/api/v1")
{
// Health check
public.GET("/ping", healthHandler.Ping)
public.GET("/health", healthHandler.HealthCheck)
// Auth routes
authGroup := public.Group("/auth")
{
authGroup.POST("/register", authHandler.Register)
authGroup.POST("/login", authHandler.Login)
authGroup.POST("/refresh", authHandler.RefreshToken)
}
}
// Protected routes - Yêu cầu xác thực
protected := router.Group("/api/v1")
protected.Use(authMiddleware.Authenticate())
{
// Auth routes
authGroup := protected.Group("/auth")
{
authGroup.POST("/logout", authHandler.Logout)
}
// User routes
usersGroup := protected.Group("/users")
{
usersGroup.GET("", authMiddleware.RequireRole(role.Admin, role.Manager), /* userHandler.ListUsers */)
usersGroup.GET("/:id", /* userHandler.GetUser */)
usersGroup.PUT("/:id", /* userHandler.UpdateUser */)
usersGroup.DELETE("/:id", authMiddleware.RequireRole(role.Admin), /* userHandler.DeleteUser */)
}
// Admin routes
adminGroup := protected.Group("/admin")
adminGroup.Use(authMiddleware.RequireRole(role.Admin))
{
// Role management
adminGroup.Group("/roles")
}
}
return router
}