169 lines
4.7 KiB
Go
169 lines
4.7 KiB
Go
package handler
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"messenger/internal/model"
|
|
"messenger/internal/store"
|
|
)
|
|
|
|
type contextKey string
|
|
|
|
const (
|
|
requestIDContextKey contextKey = "request_id"
|
|
userContextKey contextKey = "user"
|
|
tokenContextKey contextKey = "token"
|
|
)
|
|
|
|
type loggingResponseWriter struct {
|
|
http.ResponseWriter
|
|
statusCode int
|
|
}
|
|
|
|
func (lrw *loggingResponseWriter) WriteHeader(code int) {
|
|
lrw.statusCode = code
|
|
lrw.ResponseWriter.WriteHeader(code)
|
|
}
|
|
|
|
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)
|
|
})
|
|
}
|
|
|
|
func RequestIDMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
reqID := strings.TrimSpace(r.Header.Get("X-Request-Id"))
|
|
if reqID == "" {
|
|
reqID = uuid.New().String()
|
|
}
|
|
w.Header().Set("X-Request-Id", reqID)
|
|
ctx := context.WithValue(r.Context(), requestIDContextKey, reqID)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
|
|
func LoggingMiddleware(instanceID string, next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
lrw := &loggingResponseWriter{ResponseWriter: w, statusCode: http.StatusOK}
|
|
|
|
next.ServeHTTP(lrw, r)
|
|
|
|
reqID, _ := r.Context().Value(requestIDContextKey).(string)
|
|
duration := time.Since(start)
|
|
|
|
logEntry := map[string]interface{}{
|
|
"time": time.Now().UTC().Format(time.RFC3339Nano),
|
|
"instance_id": instanceID,
|
|
"method": r.Method,
|
|
"path": r.URL.Path,
|
|
"status": lrw.statusCode,
|
|
"duration_ms": float64(duration.Microseconds()) / 1000.0,
|
|
"request_id": reqID,
|
|
"remote_ip": r.RemoteAddr,
|
|
}
|
|
logBytes, _ := json.Marshal(logEntry)
|
|
fmt.Fprintln(os.Stdout, string(logBytes))
|
|
})
|
|
}
|
|
|
|
func GetRequestID(ctx context.Context) string {
|
|
if val, ok := ctx.Value(requestIDContextKey).(string); ok && val != "" {
|
|
return val
|
|
}
|
|
return uuid.New().String()
|
|
}
|
|
|
|
func WriteError(w http.ResponseWriter, r *http.Request, status int, code, message string) {
|
|
reqID := GetRequestID(r.Context())
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.Header().Set("X-Request-Id", reqID)
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(model.ErrorResponse{
|
|
Error: model.ErrorDetail{
|
|
Code: code,
|
|
Message: message,
|
|
RequestID: reqID,
|
|
},
|
|
})
|
|
}
|
|
|
|
func WriteBasicUnauthorized(w http.ResponseWriter, r *http.Request, message string) {
|
|
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
|
WriteError(w, r, http.StatusUnauthorized, "unauthorized", message)
|
|
}
|
|
|
|
func WriteBearerUnauthorized(w http.ResponseWriter, r *http.Request, message string) {
|
|
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
|
WriteError(w, r, http.StatusUnauthorized, "unauthorized", message)
|
|
}
|
|
|
|
func WriteJSON(w http.ResponseWriter, r *http.Request, status int, data interface{}) {
|
|
reqID := GetRequestID(r.Context())
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.Header().Set("X-Request-Id", reqID)
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(data)
|
|
}
|
|
|
|
func RequireBearerAuth(st store.Store, next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
// Note: X-User-Id is intentionally ignored in Lab 2+ per contract.
|
|
authHeader := strings.TrimSpace(r.Header.Get("Authorization"))
|
|
if authHeader == "" {
|
|
WriteBearerUnauthorized(w, r, "missing Authorization header")
|
|
return
|
|
}
|
|
|
|
parts := strings.SplitN(authHeader, " ", 2)
|
|
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
|
|
WriteBearerUnauthorized(w, r, "Bearer authentication required")
|
|
return
|
|
}
|
|
|
|
rawToken := strings.TrimSpace(parts[1])
|
|
if rawToken == "" || strings.ContainsAny(rawToken, " \t\r\n") {
|
|
WriteBearerUnauthorized(w, r, "invalid Bearer token")
|
|
return
|
|
}
|
|
|
|
user, err := st.GetUserByToken(r.Context(), rawToken)
|
|
if err != nil {
|
|
if errors.Is(err, store.ErrUnavailable) {
|
|
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "storage dependency is temporarily unavailable")
|
|
return
|
|
}
|
|
WriteBearerUnauthorized(w, r, "invalid, expired, or revoked session token")
|
|
return
|
|
}
|
|
|
|
ctx := context.WithValue(r.Context(), userContextKey, user)
|
|
ctx = context.WithValue(ctx, tokenContextKey, rawToken)
|
|
next(w, r.WithContext(ctx))
|
|
}
|
|
}
|
|
|
|
func GetAuthUser(ctx context.Context) *model.User {
|
|
if user, ok := ctx.Value(userContextKey).(*model.User); ok {
|
|
return user
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func GetAuthToken(ctx context.Context) string {
|
|
if tok, ok := ctx.Value(tokenContextKey).(string); ok {
|
|
return tok
|
|
}
|
|
return ""
|
|
}
|