72 lines
2 KiB
Go
72 lines
2 KiB
Go
package router
|
|
|
|
import (
|
|
"github.com/gin-gonic/gin"
|
|
log "github.com/sirupsen/logrus"
|
|
"merch-parser-api/internal/interfaces"
|
|
"merch-parser-api/internal/shared"
|
|
"merch-parser-api/pkg/responses"
|
|
"net/http"
|
|
)
|
|
|
|
type mwDeps struct {
|
|
prefix string
|
|
excludeRoutes *map[string]shared.ExcludeRoute
|
|
tokenProv interfaces.JWTProvider
|
|
usersRefreshRoute string
|
|
}
|
|
|
|
func authMiddleware(deps mwDeps) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if excluded(deps.prefix, c.FullPath(), c.Request.Method, deps.excludeRoutes) {
|
|
log.WithField("msg", "route excluded from auth check").Info("MW | Authorization")
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
if c.FullPath() == deps.usersRefreshRoute && c.Request.Method == "POST" {
|
|
refreshUuid, err := c.Cookie("refresh_uuid")
|
|
if err != nil {
|
|
c.JSON(http.StatusUnauthorized, responses.ErrorResponse401{Error: "Refresh token is required"})
|
|
log.WithField("msg", "Refresh token is required").Error("MW | Authorization")
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Set("refreshUuid", refreshUuid)
|
|
|
|
log.WithField("msg", "refresh token set to context").Debug("MW | Authorization")
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
token := c.GetHeader("Authorization")
|
|
if token == "" {
|
|
c.JSON(http.StatusUnauthorized, responses.ErrorResponse401{Error: "Authorization token is required"})
|
|
log.WithField("msg", "Authorization token is required").Error("MW | Authorization")
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
userUuid, sessionUuid, err := deps.tokenProv.Parse(token)
|
|
if err != nil {
|
|
c.JSON(http.StatusUnauthorized, responses.ErrorResponse401{Error: err.Error()})
|
|
log.WithField("msg", "error parsing jwt").Error("MW | Authorization")
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Set("userUuid", userUuid)
|
|
c.Set("sessionUuid", sessionUuid)
|
|
|
|
log.WithFields(log.Fields{
|
|
"userUuid": userUuid,
|
|
"sessionUuid": sessionUuid,
|
|
}).Debug("MW | Parsed uuids")
|
|
|
|
if !c.IsAborted() {
|
|
log.WithField("msg", "context aborted").Info("MW | Authorization")
|
|
c.Next()
|
|
}
|
|
}
|
|
}
|