update middleware.go, response.go
This commit is contained in:
1 parent
d24b3837f1
commit
ecfac68f89
2 files changed
+50
No files matched your search
@@ -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)
|
||||||
|
}
|
||||||
@@ -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})
|
||||||
|
}
|
||||||
Reference in new issue
Block a user