package http import ( "strings" "github.com/dusiburg/kotosoft-id/internal/handlers" "github.com/dusiburg/kotosoft-id/internal/middleware" "github.com/dusiburg/kotosoft-id/internal/models" "github.com/dusiburg/kotosoft-id/internal/repositories" "github.com/dusiburg/kotosoft-id/internal/services" "github.com/gin-gonic/gin" "github.com/google/uuid" ) func NewRouter( auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consents *handlers.ConsentHandler, clients *handlers.ClientHandler, svc *services.Service, repo *repositories.OAuthRepository, limiter *services.RateLimiter, ) *gin.Engine { r := gin.Default() r.Use(middleware.LoggingMiddleware()) r.Use(errorMiddleware()) o := r.Group("/oauth") { o.GET("/authorize", oauth.Authorize) o.GET("/session/:token", oauth.GetSession) o.POST("/session/login", middleware.RateLimit(limiter, services.LoginRateLimit, middleware.LoginKeyFn), oauth.SessionLogin, ) o.POST("/session/attach", middleware.RateLimit(limiter, services.TokenRateLimit, middleware.IPKeyFn("session_attach")), oauth.SessionAttach, ) o.POST("/session/approve", middleware.RateLimit(limiter, services.TokenRateLimit, middleware.IPKeyFn("session_approve")), oauth.SessionApprove, ) o.POST("/token", middleware.RateLimit(limiter, services.TokenRateLimit, middleware.TokenKeyFn), oauth.Token, ) o.POST("/revoke", middleware.RateLimit(limiter, services.RevokeRateLimit, middleware.RevokeKeyFn), oauth.Revoke, ) } api := r.Group("/api/v1") { a := api.Group("/auth") a.POST("/register", middleware.RateLimit(limiter, services.RegisterRateLimit, middleware.IPKeyFn("register")), auth.Register, ) a.POST("/refresh", middleware.RateLimit(limiter, services.RefreshRateLimit, middleware.RefreshKeyFn), auth.Refresh, ) me := api.Group("/me") me.GET("", authMiddleware(svc, repo, "profile:read"), auth.Profile) me.PATCH("", authMiddleware(svc, repo, "profile:edit"), auth.UpdateProfile) me.DELETE("", authMiddleware(svc, repo, "profile:delete"), auth.DeleteProfile) me.GET("/consents", authMiddleware(svc, repo, "profile:consent:read"), consents.GetUserConsents) me.DELETE("/consent/:clientId", authMiddleware(svc, repo, "profile:consent:delete"), consents.RevokeAppAccess) admin := api.Group("/admin") admin.Use(authMiddleware(svc, repo), middleware.AdminOnly()) { c := admin.Group("/clients") c.POST("", clients.Create) c.GET("", clients.List) c.GET("/:id", clients.Get) c.PATCH("/:id", clients.Update) c.DELETE("/:id", clients.Deactivate) } } return r } func authMiddleware(svc *services.Service, repo *repositories.OAuthRepository, requiredScopes ...string) gin.HandlerFunc { return func(c *gin.Context) { token, ok := bearerToken(c) if !ok { c.Error(models.ErrUnauthorized) c.Abort() return } info, err := svc.ValidateAccessToken(c.Request.Context(), token) if err != nil { c.Error(models.ErrUnauthorized) c.Abort() return } if len(requiredScopes) > 0 && !services.ScopesContain(info.Scopes, requiredScopes) { c.Error(models.ErrInsufficientScope) c.Abort() return } if _, err := repo.GetOAuthClientByID(c.Request.Context(), info.ClientID); err != nil { c.Error(models.ErrForbidden) c.Abort() return } user, err := svc.GetUserByID(c.Request.Context(), info.UserID) if err != nil { c.Error(models.ErrUnauthorized) c.Abort() return } c.Set("user_id", info.UserID) c.Set("is_admin", user.IsAdmin) c.Next() } } func errorMiddleware() gin.HandlerFunc { return func(c *gin.Context) { c.Next() if len(c.Errors) == 0 || c.Writer.Written() { return } err := c.Errors.Last().Err if apiErr, ok := err.(*models.APIError); ok { c.JSON(apiErr.Code, apiErr) return } c.JSON(500, models.ErrInternal) } } func bearerToken(c *gin.Context) (string, bool) { return strings.CutPrefix(c.GetHeader("Authorization"), "Bearer ") } func UserIDFromContext(c *gin.Context) (uuid.UUID, bool) { v, ok := c.Get("user_id") if !ok { return uuid.Nil, false } id, ok := v.(uuid.UUID) return id, ok }