146 lines
4.5 KiB
Go
146 lines
4.5 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"mtusi-messenger/internal/apperr"
|
|
"mtusi-messenger/internal/model"
|
|
"mtusi-messenger/internal/store"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type ctxKey int
|
|
|
|
const (
|
|
ctxRequestID ctxKey = iota
|
|
ctxUser
|
|
ctxToken
|
|
ctxCreds
|
|
)
|
|
|
|
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)
|
|
})
|
|
}
|
|
|
|
// ─────────── Охранник 4: Идентификатор реплики (Lab 3) ───────────
|
|
func instanceIDMiddleware(instanceID string, next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("X-Instance-Id", instanceID)
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
// ─────────── Пропускной пункт lab2: Bearer ───────────
|
|
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) {
|
|
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)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
}
|
|
}
|
|
|
|
// ─────────── Входная дверь: только Basic ───────────
|
|
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) }
|