MW usage refactor

This commit is contained in:
nquidox 2026-03-21 15:21:30 +03:00
parent 229eebcf66
commit 21b54c4167
9 changed files with 98 additions and 48 deletions

View file

@ -65,6 +65,7 @@ func New(ctx context.Context, cfg config.Config) *App {
DB: dbPool, DB: dbPool,
Utils: u, Utils: u,
}) })
newApp.modules = append(newApp.modules, userProv)
newApp.router = router.NewRouter(router.Deps{ newApp.router = router.NewRouter(router.Deps{
Host: cfg.Http.Host, Host: cfg.Http.Host,
@ -76,15 +77,11 @@ func New(ctx context.Context, cfg config.Config) *App {
ServiceId: serviceId, ServiceId: serviceId,
}) })
//modules
var modules []Module
m := merch.New(merch.Deps{ m := merch.New(merch.Deps{
DB: dbPool, DB: dbPool,
Utils: u, Utils: u,
}) })
modules = append(modules, m) newApp.modules = append(newApp.modules, m)
newApp.modules = modules
newApp.tasker = task.New(task.Deps{ newApp.tasker = task.New(task.Deps{
Addr: "", Addr: "",
@ -97,8 +94,11 @@ func New(ctx context.Context, cfg config.Config) *App {
func (app *App) Run(ctx context.Context) error { func (app *App) Run(ctx context.Context) error {
log.Infof("%v starting...", pkgLogHeader) log.Infof("%v starting...", pkgLogHeader)
//getting middlewares for modules routes registration
mws := app.router.MWSet()
baseGroup := app.router.BaseGroup() baseGroup := app.router.BaseGroup()
app.collectRoutes(baseGroup) app.collectRoutes(baseGroup, mws)
errCh := make(chan error, 10) errCh := make(chan error, 10)
@ -140,9 +140,9 @@ func (app *App) shutdown(ctx context.Context) {
log.Infof("%v shutdown complete", pkgLogHeader) log.Infof("%v shutdown complete", pkgLogHeader)
} }
func (app *App) collectRoutes(group *gin.RouterGroup) { func (app *App) collectRoutes(group *gin.RouterGroup, mw *router.Middlewares) {
for _, m := range app.modules { for _, m := range app.modules {
m.RegisterRoutes(group) m.RegisterRoutes(group, mw)
} }
log.Infof("%v routes registered", pkgLogHeader) log.Infof("%v routes registered", pkgLogHeader)
} }
@ -169,7 +169,7 @@ func (app *App) isRegistered(ctx context.Context, cfg config.Config) (int32, boo
} }
if response == nil { if response == nil {
log.Error("%v error checking registration in auth service", pkgLogHeader) log.Errorf("%v error checking registration in auth service", pkgLogHeader)
return 0, false return 0, false
} }

View file

@ -1,7 +1,10 @@
package app package app
import "github.com/gin-gonic/gin" import (
"github.com/gin-gonic/gin"
"merch-api/pkg/router"
)
type Module interface { type Module interface {
RegisterRoutes(r *gin.RouterGroup) RegisterRoutes(r *gin.RouterGroup, mw *router.Middlewares)
} }

View file

@ -6,6 +6,7 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"merch-api/pkg/responses" "merch-api/pkg/responses"
"merch-api/pkg/router"
"merch-api/pkg/utils" "merch-api/pkg/utils"
"net/http" "net/http"
) )
@ -24,8 +25,9 @@ func newController(s *service, u utils.Utils) *controller {
} }
} }
func (h *Handler) RegisterRoutes(r *gin.RouterGroup) { func (h *Handler) RegisterRoutes(r *gin.RouterGroup, mw *router.Middlewares) {
merchGroup := r.Group("/merch") merchGroup := r.Group("/merch")
merchGroup.Use(mw.AuthMW)
merchGroup.POST("/create", h.controller.create) merchGroup.POST("/create", h.controller.create)
merchGroup.GET("/:id", h.controller.getOne) merchGroup.GET("/:id", h.controller.getOne)
@ -35,21 +37,28 @@ func (h *Handler) RegisterRoutes(r *gin.RouterGroup) {
merchGroup.DELETE("/:id", h.controller.deleteMerch) merchGroup.DELETE("/:id", h.controller.deleteMerch)
originsGroup := merchGroup.Group("/origins") originsGroup := merchGroup.Group("/origins")
originsGroup.Use(mw.AuthMW)
originsGroup.POST("", h.controller.createOrigin) originsGroup.POST("", h.controller.createOrigin)
originsGroup.GET("", h.controller.getOrigins) originsGroup.GET("", h.controller.getOrigins)
originsGroup.DELETE("", h.controller.deleteOrigin) originsGroup.DELETE("", h.controller.deleteOrigin)
chartsGroup := r.Group("/prices") chartsGroup := r.Group("/prices")
chartsGroup.Use(mw.AuthMW)
chartsGroup.GET("", h.controller.getChartsPrices) chartsGroup.GET("", h.controller.getChartsPrices)
chartsGroup.GET("/:uuid", h.controller.getDistinctPrices) chartsGroup.GET("/:uuid", h.controller.getDistinctPrices)
zeroPricesGroup := merchGroup.Group("/zeroprices") zeroPricesGroup := merchGroup.Group("/zeroprices")
zeroPricesGroup.Use(mw.AuthMW)
zeroPricesGroup.GET("", h.controller.getZeroPrices) zeroPricesGroup.GET("", h.controller.getZeroPrices)
zeroPricesGroup.DELETE("", h.controller.deleteZeroPrices) zeroPricesGroup.DELETE("", h.controller.deleteZeroPrices)
zeroPricesGroup.DELETE("/period", h.controller.deleteZeroPricesPeriod) zeroPricesGroup.DELETE("/period", h.controller.deleteZeroPricesPeriod)
labelsGroup := merchGroup.Group("/labels") labelsGroup := merchGroup.Group("/labels")
labelsGroup.Use(mw.AuthMW)
labelsGroup.POST("", h.controller.createLabel) labelsGroup.POST("", h.controller.createLabel)
labelsGroup.GET("", h.controller.getLabels) labelsGroup.GET("", h.controller.getLabels)
labelsGroup.PUT("/:uuid", h.controller.updateLabel) labelsGroup.PUT("/:uuid", h.controller.updateLabel)

View file

@ -37,7 +37,7 @@ func setupTestRouter(mockRepo Repository) *gin.Engine {
c.Next() c.Next()
}) })
handler.RegisterRoutes(router.Group("")) handler.RegisterRoutes(router.Group(""), nil)
return router return router
} }

