39 lines
787 B
Go
39 lines
787 B
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"high-loud-apps-labs/internal/domain"
|
|
"high-loud-apps-labs/internal/httpapi/dto"
|
|
)
|
|
|
|
func Auth(users domain.UserRepository) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
id := c.GetHeader("X-User-Id")
|
|
if id == "" {
|
|
abortUnauthorized(c, "требуется X-User-Id")
|
|
return
|
|
}
|
|
|
|
u, err := users.GetByID(c.Request.Context(), id)
|
|
if err != nil {
|
|
abortUnauthorized(c, "неизвестный пользователь")
|
|
return
|
|
}
|
|
|
|
c.Set(CurrentUserKey, u)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func abortUnauthorized(c *gin.Context, msg string) {
|
|
reqID := GetRequestID(c)
|
|
body := dto.ErrorFromDomain(
|
|
&domain.UnauthorizedError{Reason: msg},
|
|
reqID,
|
|
)
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, body)
|
|
}
|