forked from mtusi2026/mtusi2026lab2
lab2 - оценка 5
This commit is contained in:
@@ -0,0 +1,146 @@
|
||||
// package api, middleware.go — охранники + новая аутентификация lab2.
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"mtusi-messenger/internal/store"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/apperr"
|
||||
"mtusi-messenger/internal/model"
|
||||
)
|
||||
|
||||
type ctxKey int
|
||||
|
||||
const (
|
||||
ctxRequestID ctxKey = iota
|
||||
ctxUser // текущий пользователь (из сессии)
|
||||
ctxToken // сам токен (нужен logout'у)
|
||||
ctxCreds // распарсенные Basic-credentials (нужны createSession)
|
||||
)
|
||||
|
||||
// Значения WWW-Authenticate из контракта — одни и те же во всех 401 соответствующего типа.
|
||||
const (
|
||||
wwwBearer = `Bearer realm="messenger"`
|
||||
wwwBasic = `Basic realm="messenger", charset="UTF-8"`
|
||||
)
|
||||
|
||||
// ─────────── Охранник 1: номерок (из lab1) ───────────
|
||||
func requestIDMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.Header.Get("X-Request-Id")
|
||||
if id == "" {
|
||||
id = uuid.NewString()
|
||||
}
|
||||
w.Header().Set("X-Request-Id", id)
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxRequestID, id)))
|
||||
})
|
||||
}
|
||||
|
||||
func requestID(r *http.Request) string {
|
||||
if id, ok := r.Context().Value(ctxRequestID).(string); ok && id != "" {
|
||||
return id
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
// ─────────── Охранник 2: журнал без тел (из lab1) ───────────
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (s *statusWriter) WriteHeader(code int) {
|
||||
s.status = code
|
||||
s.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func loggingMiddleware(log *slog.Logger, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(sw, r)
|
||||
log.Info("http",
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", sw.status,
|
||||
"dur_ms", time.Since(start).Milliseconds(),
|
||||
"request_id", requestID(r),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
// ─────────── Охранник 3: выключатель паник (из lab1) ───────────
|
||||
func recoverMiddleware(log *slog.Logger, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if rec := recover(); rec != nil {
|
||||
log.Error("panic recovered", "path", r.URL.Path, "request_id", requestID(r))
|
||||
apperr.Write(w, requestID(r), apperr.Internal("internal error"))
|
||||
}
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// ─────────── Пропускной пункт lab2: Bearer ───────────
|
||||
// Правила контракта, зашитые сюда:
|
||||
// 1. Нет токена / не Bearer / токен неизвестен|истёк|отозван -> 401 + WWW-Authenticate: Bearer.
|
||||
// 2. Basic на бизнес-endpoint -> 401 (Basic живёт только на /auth/sessions).
|
||||
// 3. X-User-Id ИГНОРИРУЕТСЯ: с lab2 он не даёт доступ вообще (мы его даже не читаем).
|
||||
func (s *Server) auth(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
id := requestID(r)
|
||||
h := r.Header.Get("Authorization")
|
||||
if strings.HasPrefix(h, "Basic ") { // чужая схема на защищённом пути
|
||||
w.Header().Set("WWW-Authenticate", wwwBearer)
|
||||
apperr.Write(w, id, apperr.Unauthorized("Bearer token required"))
|
||||
return
|
||||
}
|
||||
token, ok := parseBearerHeader(r)
|
||||
if !ok {
|
||||
w.Header().Set("WWW-Authenticate", wwwBearer)
|
||||
apperr.Write(w, id, apperr.Unauthorized("Bearer token required"))
|
||||
return
|
||||
}
|
||||
user, err := s.store.SessionUser(r.Context(), token)
|
||||
if err != nil {
|
||||
if store.IsUnavailable(err) { // БД мертва -> 503, а не 401 и не 200
|
||||
apperr.Write(w, id, apperr.Unavailable("database unavailable"))
|
||||
return
|
||||
}
|
||||
w.Header().Set("WWW-Authenticate", wwwBearer)
|
||||
apperr.Write(w, id, apperr.Unauthorized("valid Bearer token required"))
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), ctxUser, user)
|
||||
ctx = context.WithValue(ctx, ctxToken, token) // токен едет дальше: его заберёт logout
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────── Входная дверь: только Basic ───────────
|
||||
// Проверяет ФОРМАТ заголовка; сверку пароля с KDF-хэшем делает хендлер (нужна БД).
|
||||
// Любой провал формата -> 401 + WWW-Authenticate: Basic (тот же ответ, что и
|
||||
// неверные credentials: существование учётки не раскрывается).
|
||||
func (s *Server) basicOnly(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
id := requestID(r)
|
||||
creds, ok := parseBasicHeader(r)
|
||||
if !ok {
|
||||
w.Header().Set("WWW-Authenticate", wwwBasic)
|
||||
apperr.Write(w, id, apperr.Unauthorized("Basic credentials required"))
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxCreds, creds)))
|
||||
}
|
||||
}
|
||||
|
||||
func currentUser(r *http.Request) *model.User { return r.Context().Value(ctxUser).(*model.User) }
|
||||
func currentToken(r *http.Request) string { return r.Context().Value(ctxToken).(string) }
|
||||
func currentCreds(r *http.Request) loginCreds { return r.Context().Value(ctxCreds).(loginCreds) }
|
||||
Reference in New Issue
Block a user