View file

@ -4,6 +4,7 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"merch-api/internal/appLog" "merch-api/internal/appLog"
"merch-api/pkg/responses" "merch-api/pkg/responses"
"merch-api/pkg/router"
"merch-api/pkg/utils" "merch-api/pkg/utils"
"net/http" "net/http"
) )
@ -22,11 +23,11 @@ func newController(s *service, utils utils.Utils) *controller {
} }
} }
func (h *Handler) RegisterRoutes(r *gin.RouterGroup) { func (h *Handler) RegisterRoutes(r *gin.RouterGroup, mw *router.Middlewares) {
userGroup := r.Group("/user") userGroup := r.Group("/user")
userGroup.POST("", h.controller.create) userGroup.POST("", mw.RegMW, h.controller.create)
userGroup.DELETE("", h.controller.delete) userGroup.DELETE("", mw.AuthMW, h.controller.delete)
} }
// create godoc // create godoc

View file

@ -1,7 +0,0 @@
package user
import "context"
type Provider interface {
GetUserId(ctx context.Context, userUuid string) (int64, error)
}

View file

@ -1,7 +0,0 @@
package authCheck
import "context"
type AuthChecker interface {
VerifySession(ctx context.Context, sessionUuid string, serviceId int32) (string, error)
}

View file

