package routes import ( "fmt" "gofaster/internal/auth/controller" "gofaster/internal/auth/repository" "gofaster/internal/auth/service" "gofaster/internal/shared/jwt" "gofaster/internal/shared/middleware" "time" "github.com/gin-gonic/gin" "gorm.io/gorm" ) // RegisterAuthRoutes 注册认证相关路由 func RegisterAuthRoutes(r *gin.RouterGroup, db *gorm.DB, jwtConfig middleware.JWTConfig) { fmt.Printf("🚀 开始注册认证路由\n") fmt.Printf("🔑 JWT配置: SecretKey=%s, Issuer=%s\n", jwtConfig.SecretKey[:10]+"...", jwtConfig.Issuer) // 创建仓储层实例 userRepo := repository.NewUserRepository(db) captchaRepo := repository.NewCaptchaRepository(db) passwordPolicyRepo := repository.NewPasswordPolicyRepository(db) passwordHistoryRepo := repository.NewPasswordHistoryRepository(db) passwordResetRepo := repository.NewPasswordResetRepository(db) // 创建JWT管理器 jwtManager := jwt.NewJWTManager(jwtConfig.SecretKey, jwtConfig.Issuer) // 创建服务层实例 authService := service.NewAuthService(userRepo, captchaRepo, jwtManager) userService := service.NewUserService(userRepo) passwordService := service.NewPasswordService(userService, passwordPolicyRepo, passwordHistoryRepo, passwordResetRepo) // 创建控制器实例 authController := controller.NewAuthController(authService) passwordController := controller.NewPasswordController(passwordService, userService) // 认证路由组 auth := r.Group("/auth") { // 公开接口(无需认证) auth.POST("/login", authController.Login) // 用户登录 auth.GET("/captcha", authController.GenerateCaptcha) // 生成验证码 auth.GET("/test", func(c *gin.Context) { // 测试端点 c.JSON(200, gin.H{ "message": "Auth routes are working!", "timestamp": time.Now().Unix(), }) }) // 密码策略相关接口(无需认证) auth.GET("/password-policy", passwordController.GetPasswordPolicy) // 获取密码策略 auth.POST("/validate-password", passwordController.ValidatePassword) // 验证密码强度 // 添加一个测试路由来验证路由注册是否正常 auth.GET("/test-route", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "路由注册正常,JWT中间件即将应用", "timestamp": time.Now().Unix(), }) }) // 需要认证的接口 fmt.Printf("🔒 应用JWT中间件到需要认证的路由\n") auth.Use(middleware.JWTAuth(jwtConfig)) { // 添加一个测试路由来验证JWT中间件是否工作 auth.GET("/test-jwt", func(c *gin.Context) { userID, exists := middleware.GetUserID(c) if !exists { c.JSON(401, gin.H{"error": "JWT中间件未正确工作,无法获取用户ID"}) return } c.JSON(200, gin.H{ "message": "JWT中间件工作正常!", "user_id": userID, "timestamp": time.Now().Unix(), }) }) auth.POST("/logout", authController.Logout) // 用户登出 auth.POST("/refresh", authController.RefreshToken) // 刷新令牌 auth.GET("/userinfo", authController.GetUserInfo) // 获取用户信息 // 密码管理接口 auth.POST("/change-password", passwordController.ChangePassword) // 修改密码 auth.GET("/password-status", passwordController.CheckPasswordStatus) // 检查密码状态 } } }