162 lines
4.2 KiB
Go
162 lines
4.2 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type contextKey string
|
|
|
|
const userIDKey contextKey = "user_id"
|
|
const requestIDKey contextKey = "request_id"
|
|
|
|
type statusRecorder struct {
|
|
http.ResponseWriter
|
|
status int
|
|
bytes int
|
|
}
|
|
|
|
func (r *statusRecorder) WriteHeader(status int) {
|
|
r.status = status
|
|
r.ResponseWriter.WriteHeader(status)
|
|
}
|
|
|
|
func (r *statusRecorder) Write(body []byte) (int, error) {
|
|
if r.status == 0 {
|
|
r.status = http.StatusOK
|
|
}
|
|
n, err := r.ResponseWriter.Write(body)
|
|
r.bytes += n
|
|
return n, err
|
|
}
|
|
|
|
func (s *Server) requestID(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
requestID := strings.TrimSpace(r.Header.Get("X-Request-ID"))
|
|
if requestID == "" || len(requestID) > 128 {
|
|
requestID = newRequestID()
|
|
}
|
|
w.Header().Set("X-Request-ID", requestID)
|
|
ctx := context.WithValue(r.Context(), requestIDKey, requestID)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
|
|
func (s *Server) requestLogging(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
recorder := &statusRecorder{ResponseWriter: w}
|
|
next.ServeHTTP(recorder, r)
|
|
status := recorder.status
|
|
if status == 0 {
|
|
status = http.StatusOK
|
|
}
|
|
attrs := []any{
|
|
"request_id", requestID(r),
|
|
"method", r.Method,
|
|
"path", r.URL.Path,
|
|
"status", status,
|
|
"bytes", recorder.bytes,
|
|
"duration_ms", time.Since(start).Milliseconds(),
|
|
"remote", r.RemoteAddr,
|
|
}
|
|
if userID := currentUserID(r); userID != "" {
|
|
attrs = append(attrs, "user_id", userID)
|
|
}
|
|
if status >= 500 {
|
|
s.logger.Error("http request", attrs...)
|
|
return
|
|
}
|
|
s.logger.Info("http request", attrs...)
|
|
})
|
|
}
|
|
|
|
func (s *Server) cors(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
origin := r.Header.Get("Origin")
|
|
if s.isAllowedOrigin(origin) {
|
|
w.Header().Set("Access-Control-Allow-Origin", origin)
|
|
w.Header().Set("Vary", "Origin")
|
|
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
|
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
|
|
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
|
|
w.Header().Set("Access-Control-Expose-Headers", "X-Request-ID")
|
|
}
|
|
if r.Method == http.MethodOptions {
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func (s *Server) isAllowedOrigin(origin string) bool {
|
|
if origin == "" {
|
|
return false
|
|
}
|
|
for _, allowed := range s.cfg.CORSOrigins {
|
|
if allowed == "*" || strings.EqualFold(allowed, origin) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (s *Server) requireAuth(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
authHeader := r.Header.Get("Authorization")
|
|
token := strings.TrimSpace(strings.TrimPrefix(authHeader, "Bearer "))
|
|
if token == "" || token == authHeader {
|
|
writeError(w, http.StatusUnauthorized, nil)
|
|
return
|
|
}
|
|
userID, err := s.auth.VerifyToken(token)
|
|
if err != nil {
|
|
writeError(w, http.StatusUnauthorized, err)
|
|
return
|
|
}
|
|
ctx := context.WithValue(r.Context(), userIDKey, userID)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
|
|
// Admin rights are read from PostgreSQL for every request. A previously
|
|
// issued token does not preserve privileges after an account is demoted.
|
|
func (s *Server) requireAdmin(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
user, err := s.store.GetUser(r.Context(), currentUserID(r))
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, err)
|
|
return
|
|
}
|
|
if user.Role != "admin" {
|
|
writeError(w, http.StatusForbidden, nil)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func currentUserID(r *http.Request) string {
|
|
value, _ := r.Context().Value(userIDKey).(string)
|
|
return value
|
|
}
|
|
|
|
func requestID(r *http.Request) string {
|
|
value, _ := r.Context().Value(requestIDKey).(string)
|
|
return value
|
|
}
|
|
|
|
func newRequestID() string {
|
|
var b [12]byte
|
|
if _, err := rand.Read(b[:]); err != nil {
|
|
return strconv.FormatInt(time.Now().UnixNano(), 36)
|
|
}
|
|
return hex.EncodeToString(b[:])
|
|
}
|