@ -3,8 +3,6 @@ package router
import ( import (
"context" "context"
"fmt" "fmt"
"merch-api/internal/user"
"merch-api/pkg/authCheck"
"net" "net"
"net/http" "net/http"
@ -14,22 +12,32 @@ import (
ginSwagger "github.com/swaggo/gin-swagger" ginSwagger "github.com/swaggo/gin-swagger"
) )
const pkgLogHeader string = "Router |" const (
tokenCookieName string = "sessionToken"
pkgLogHeader string = "Router |"
)
type Deps struct { type Deps struct {
Host string Host string
Port string Port string
Prefix string Prefix string
GinMode string GinMode string
UserProvider user.Provider UserProvider UserProvider
AuthProvider authCheck.AuthChecker AuthProvider AuthChecker
ServiceId int32 ServiceId int32
} }
type Router struct { type Router struct {
srv *http.Server srv *http.Server
engine *gin.Engine engine *gin.Engine
prefix string prefix string
providers providers
}
type providers struct {
userProvider UserProvider
authChecker AuthChecker
serviceId int32
} }
func NewRouter(deps Deps) *Router { func NewRouter(deps Deps) *Router {
@ -57,8 +65,6 @@ func NewRouter(deps Deps) *Router {
engine.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) engine.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
engine.Use(authMW(deps.UserProvider, deps.AuthProvider, deps.ServiceId))
return &Router{ return &Router{
srv: &http.Server{ srv: &http.Server{
Addr: net.JoinHostPort(deps.Host, deps.Port), Addr: net.JoinHostPort(deps.Host, deps.Port),
@ -66,6 +72,11 @@ func NewRouter(deps Deps) *Router {
}, },
engine: engine, engine: engine,
prefix: deps.Prefix, prefix: deps.Prefix,
providers: providers{
userProvider: deps.UserProvider,
authChecker: deps.AuthProvider,
serviceId: deps.ServiceId,
},
} }
} }
@ -82,3 +93,10 @@ func (r *Router) Shutdown(ctx context.Context) error {
func (r *Router) BaseGroup() *gin.RouterGroup { func (r *Router) BaseGroup() *gin.RouterGroup {
return r.engine.Group(fmt.Sprintf("%v/", r.prefix)) return r.engine.Group(fmt.Sprintf("%v/", r.prefix))
} }
func (r *Router) MWSet() *Middlewares {
return &Middlewares{
AuthMW: AuthMW(r.providers.userProvider, r.providers.authChecker, r.providers.serviceId),
RegMW: RegisterMW(r.providers.authChecker, r.providers.serviceId),
}
}

View file

@ -3,23 +3,35 @@ package router
import ( import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"merch-api/internal/user"
"merch-api/pkg/authCheck"
"merch-api/pkg/responses" "merch-api/pkg/responses"
"net/http" "net/http"
) )
func authMW(up user.Provider, auth authCheck.AuthChecker, serviceId int32) gin.HandlerFunc { type DepsMW struct {
log.Debug("Auth Middleware enabled") UserProv UserProvider
AuthProv AuthChecker
ServiceId int32
}
type Middlewares struct {
AuthMW gin.HandlerFunc
RegMW gin.HandlerFunc
}
func AuthMW(up UserProvider, ap AuthChecker, sid int32) gin.HandlerFunc {
log.Debug("Auth Middlewares enabled")
return func(c *gin.Context) { return func(c *gin.Context) {
cookie, err := c.Cookie("sessionToken") cookie, err := c.Cookie(tokenCookieName)
if err != nil { if err != nil {
c.JSON(http.StatusUnauthorized, responses.Unauthorized{Error: err.Error()}) c.JSON(http.StatusUnauthorized, responses.Unauthorized{Error: err.Error()})
c.Abort() c.Abort()
return
} }
userUuid, err := auth.VerifySession(c, cookie, serviceId) userUuid, err := ap.VerifySession(c, cookie, sid)
if err != nil {
c.JSON(http.StatusUnauthorized, responses.Unauthorized{Error: err.Error()})
c.Abort()
}
userId, err := up.GetUserId(c, userUuid) userId, err := up.GetUserId(c, userUuid)
if err != nil { if err != nil {
@ -33,3 +45,24 @@ func authMW(up user.Provider, auth authCheck.AuthChecker, serviceId int32) gin.H
c.Next() c.Next()
} }
} }
func RegisterMW(ap AuthChecker, sid int32) gin.HandlerFunc {
log.Debug("Auth Middlewares enabled")
return func(c *gin.Context) {
cookie, err := c.Cookie(tokenCookieName)
if err != nil {
c.JSON(http.StatusUnauthorized, responses.Unauthorized{Error: err.Error()})
c.Abort()
return
}
userUuid, err := ap.VerifySession(c, cookie, sid)
if err != nil {
c.JSON(http.StatusUnauthorized, responses.Unauthorized{Error: err.Error()})
c.Abort()
}
c.Set("userUuid", userUuid)
c.Next()
}
}