Files
mtusi2026lab2/internal/transport/http/middleware/auth.go
T
OlegRood 834876c938 ЛР 2: закрыть уровень 4
Завершить PostgreSQL, Redis-сессии, миграции, таймауты и диагностику. Зафиксировать собственные тесты и доказательства финального прогона: 43 PASS, 0 FAIL, 0 SKIP; 768 HTTP-запросов без ошибок. Добавить официальный отчёт с запуском, архитектурой, SQL-планами и ограничениями. PR отложен до завершения уровня 5.
2026-10-28 13:30:26 +03:00

64 lines
1.3 KiB
Go

package middleware
import (
"errors"
"highload/internal/service"
"highload/internal/transport/http/httputils"
"net/http"
"github.com/google/uuid"
)
type Middleware struct {
authService *service.AuthService
}
func NewMiddleware(authService *service.AuthService) *Middleware {
return &Middleware{
authService: authService,
}
}
func (m *Middleware) Auth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestID := RequestIDFromContext(r.Context())
token, ok := httputils.ExtractBearerToken(r)
if !ok {
httputils.WriteBearerUnauthorized(w, requestID)
return
}
userID, err := m.authService.ValidateSession(r.Context(), token)
if err != nil {
if errors.Is(err, service.ErrUnauthorized) {
httputils.WriteBearerUnauthorized(w, requestID)
return
}
httputils.WriteServiceError(w, err, requestID)
return
}
ctx := WithUserID(r.Context(), userID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func (m *Middleware) RequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestID := uuid.NewString()
w.Header().Set("X-Request-Id", requestID)
ctx := WithRequestID(r.Context(), requestID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}