Create internal/router/ package to organize route registration: - router.go: Main router setup and configuration - auth.go: Authentication routes (login, register, profile, etc.) - docs.go: Documentation routes - frontend.go: Frontend SSR routes (/, /login, /admin, etc.) - helpers.go: Helper functions for template rendering This is the first step in refactoring 858-line main.go into a more maintainable structure following Go best practices. Routes themselves have NOT changed - only organization.
57 lines
1.9 KiB
Go
57 lines
1.9 KiB
Go
package router
|
|
|
|
import (
|
|
"bookhoard/internal/handlers"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"github.com/labstack/echo-jwt/v4"
|
|
"github.com/labstack/echo/v4"
|
|
)
|
|
|
|
func registerAuthRoutes(cfg *Config, rateLimitMiddleware echo.MiddlewareFunc) {
|
|
e := cfg.Echo
|
|
|
|
// Auth routes (no auth required, but rate limited)
|
|
e.POST("/api/auth/register", rateLimitMiddleware(cfg.AuthHandler.Register))
|
|
e.POST("/api/auth/login", rateLimitMiddleware(cfg.AuthHandler.Login))
|
|
|
|
// JWT middleware for protected routes
|
|
jwtMiddleware := echojwt.WithConfig(echojwt.Config{
|
|
SigningKey: []byte(cfg.Cfg.JWTSecret),
|
|
ContextKey: "user",
|
|
SuccessHandler: func(c echo.Context) {
|
|
token := c.Get("user").(*jwt.Token)
|
|
claims := token.Claims.(jwt.MapClaims)
|
|
c.Set("user_id", claims["user_id"])
|
|
c.Set("user_role", claims["user_role"])
|
|
c.Set("user_email", claims["user_email"])
|
|
c.Set("user_username", claims["user_username"])
|
|
},
|
|
})
|
|
|
|
// Create protected route group
|
|
protected := e.Group("/api", jwtMiddleware)
|
|
|
|
// Protected auth routes
|
|
protected.GET("/auth/profile", cfg.AuthHandler.GetProfile)
|
|
protected.PUT("/auth/profile", cfg.AuthHandler.UpdateProfile)
|
|
|
|
// Refresh token endpoint (no authentication required - uses refresh token from body)
|
|
e.POST("/api/auth/refresh", cfg.AuthHandler.RefreshAccessToken)
|
|
|
|
// Logout endpoint (optional authentication - can revoke tokens if provided)
|
|
e.POST("/api/auth/logout", cfg.AuthHandler.Logout)
|
|
|
|
// Auth update routes
|
|
authGroup := e.Group("/api/auth", jwtMiddleware)
|
|
authGroup.PUT("/email", cfg.AuthHandler.UpdateEmail)
|
|
authGroup.PUT("/username", cfg.AuthHandler.UpdateUsername)
|
|
authGroup.PUT("/password", cfg.AuthHandler.UpdatePassword)
|
|
authGroup.PUT("/theme", cfg.AuthHandler.UpdateTheme)
|
|
|
|
// Admin-only routes for user management
|
|
admin := protected.Group("/auth", handlers.AdminMiddleware)
|
|
admin.GET("/users", cfg.AuthHandler.ListUsers)
|
|
admin.PUT("/users/:id/max-devices", cfg.AuthHandler.UpdateUserMaxDevices)
|
|
}
|