Files
mtusi2026lab2/backend/internal/httpapi/middleware/auth.go
T

50 lines
986 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"
)
const CurrentUserKey = "current_user"
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 CurrentUser(c *gin.Context) *domain.User {
if v, ok := c.Get(CurrentUserKey); ok {
if u, ok := v.(*domain.User); ok {
return u
}
}
return nil
}
func abortUnauthorized(c *gin.Context, msg string) {
reqID := GetRequestID(c)
body := dto.ErrorFromDomain(
&domain.UnauthorizedError{Reason: msg},
reqID,
)
c.AbortWithStatusJSON(http.StatusUnauthorized, body)
}