merch-api/pkg/router/middleware.go

69 lines
1.6 KiB
Go
Raw Permalink Normal View History

2026-02-23 19:33:21 +03:00
package router
2026-03-02 17:31:15 +03:00
2026-03-04 16:59:00 +03:00
import (
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
2026-03-06 19:07:14 +03:00
"merch-api/pkg/responses"
"net/http"
2026-03-04 16:59:00 +03:00
)
2026-03-02 17:31:15 +03:00
2026-03-21 15:21:30 +03:00
type DepsMW struct {
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")
2026-03-02 17:31:15 +03:00
return func(c *gin.Context) {
2026-03-21 15:21:30 +03:00
cookie, err := c.Cookie(tokenCookieName)
2026-03-20 14:53:01 +03:00
if err != nil {
c.JSON(http.StatusUnauthorized, responses.Unauthorized{Error: err.Error()})
c.Abort()
}
2026-03-21 15:21:30 +03:00
userUuid, err := ap.VerifySession(c, cookie, sid)
if err != nil {
c.JSON(http.StatusUnauthorized, responses.Unauthorized{Error: err.Error()})
c.Abort()
}
2026-03-06 19:07:14 +03:00
userId, err := up.GetUserId(c, userUuid)
if err != nil {
c.JSON(http.StatusUnauthorized, responses.Unauthorized{Error: err.Error()})
log.WithError(err).Errorf("%v error converting user uuid to user id: %v", pkgLogHeader, userUuid)
return
}
c.Set("userId", userId)
2026-03-20 16:08:54 +03:00
c.Set("userUuid", userUuid)
2026-03-02 17:31:15 +03:00
c.Next()
}
}
2026-03-21 15:21:30 +03:00
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()
}
}