lab7: TLS/mTLS по trust matrix, OpenBao (cert auth, KV, policies), роли БД, Argon2id+rehash, лимит входа, hardening, secprobe и тесты
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/charawein/mtusi2026lab7/internal/service"
|
||||
"github.com/charawein/mtusi2026lab7/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type AttachmentHandler struct {
|
||||
attachments *service.AttachmentService
|
||||
}
|
||||
|
||||
func NewAttachmentHandler(attachments *service.AttachmentService) *AttachmentHandler {
|
||||
return &AttachmentHandler{attachments: attachments}
|
||||
}
|
||||
|
||||
// Upload: POST /api/v1/chats/{chat_id}/attachments?filename=... с сырыми байтами PNG/JPEG.
|
||||
func (h *AttachmentHandler) Upload(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
if len(q["filename"]) != 1 {
|
||||
httputil.WriteError(w, r, service.ErrInvalidInput)
|
||||
return
|
||||
}
|
||||
// MaxBytesReader — второй рубеж: не дать прочитать больше лимита + 1 байт,
|
||||
// даже если Content-Length солгал.
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 10*1024*1024+1)
|
||||
a, err := h.attachments.Upload(r.Context(), uid, r.PathValue("chat_id"), q.Get("filename"),
|
||||
r.Header.Get("Content-Type"), r.Body, r.ContentLength)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
// 202: оригинал устойчиво принят, обработка асинхронна; готовность — по GET.
|
||||
httputil.WriteJSON(w, r, http.StatusAccepted, a)
|
||||
}
|
||||
|
||||
// Get: GET /api/v1/attachments/{attachment_id} — метаданные.
|
||||
func (h *AttachmentHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
a, err := h.attachments.Get(r.Context(), uid, r.PathValue("attachment_id"))
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusOK, a)
|
||||
}
|
||||
|
||||
// Content: GET /api/v1/attachments/{attachment_id}/content[?variant=original] — байты
|
||||
// через авторизованный API, без redirect на S3.
|
||||
func (h *AttachmentHandler) Content(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
variant := r.URL.Query().Get("variant")
|
||||
switch variant {
|
||||
case "", "original", "thumbnail", "crop", "optimized":
|
||||
default:
|
||||
httputil.WriteError(w, r, service.ErrInvalidInput)
|
||||
return
|
||||
}
|
||||
c, rc, err := h.attachments.Open(r.Context(), uid, r.PathValue("attachment_id"), variant)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
defer rc.Close()
|
||||
w.Header().Set("Content-Type", c.ContentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(c.Size, 10))
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if n, err := io.Copy(w, rc); err != nil {
|
||||
// Заголовок уже отправлен: клиент увидит обрыв по Content-Length.
|
||||
slog.Warn("attachment download interrupted", "attachment_id", r.PathValue("attachment_id"), "sent", n, "err", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab7/internal/domain"
|
||||
"github.com/charawein/mtusi2026lab7/internal/service"
|
||||
"github.com/charawein/mtusi2026lab7/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
auth *service.AuthService
|
||||
}
|
||||
|
||||
func NewAuthHandler(auth *service.AuthService) *AuthHandler {
|
||||
return &AuthHandler{auth: auth}
|
||||
}
|
||||
|
||||
type sessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
User *domain.User `json:"user"`
|
||||
}
|
||||
|
||||
func (h *AuthHandler) CreateSession(w http.ResponseWriter, r *http.Request) {
|
||||
username, password, ok := parseBasicAuth(r.Header.Get("Authorization"))
|
||||
if !ok {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
sess, u, err := h.auth.Login(r.Context(), username, password)
|
||||
if err != nil {
|
||||
if err == service.ErrUnauthorized {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
}
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
// Формат RFC3339 без микросекунд: "2026-10-09T19:00:36Z".
|
||||
// Python-клиент тестов ожидает 'Z' в конце строки.
|
||||
httputil.WriteJSON(w, r, http.StatusCreated, sessionResponse{
|
||||
Token: sess.Token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: sess.ExpiresAt.UTC().Truncate(time.Second).Format(time.RFC3339),
|
||||
User: u,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *AuthHandler) RevokeSession(w http.ResponseWriter, r *http.Request) {
|
||||
token := bearerToken(r)
|
||||
if token == "" {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
if err := h.auth.Logout(r.Context(), token); err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func parseBasicAuth(h string) (string, string, bool) {
|
||||
const prefix = "Basic "
|
||||
if !strings.HasPrefix(h, prefix) {
|
||||
return "", "", false
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(h[len(prefix):])
|
||||
if err != nil {
|
||||
return "", "", false
|
||||
}
|
||||
parts := strings.SplitN(string(raw), ":", 2)
|
||||
if len(parts) != 2 {
|
||||
return "", "", false
|
||||
}
|
||||
return parts[0], parts[1], true
|
||||
}
|
||||
|
||||
func bearerToken(r *http.Request) string {
|
||||
h := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(h, "Bearer ") {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimPrefix(h, "Bearer ")
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/charawein/mtusi2026lab7/internal/service"
|
||||
"github.com/charawein/mtusi2026lab7/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type ChatHandler struct {
|
||||
chats *service.ChatService
|
||||
}
|
||||
|
||||
func NewChatHandler(chats *service.ChatService) *ChatHandler {
|
||||
return &ChatHandler{chats: chats}
|
||||
}
|
||||
|
||||
func (h *ChatHandler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
if err := httputil.DecodeJSON(r, &body); err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
c, err := h.chats.Create(r.Context(), uid, body.Title, body.MemberIDs)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusCreated, c)
|
||||
}
|
||||
|
||||
func (h *ChatHandler) ListChats(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
limit, err := httputil.ParseLimit(r)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
|
||||
items, next, err := h.chats.List(r.Context(), uid, cursor, limit)
|
||||
if err != nil {
|
||||
// ВРЕМЕННО: логируем точную ошибку
|
||||
slog.Error("ListChats failed", "err", err, "uid", uid, "cursor", cursor, "limit", limit)
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusOK, httputil.PageResponse{Items: items, NextCursor: httputil.NextOrNull(next)})
|
||||
}
|
||||
|
||||
func (h *ChatHandler) GetChat(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
if chatID == "" {
|
||||
httputil.WriteError(w, r, service.ErrInvalidInput)
|
||||
return
|
||||
}
|
||||
|
||||
c, err := h.chats.Get(r.Context(), uid, chatID)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusOK, c)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"github.com/charawein/mtusi2026lab7/internal/service"
|
||||
"github.com/charawein/mtusi2026lab7/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type HealthHandler struct {
|
||||
pool *pgxpool.Pool
|
||||
redis *redis.Client
|
||||
draining *atomic.Bool
|
||||
}
|
||||
|
||||
func NewHealthHandler(pool *pgxpool.Pool, redisClient *redis.Client, draining *atomic.Bool) *HealthHandler {
|
||||
return &HealthHandler{pool: pool, redis: redisClient, draining: draining}
|
||||
}
|
||||
|
||||
// Live проверяет только жизнь процесса.
|
||||
func (h *HealthHandler) Live(w http.ResponseWriter, r *http.Request) {
|
||||
httputil.WriteJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
// Ready проверяет доступность PostgreSQL и Redis.
|
||||
// После SIGTERM возвращает 503, чтобы LB исключил реплику до закрытия listener.
|
||||
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
|
||||
if h.draining.Load() {
|
||||
httputil.WriteError(w, r, service.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := h.pool.Ping(ctx); err != nil {
|
||||
httputil.WriteError(w, r, service.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
if err := h.redis.Ping(ctx).Err(); err != nil {
|
||||
httputil.WriteError(w, r, service.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
type healthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"runtime"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/charawein/mtusi2026lab7/internal/config"
|
||||
)
|
||||
|
||||
// NewInternalStatsHandler отдаёт счётчики пула PostgreSQL и рантайма Go.
|
||||
// Нужен для поиска точки насыщения пула в экспериментах трека 1:
|
||||
// рост empty_acquire_count/acquire_duration означает ожидание свободного соединения.
|
||||
func NewInternalStatsHandler(pool *pgxpool.Pool, cfg config.Config) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /internal/stats", func(w http.ResponseWriter, r *http.Request) {
|
||||
st := pool.Stat()
|
||||
body := map[string]any{
|
||||
"instance_id": cfg.InstanceID,
|
||||
"cache_invalidation": cfg.CacheInvalidation,
|
||||
"pool": map[string]any{
|
||||
"max_conns": st.MaxConns(),
|
||||
"total_conns": st.TotalConns(),
|
||||
"acquired_conns": st.AcquiredConns(),
|
||||
"idle_conns": st.IdleConns(),
|
||||
"acquire_count": st.AcquireCount(),
|
||||
"empty_acquire_count": st.EmptyAcquireCount(),
|
||||
"canceled_acquire_count": st.CanceledAcquireCount(),
|
||||
"acquire_duration_ms": st.AcquireDuration().Milliseconds(),
|
||||
},
|
||||
"goroutines": runtime.NumGoroutine(),
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(body)
|
||||
})
|
||||
return mux
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/charawein/mtusi2026lab7/internal/service"
|
||||
"github.com/charawein/mtusi2026lab7/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type MessageHandler struct {
|
||||
messages *service.MessageService
|
||||
}
|
||||
|
||||
func NewMessageHandler(messages *service.MessageService) *MessageHandler {
|
||||
return &MessageHandler{messages: messages}
|
||||
}
|
||||
|
||||
// attachmentIDs — поле контракта, которое обязано быть JSON-массивом строк.
|
||||
// null недопустим (в отличие от отсутствия поля — его трактуем как пустой
|
||||
// список и пробрасываем дальше как nil-срез).
|
||||
type attachmentIDs struct {
|
||||
present bool
|
||||
value []string
|
||||
}
|
||||
|
||||
var errAttachmentIDsNull = errors.New("attachment_ids must be an array, not null")
|
||||
|
||||
func (a *attachmentIDs) UnmarshalJSON(b []byte) error {
|
||||
a.present = true
|
||||
if string(b) == "null" {
|
||||
return errAttachmentIDsNull
|
||||
}
|
||||
var v []string
|
||||
if err := json.Unmarshal(b, &v); err != nil {
|
||||
return err
|
||||
}
|
||||
a.value = v
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *MessageHandler) SendMessage(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
if chatID == "" {
|
||||
httputil.WriteError(w, r, service.ErrInvalidInput)
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Text *string `json:"text"`
|
||||
AttachmentIDs attachmentIDs `json:"attachment_ids"`
|
||||
}
|
||||
if err := httputil.DecodeJSON(r, &body); err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
if body.Text == nil { // text обязателен по контракту, даже пустой
|
||||
httputil.WriteError(w, r, service.ErrInvalidInput)
|
||||
return
|
||||
}
|
||||
// null в attachment_ids — нарушение контракта; отсутствие поля считаем
|
||||
// пустым списком.
|
||||
if body.AttachmentIDs.present && body.AttachmentIDs.value == nil {
|
||||
// present == true и value == nil возможно только если был null —
|
||||
// но UnmarshalJSON уже вернул ошибку. Оставляем защиту на будущее.
|
||||
httputil.WriteError(w, r, service.ErrInvalidInput)
|
||||
return
|
||||
}
|
||||
|
||||
// Повтор с тем же ключом возвращает тот же 201 и то же сообщение.
|
||||
key := r.Header.Get("Idempotency-Key")
|
||||
m, err := h.messages.Send(r.Context(), uid, chatID, *body.Text, body.AttachmentIDs.value, key)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusCreated, m)
|
||||
}
|
||||
|
||||
func (h *MessageHandler) ListMessages(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
chatID := r.PathValue("chat_id")
|
||||
if chatID == "" {
|
||||
httputil.WriteError(w, r, service.ErrInvalidInput)
|
||||
return
|
||||
}
|
||||
|
||||
limit, err := httputil.ParseLimit(r)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
|
||||
items, next, err := h.messages.List(r.Context(), uid, chatID, cursor, limit)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusOK, httputil.PageResponse{Items: items, NextCursor: httputil.NextOrNull(next)})
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/charawein/mtusi2026lab7/internal/service"
|
||||
"github.com/charawein/mtusi2026lab7/internal/transport/httputil"
|
||||
)
|
||||
|
||||
// Auth проверяет Authorization: Bearer <token> через AuthService.
|
||||
func Auth(auth *service.AuthService) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
header := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(header, "Bearer ") {
|
||||
writeUnauthorized(w, r)
|
||||
return
|
||||
}
|
||||
token := strings.TrimPrefix(header, "Bearer ")
|
||||
if token == "" {
|
||||
writeUnauthorized(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
u, err := auth.ValidateSession(r.Context(), token)
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrUnauthorized) {
|
||||
writeUnauthorized(w, r)
|
||||
return
|
||||
}
|
||||
slog.Error("auth: unexpected", "err", err)
|
||||
httputil.WriteError(w, r, nil)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := httputil.ContextWithUserID(r.Context(), u.ID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func writeUnauthorized(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
// InstanceID добавляет X-Instance-Id ко всем ответам API, включая ошибки и health.
|
||||
// Значение задаётся один раз при старте процесса и не меняется до его завершения.
|
||||
func InstanceID(id string) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", id)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab7/internal/transport/httputil"
|
||||
)
|
||||
|
||||
// Logging — структурный лог запроса (event=http.request) в контексте server span:
|
||||
// trace_id/span_id добавляются обработчиком slog. Вместо сырого пути пишется
|
||||
// шаблон маршрута, тело и заголовки (Authorization) не логируются.
|
||||
func Logging(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
rec, ok := w.(*statusRecorder)
|
||||
if !ok {
|
||||
rec = &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||
}
|
||||
next.ServeHTTP(rec, r)
|
||||
level := slog.LevelInfo
|
||||
if rec.status >= 500 {
|
||||
level = slog.LevelError
|
||||
} else if rec.status >= 400 {
|
||||
level = slog.LevelWarn
|
||||
}
|
||||
slog.Log(r.Context(), level, "http request",
|
||||
"event", "http.request",
|
||||
"request_id", httputil.RequestIDFrom(r.Context()),
|
||||
"method", r.Method,
|
||||
"route", route(r),
|
||||
"status", rec.status,
|
||||
"duration_ms", time.Since(start).Milliseconds(),
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"github.com/charawein/mtusi2026lab7/internal/service"
|
||||
"github.com/charawein/mtusi2026lab7/internal/transport/httputil"
|
||||
)
|
||||
|
||||
// LoginLimiter — общий для всех реплик лимит попыток входа (Redis, фиксированное
|
||||
// окно): отдельно по username и по IP клиента. Превышение — 429 + Retry-After до
|
||||
// конца окна; Argon2id при этом не вычисляется (дорогой hash не становится
|
||||
// усилителем DoS). Ключи Redis — SHA-256 username/IP, не сами значения.
|
||||
//
|
||||
// IP берётся из последнего значения X-Forwarded-For, которое добавляет HAProxy:
|
||||
// API принимает соединения только от LB (mTLS с identity lb), поэтому заголовок
|
||||
// нельзя подделать в обход балансировщика.
|
||||
type LoginLimiter struct {
|
||||
rdb *redis.Client
|
||||
perUser int64
|
||||
perIP int64
|
||||
window time.Duration
|
||||
}
|
||||
|
||||
func NewLoginLimiter(rdb *redis.Client, perUser, perIP int, window time.Duration) *LoginLimiter {
|
||||
return &LoginLimiter{rdb: rdb, perUser: int64(perUser), perIP: int64(perIP), window: window}
|
||||
}
|
||||
|
||||
func clientIP(r *http.Request) string {
|
||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
||||
parts := strings.Split(xff, ",")
|
||||
return strings.TrimSpace(parts[len(parts)-1])
|
||||
}
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
return r.RemoteAddr
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
func basicUser(r *http.Request) string {
|
||||
h := r.Header.Get("Authorization")
|
||||
if len(h) < 6 || !strings.EqualFold(h[:6], "basic ") {
|
||||
return ""
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(h[6:]))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
u, _, _ := strings.Cut(string(raw), ":")
|
||||
return u
|
||||
}
|
||||
|
||||
func hkey(prefix, v string) string {
|
||||
sum := sha256.Sum256([]byte(v))
|
||||
return prefix + hex.EncodeToString(sum[:12])
|
||||
}
|
||||
|
||||
// hit увеличивает счётчик окна и возвращает (значение, оставшийся TTL).
|
||||
func (l *LoginLimiter) hit(r *http.Request, key string) (int64, time.Duration, error) {
|
||||
ctx := r.Context()
|
||||
pipe := l.rdb.TxPipeline()
|
||||
incr := pipe.Incr(ctx, key)
|
||||
pipe.ExpireNX(ctx, key, l.window)
|
||||
ttl := pipe.TTL(ctx, key)
|
||||
if _, err := pipe.Exec(ctx); err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
return incr.Val(), ttl.Val(), nil
|
||||
}
|
||||
|
||||
func (l *LoginLimiter) Wrap(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
checks := []struct {
|
||||
key string
|
||||
limit int64
|
||||
kind string
|
||||
}{{hkey("rl:login:ip:", clientIP(r)), l.perIP, "ip"}}
|
||||
if u := basicUser(r); u != "" {
|
||||
checks = append(checks, struct {
|
||||
key string
|
||||
limit int64
|
||||
kind string
|
||||
}{hkey("rl:login:user:", strings.ToLower(u)), l.perUser, "user"})
|
||||
}
|
||||
for _, c := range checks {
|
||||
n, ttl, err := l.hit(r, c.key)
|
||||
if err != nil {
|
||||
// Без общего счётчика вход не разрешаем (fail closed): 503, не обход лимита.
|
||||
slog.WarnContext(r.Context(), "login rate limiter unavailable", "event", "auth.ratelimit_error", "err", err)
|
||||
httputil.WriteError(w, r, service.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
if n > c.limit {
|
||||
secs := int(ttl.Seconds() + 0.999)
|
||||
if secs < 1 {
|
||||
secs = 1
|
||||
}
|
||||
w.Header().Set("Retry-After", strconv.Itoa(secs))
|
||||
slog.WarnContext(r.Context(), "login rate limited", "event", "auth.rate_limited", "by", c.kind, "retry_after_s", secs)
|
||||
httputil.WriteError(w, r, service.ErrRateLimited)
|
||||
return
|
||||
}
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/charawein/mtusi2026lab7/internal/transport/httputil"
|
||||
)
|
||||
|
||||
func Recovery(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if rec := recover(); rec != nil {
|
||||
slog.Error("panic in handler",
|
||||
"panic", rec,
|
||||
"request_id", httputil.RequestIDFrom(r.Context()),
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
)
|
||||
httputil.WriteError(w, r, nil)
|
||||
}
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/charawein/mtusi2026lab7/internal/transport/httputil"
|
||||
)
|
||||
|
||||
func RequestID(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 = newRequestID()
|
||||
}
|
||||
w.Header().Set("X-Request-Id", id)
|
||||
ctx := httputil.ContextWithRequestID(r.Context(), id)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func newRequestID() string {
|
||||
var b [12]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
panic(fmt.Sprintf("crypto/rand failed: %v", err))
|
||||
}
|
||||
return fmt.Sprintf("%x", b[:])
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"github.com/charawein/mtusi2026lab7/internal/telemetry"
|
||||
"github.com/charawein/mtusi2026lab7/internal/transport/httputil"
|
||||
)
|
||||
|
||||
// statusRecorder запоминает код ответа и число байт тела.
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
bytes int64
|
||||
}
|
||||
|
||||
func (r *statusRecorder) WriteHeader(code int) {
|
||||
r.status = code
|
||||
r.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (r *statusRecorder) Write(b []byte) (int, error) {
|
||||
n, err := r.ResponseWriter.Write(b)
|
||||
r.bytes += int64(n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// Unwrap даёт http.ResponseController доступ к исходному writer.
|
||||
func (r *statusRecorder) Unwrap() http.ResponseWriter { return r.ResponseWriter }
|
||||
|
||||
// route — шаблон маршрута ServeMux без метода ("/api/v1/chats/{chat_id}/messages").
|
||||
// ServeMux записывает его в r.Pattern того же *Request, поэтому читается после
|
||||
// next.ServeHTTP. Неизвестный путь не попадает в метки как сырой URL.
|
||||
func route(r *http.Request) string {
|
||||
p := r.Pattern
|
||||
if p == "" {
|
||||
return "unmatched"
|
||||
}
|
||||
if i := strings.IndexByte(p, ' '); i >= 0 {
|
||||
p = p[i+1:]
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func statusClass(code int) string { return fmt.Sprintf("%dxx", code/100) }
|
||||
|
||||
// Telemetry — server span на запрос и метрика http.server.request.duration
|
||||
// (histogram, секунды; её _count — счётчик запросов). Метки: метод, шаблон
|
||||
// маршрута, код и класс ответа — без user/chat/message ID и сырого URL.
|
||||
func Telemetry(next http.Handler) http.Handler {
|
||||
tracer := telemetry.Tracer()
|
||||
meter := telemetry.Meter()
|
||||
duration, _ := meter.Float64Histogram("http.server.request.duration",
|
||||
metric.WithUnit("s"), metric.WithDescription("Duration of HTTP server requests"))
|
||||
inflight, _ := meter.Int64UpDownCounter("http.server.active_requests",
|
||||
metric.WithUnit("{request}"), metric.WithDescription("In-flight HTTP requests"))
|
||||
prop := otel.GetTextMapPropagator()
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
ctx := prop.Extract(r.Context(), propagation.HeaderCarrier(r.Header))
|
||||
if strings.HasPrefix(r.URL.Path, "/health/") {
|
||||
// Проверки LB раз в секунду: метрики пишем, трассы нет (ParentBased).
|
||||
ctx = telemetry.Unsampled(r.Context())
|
||||
}
|
||||
ctx, span := tracer.Start(ctx, r.Method, trace.WithSpanKind(trace.SpanKindServer),
|
||||
trace.WithAttributes(
|
||||
attribute.String("http.request.method", r.Method),
|
||||
attribute.String("request_id", httputil.RequestIDFrom(r.Context())),
|
||||
))
|
||||
defer span.End()
|
||||
methodAttr := attribute.String("http.request.method", r.Method)
|
||||
inflight.Add(ctx, 1, metric.WithAttributes(methodAttr))
|
||||
defer inflight.Add(ctx, -1, metric.WithAttributes(methodAttr))
|
||||
|
||||
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||
r2 := r.WithContext(ctx)
|
||||
next.ServeHTTP(rec, r2)
|
||||
|
||||
rt := route(r2)
|
||||
span.SetName(r.Method + " " + rt)
|
||||
span.SetAttributes(
|
||||
attribute.String("http.route", rt),
|
||||
attribute.Int("http.response.status_code", rec.status),
|
||||
)
|
||||
if rec.status >= 500 {
|
||||
span.SetStatus(codes.Error, http.StatusText(rec.status))
|
||||
}
|
||||
duration.Record(ctx, time.Since(start).Seconds(), metric.WithAttributes(
|
||||
methodAttr,
|
||||
attribute.String("http.route", rt),
|
||||
attribute.Int("http.response.status_code", rec.status),
|
||||
attribute.String("http.response.status_class", statusClass(rec.status)),
|
||||
))
|
||||
r.Pattern = r2.Pattern // для внешних middleware (логирование)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
|
||||
"go.opentelemetry.io/otel/sdk/metric/metricdata"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
"go.opentelemetry.io/otel/sdk/trace/tracetest"
|
||||
)
|
||||
|
||||
// Метки метрики и имя span — шаблон маршрута, а не сырой путь с UUID;
|
||||
// 5xx помечает span ошибкой; /health/* не создаёт трасс; входящий traceparent
|
||||
// продолжается.
|
||||
func TestTelemetryRouteTemplateAndStatus(t *testing.T) {
|
||||
exp := tracetest.NewInMemoryExporter()
|
||||
otel.SetTracerProvider(sdktrace.NewTracerProvider(sdktrace.WithSyncer(exp)))
|
||||
reader := sdkmetric.NewManualReader()
|
||||
otel.SetMeterProvider(sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader)))
|
||||
otel.SetTextMapPropagator(propagation.TraceContext{})
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
})
|
||||
mux.HandleFunc("GET /health/ready", func(w http.ResponseWriter, r *http.Request) {})
|
||||
h := Telemetry(Logging(mux))
|
||||
|
||||
const chat = "0b5ad0a8-6b44-4d34-9a43-2b4d1f1a7c11"
|
||||
req := httptest.NewRequest("POST", "/api/v1/chats/"+chat+"/messages", nil)
|
||||
req.Header.Set("traceparent", "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
|
||||
h.ServeHTTP(httptest.NewRecorder(), req)
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/health/ready", nil))
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/nope/"+chat, nil))
|
||||
|
||||
spans := exp.GetSpans()
|
||||
if len(spans) != 2 {
|
||||
t.Fatalf("want 2 spans (health is not traced), got %d", len(spans))
|
||||
}
|
||||
s := spans[0]
|
||||
if s.Name != "POST /api/v1/chats/{chat_id}/messages" || s.Status.Code != codes.Error {
|
||||
t.Fatalf("span %q status %v", s.Name, s.Status)
|
||||
}
|
||||
if s.SpanContext.TraceID().String() != "4bf92f3577b34da6a3ce929d0e0e4736" || s.Parent.SpanID().String() != "00f067aa0ba902b7" {
|
||||
t.Fatalf("incoming traceparent not continued: %s parent %s", s.SpanContext.TraceID(), s.Parent.SpanID())
|
||||
}
|
||||
if spans[1].Name != "GET unmatched" {
|
||||
t.Fatalf("unknown path must be 'unmatched', got %q", spans[1].Name)
|
||||
}
|
||||
|
||||
var rm metricdata.ResourceMetrics
|
||||
if err := reader.Collect(context.Background(), &rm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
routes := map[string]bool{}
|
||||
for _, sm := range rm.ScopeMetrics {
|
||||
for _, m := range sm.Metrics {
|
||||
if m.Name != "http.server.request.duration" {
|
||||
continue
|
||||
}
|
||||
for _, dp := range m.Data.(metricdata.Histogram[float64]).DataPoints {
|
||||
for _, kv := range dp.Attributes.ToSlice() {
|
||||
if strings.Contains(kv.Value.Emit(), chat) {
|
||||
t.Fatalf("raw id in metric attribute %s", kv.Key)
|
||||
}
|
||||
}
|
||||
r, _ := dp.Attributes.Value("http.route")
|
||||
routes[r.AsString()] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, want := range []string{"/api/v1/chats/{chat_id}/messages", "/health/ready", "unmatched"} {
|
||||
if !routes[want] {
|
||||
t.Fatalf("route %q not recorded: %v", want, routes)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Timeout ограничивает время выполнения запроса.
|
||||
func Timeout(d time.Duration) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), d)
|
||||
defer cancel()
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"github.com/charawein/mtusi2026lab7/internal/service"
|
||||
"github.com/charawein/mtusi2026lab7/internal/transport/http/middleware"
|
||||
)
|
||||
|
||||
func NewRouter(
|
||||
users *service.UserService,
|
||||
chats *service.ChatService,
|
||||
messages *service.MessageService,
|
||||
attachments *service.AttachmentService,
|
||||
auth *service.AuthService,
|
||||
pool *pgxpool.Pool,
|
||||
redisClient *redis.Client,
|
||||
instanceID string,
|
||||
draining *atomic.Bool,
|
||||
) http.Handler {
|
||||
userH := NewUserHandler(users)
|
||||
chatH := NewChatHandler(chats)
|
||||
msgH := NewMessageHandler(messages)
|
||||
authH := NewAuthHandler(auth)
|
||||
attH := NewAttachmentHandler(attachments)
|
||||
healthH := NewHealthHandler(pool, redisClient, draining)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
|
||||
// Таймаут на запрос: обычный API — 5 s, передача файлов — 30 s.
|
||||
short := middleware.Timeout(5 * time.Second)
|
||||
long := middleware.Timeout(30 * time.Second)
|
||||
authMW := func(h http.Handler) http.Handler { return short(middleware.Auth(auth)(h)) }
|
||||
fileMW := func(h http.Handler) http.Handler { return long(middleware.Auth(auth)(h)) }
|
||||
|
||||
mux.Handle("GET /health/live", short(http.HandlerFunc(healthH.Live)))
|
||||
mux.Handle("GET /health/ready", short(http.HandlerFunc(healthH.Ready)))
|
||||
mux.Handle("POST /api/v1/users", short(http.HandlerFunc(userH.CreateUser)))
|
||||
// Вход: общий для реплик лимит попыток (Redis) до вычисления Argon2id.
|
||||
limiter := middleware.NewLoginLimiter(redisClient, envInt("LOGIN_RATE_PER_USER", 10), envInt("LOGIN_RATE_PER_IP", 60),
|
||||
time.Duration(envInt("LOGIN_RATE_WINDOW_SECONDS", 60))*time.Second)
|
||||
mux.Handle("POST /api/v1/auth/sessions", short(limiter.Wrap(http.HandlerFunc(authH.CreateSession))))
|
||||
|
||||
mux.Handle("DELETE /api/v1/auth/sessions/current", authMW(http.HandlerFunc(authH.RevokeSession)))
|
||||
mux.Handle("GET /api/v1/users/me", authMW(http.HandlerFunc(userH.CurrentUser)))
|
||||
mux.Handle("POST /api/v1/chats", authMW(http.HandlerFunc(chatH.CreateChat)))
|
||||
mux.Handle("GET /api/v1/chats", authMW(http.HandlerFunc(chatH.ListChats)))
|
||||
mux.Handle("GET /api/v1/chats/{chat_id}", authMW(http.HandlerFunc(chatH.GetChat)))
|
||||
mux.Handle("POST /api/v1/chats/{chat_id}/messages", authMW(http.HandlerFunc(msgH.SendMessage)))
|
||||
mux.Handle("GET /api/v1/chats/{chat_id}/messages", authMW(http.HandlerFunc(msgH.ListMessages)))
|
||||
mux.Handle("POST /api/v1/chats/{chat_id}/attachments", fileMW(http.HandlerFunc(attH.Upload)))
|
||||
mux.Handle("GET /api/v1/attachments/{attachment_id}", authMW(http.HandlerFunc(attH.Get)))
|
||||
mux.Handle("GET /api/v1/attachments/{attachment_id}/content", fileMW(http.HandlerFunc(attH.Content)))
|
||||
|
||||
// Telemetry → Recovery → Logging → mux: все middleware до mux передают тот же
|
||||
// *Request, поэтому шаблон маршрута (r.Pattern) виден после обработки;
|
||||
// паника, превращённая Recovery в 500, учитывается в span и метриках.
|
||||
handler := middleware.Logging(mux)
|
||||
handler = middleware.Recovery(handler)
|
||||
handler = middleware.Telemetry(handler)
|
||||
handler = middleware.RequestID(handler)
|
||||
handler = middleware.InstanceID(instanceID)(handler)
|
||||
return handler
|
||||
}
|
||||
|
||||
// NewHealthMux — только health endpoints (локальный listener для docker healthcheck).
|
||||
func NewHealthMux(pool *pgxpool.Pool, redisClient *redis.Client, draining *atomic.Bool) http.Handler {
|
||||
h := NewHealthHandler(pool, redisClient, draining)
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /health/live", h.Live)
|
||||
mux.HandleFunc("GET /health/ready", h.Ready)
|
||||
return middleware.RequestID(mux)
|
||||
}
|
||||
|
||||
func envInt(key string, def int) int {
|
||||
if n, err := strconv.Atoi(os.Getenv(key)); err == nil && n > 0 {
|
||||
return n
|
||||
}
|
||||
return def
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/charawein/mtusi2026lab7/internal/service"
|
||||
"github.com/charawein/mtusi2026lab7/internal/transport/httputil"
|
||||
)
|
||||
|
||||
type UserHandler struct {
|
||||
users *service.UserService
|
||||
}
|
||||
|
||||
func NewUserHandler(users *service.UserService) *UserHandler {
|
||||
return &UserHandler{users: users}
|
||||
}
|
||||
|
||||
func (h *UserHandler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := httputil.DecodeJSON(r, &body); err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
u, err := h.users.Register(r.Context(), body.Username, body.DisplayName, body.Password)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusCreated, u)
|
||||
}
|
||||
|
||||
func (h *UserHandler) CurrentUser(w http.ResponseWriter, r *http.Request) {
|
||||
uid := httputil.UserIDFromContext(r.Context())
|
||||
if uid == "" {
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
u, err := h.users.GetByID(r.Context(), uid)
|
||||
if err != nil {
|
||||
httputil.WriteError(w, r, err)
|
||||
return
|
||||
}
|
||||
httputil.WriteJSON(w, r, http.StatusOK, u)
|
||||
}
|
||||
Reference in New Issue
Block a user