update middleware.go, response.go

This commit is contained in:
redtea committed 2024-10-22 12:00:00 +03:00
1 parent d24b3837f1
commit ecfac68f89
2 files changed
+50

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
package handler
import (
"esauth/pkg/util"
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
const (
authorizationHeader = "Authorization"
userCtx = "userId"
)
func (h *Handler) userIdentity(c *gin.Context) {
header := c.GetHeader(authorizationHeader)
if header == "" {
util.NewErrorResponse(c, http.StatusUnauthorized, "empty auth header")
return
}
headerParts := strings.Split(header, " ")
if len(headerParts) != 2 {
util.NewErrorResponse(c, http.StatusUnauthorized, "invalid auth header")
return
}
userId, err := h.services.Authorization.ParseToken(headerParts[1])
if err != nil {
util.NewErrorResponse(c, http.StatusUnauthorized, err.Error())
}
c.Set(userCtx, userId)
}
+15
View File
@@ -0,0 +1,15 @@
package util
import (
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
type error struct {
Message string `json:"message"`
}
func NewErrorResponse(c *gin.Context, statusCode int, message string) {
logrus.Error(message)
c.AbortWithStatusJSON(statusCode, error{Message: message})
}