forked from mtusi2026/mtusi2026lab7
на оценку 4
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
var request dto.CreateChatRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeDecodeJSONError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.service.CreateChat(r.Context(), application.CreateChatCommand{
|
||||
ActorID: currentUser.ID, Title: request.Title, MemberIDs: request.MemberIDs,
|
||||
})
|
||||
if errors.Is(err, application.ErrInvalidInput) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "), requestID)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"one or more members do not exist", requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
response.WriteJSON(w, http.StatusCreated, dto.ChatFromDomain(chat), requestID)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
parsedChatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"invalid chat_id uuid", requestID)
|
||||
return
|
||||
}
|
||||
chatID := parsedChatID.String()
|
||||
|
||||
idempotencyKey := r.Header.Get("Idempotency-Key")
|
||||
if !idempotencyKeyPattern.MatchString(idempotencyKey) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"Idempotency-Key must match [A-Za-z0-9._:-]{1,128}", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
var request dto.CreateMessageRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeDecodeJSONError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
message, err := h.service.SendMessage(r.Context(), application.SendMessageCommand{
|
||||
ActorID: currentUser.ID,
|
||||
ChatID: chatID,
|
||||
Text: request.Text,
|
||||
AttachmentIDs: request.AttachmentIDs,
|
||||
Method: http.MethodPost,
|
||||
CanonicalPath: "/api/v1/chats/" + chatID + "/messages",
|
||||
IdempotencyKey: idempotencyKey,
|
||||
})
|
||||
if errors.Is(err, application.ErrIdempotencyConflict) {
|
||||
response.WriteError(w, http.StatusConflict, response.CodeConflict,
|
||||
"Idempotency-Key is already used for another request", requestID)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, application.ErrAttachmentNotReady) {
|
||||
response.WriteError(w, http.StatusConflict, response.CodeConflict,
|
||||
"attachment is not ready", requestID)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, application.ErrInvalidInput) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "), requestID)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
response.WriteJSON(w, http.StatusCreated, dto.MessageFromDomain(message), requestID)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
func (h *Handler) DeleteCurrentSession(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
tokenHash := middleware.GetCurrentSessionTokenHash(r.Context())
|
||||
if err := h.service.DeleteSession(r.Context(), tokenHash); err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
h.clearSessionCookie(w)
|
||||
response.WriteJSON(w, http.StatusNoContent, nil, requestID)
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func (h *Handler) GetAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
attachmentID, ok := parseAttachmentID(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
attachment, err := h.service.GetAttachment(r.Context(), attachmentID, currentUser.ID)
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound,
|
||||
"attachment not found", requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
response.WriteJSON(w, http.StatusOK, dto.AttachmentFromDomain(attachment), requestID)
|
||||
}
|
||||
|
||||
func (h *Handler) DownloadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
attachmentID, ok := parseAttachmentID(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
download, err := h.service.DownloadAttachment(
|
||||
r.Context(), attachmentID, currentUser.ID, r.URL.Query().Get("variant"),
|
||||
)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound,
|
||||
"attachment or variant not found", requestID)
|
||||
return
|
||||
case errors.Is(err, application.ErrAttachmentNotReady):
|
||||
response.WriteError(w, http.StatusConflict, response.CodeConflict,
|
||||
"attachment is not ready", requestID)
|
||||
return
|
||||
case errors.Is(err, application.ErrStorageUnavailable):
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"object storage is temporarily unavailable", requestID)
|
||||
return
|
||||
case err != nil:
|
||||
response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError,
|
||||
"unexpected internal error", requestID)
|
||||
return
|
||||
}
|
||||
defer download.Body.Close()
|
||||
|
||||
w.Header().Set("Content-Type", download.ContentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(download.SizeBytes, 10))
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Content-Disposition", mime.FormatMediaType(
|
||||
"attachment", map[string]string{"filename": download.Filename},
|
||||
))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = io.Copy(w, download.Body)
|
||||
}
|
||||
|
||||
func parseAttachmentID(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
requestID string,
|
||||
) (string, bool) {
|
||||
parsedID, err := uuid.Parse(r.PathValue("attachment_id"))
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"invalid attachment_id uuid", requestID)
|
||||
return "", false
|
||||
}
|
||||
return parsedID.String(), true
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"invalid chat_id uuid", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.service.GetChat(r.Context(), currentUser.ID, chatID)
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
response.WriteJSON(w, http.StatusOK, dto.ChatFromDomain(chat), requestID)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
func (h *Handler) GetMe(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
response.WriteJSON(w, http.StatusOK, dto.UserFromDomain(currentUser), requestID)
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
const maxJSONBodyBytes = 1 << 20
|
||||
|
||||
var (
|
||||
errUnsupportedMediaType = errors.New("unsupported media type")
|
||||
errJSONBodyTooLarge = errors.New("JSON body exceeds 1 MiB")
|
||||
)
|
||||
|
||||
type ReadinessChecker interface {
|
||||
Ping(ctx context.Context) error
|
||||
}
|
||||
|
||||
type LoginRateLimiter interface {
|
||||
AllowLoginAttempt(context.Context, [32]byte, time.Time, time.Duration, int) (bool, time.Duration, error)
|
||||
ResetLoginAttempts(context.Context, [32]byte) error
|
||||
}
|
||||
|
||||
type Option func(*Handler)
|
||||
|
||||
type Handler struct {
|
||||
service *application.Service
|
||||
readinessChecker ReadinessChecker
|
||||
readinessTimeout time.Duration
|
||||
sessionCookieSecure bool
|
||||
loginRateLimiter LoginRateLimiter
|
||||
loginRateLimit int
|
||||
loginRateWindow time.Duration
|
||||
}
|
||||
|
||||
func NewHandler(
|
||||
service *application.Service,
|
||||
options ...Option,
|
||||
) *Handler {
|
||||
handler := &Handler{
|
||||
service: service,
|
||||
readinessTimeout: 2 * time.Second,
|
||||
loginRateLimit: 5,
|
||||
loginRateWindow: time.Minute,
|
||||
}
|
||||
|
||||
for _, option := range options {
|
||||
option(handler)
|
||||
}
|
||||
|
||||
return handler
|
||||
}
|
||||
|
||||
func WithLoginRateLimit(
|
||||
limiter LoginRateLimiter,
|
||||
limit int,
|
||||
window time.Duration,
|
||||
) Option {
|
||||
return func(handler *Handler) {
|
||||
handler.loginRateLimiter = limiter
|
||||
handler.loginRateLimit = limit
|
||||
handler.loginRateWindow = window
|
||||
}
|
||||
}
|
||||
|
||||
func WithReadiness(
|
||||
checker ReadinessChecker,
|
||||
timeout time.Duration,
|
||||
) Option {
|
||||
return func(handler *Handler) {
|
||||
handler.readinessChecker = checker
|
||||
handler.readinessTimeout = timeout
|
||||
}
|
||||
}
|
||||
|
||||
func WithSessionCookieSecure(secure bool) Option {
|
||||
return func(handler *Handler) {
|
||||
handler.sessionCookieSecure = secure
|
||||
}
|
||||
}
|
||||
|
||||
func decodeJSON(r *http.Request, destination any) error {
|
||||
mediaType, parameters, err := mime.ParseMediaType(
|
||||
r.Header.Get("Content-Type"),
|
||||
)
|
||||
if err != nil || mediaType != "application/json" {
|
||||
return errUnsupportedMediaType
|
||||
}
|
||||
if charset, exists := parameters["charset"]; exists &&
|
||||
!strings.EqualFold(charset, "utf-8") {
|
||||
return errUnsupportedMediaType
|
||||
}
|
||||
|
||||
if r.Body == nil {
|
||||
return errors.New("request body is empty")
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
payload, err := io.ReadAll(io.LimitReader(
|
||||
r.Body,
|
||||
maxJSONBodyBytes+1,
|
||||
))
|
||||
if err != nil {
|
||||
return errors.New("read request body")
|
||||
}
|
||||
if len(payload) > maxJSONBodyBytes {
|
||||
return errJSONBodyTooLarge
|
||||
}
|
||||
if !utf8.Valid(payload) {
|
||||
return errors.New("request body must be valid UTF-8")
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(bytes.NewReader(payload))
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(destination); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var extra json.RawMessage
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return errors.New("extra data after JSON")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeDecodeJSONError(
|
||||
w http.ResponseWriter,
|
||||
requestID string,
|
||||
err error,
|
||||
) {
|
||||
switch {
|
||||
case errors.Is(err, errUnsupportedMediaType):
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusUnsupportedMediaType,
|
||||
response.CodeUnsupportedMediaType,
|
||||
"Content-Type must be application/json",
|
||||
requestID,
|
||||
)
|
||||
case errors.Is(err, errJSONBodyTooLarge):
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusRequestEntityTooLarge,
|
||||
response.CodePayloadTooLarge,
|
||||
err.Error(),
|
||||
requestID,
|
||||
)
|
||||
default:
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
"malformed or invalid JSON: "+err.Error(),
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDecodeJSONRejectsBodyAboveOneMiB(t *testing.T) {
|
||||
request := httptest.NewRequest(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
strings.NewReader(strings.Repeat(" ", maxJSONBodyBytes+1)),
|
||||
)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
var destination map[string]any
|
||||
err := decodeJSON(request, &destination)
|
||||
if !errors.Is(err, errJSONBodyTooLarge) {
|
||||
t.Fatalf("expected errJSONBodyTooLarge, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
// HealthLive проверяет только то, что HTTP-процесс работает.
|
||||
func (h *Handler) HealthLive(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusOK,
|
||||
map[string]string{"status": "ok"},
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
|
||||
// HealthReady проверяет зависимости, без которых API не может обслуживать трафик.
|
||||
func (h *Handler) HealthReady(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
// Этот вариант сохраняет работоспособность изолированных unit-тестов,
|
||||
// в которых PostgreSQL намеренно не создаётся.
|
||||
if h.readinessChecker == nil {
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusOK,
|
||||
map[string]string{"status": "ok"},
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(
|
||||
r.Context(),
|
||||
h.readinessTimeout,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
if err := h.readinessChecker.Ping(ctx); err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is not ready",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusOK,
|
||||
map[string]string{"status": "ok"},
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
limit, cursor, ok := parsePagination(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
page, err := h.service.ListChats(r.Context(), currentUser.ID, limit, cursor)
|
||||
if errors.Is(err, application.ErrInvalidCursor) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid cursor", requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
response.WriteJSON(w, http.StatusOK, dto.ChatPageFromDomain(page), requestID)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func (h *Handler) GetMessages(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"invalid chat_id uuid", requestID)
|
||||
return
|
||||
}
|
||||
limit, cursor, ok := parsePagination(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
page, err := h.service.ListMessages(r.Context(), currentUser.ID, chatID, limit, cursor)
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", requestID)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, application.ErrInvalidCursor) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid cursor", requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
response.WriteJSON(w, http.StatusOK, dto.MessagePageFromDomain(page), requestID)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
func parsePagination(w http.ResponseWriter, r *http.Request, requestID string) (int, string, bool) {
|
||||
query := r.URL.Query()
|
||||
limit := 50
|
||||
if query.Has("limit") {
|
||||
parsed, err := strconv.Atoi(query.Get("limit"))
|
||||
if err != nil || parsed < 1 || parsed > 100 {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"limit must be an integer between 1 and 100", requestID)
|
||||
return 0, "", false
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
cursor := query.Get("cursor")
|
||||
if query.Has("cursor") && cursor == "" {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"cursor must not be empty", requestID)
|
||||
return 0, "", false
|
||||
}
|
||||
return limit, cursor, true
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
const sessionCookieName = "mtusi_session"
|
||||
|
||||
func (h *Handler) setSessionCookie(
|
||||
w http.ResponseWriter,
|
||||
token string,
|
||||
expiresAt time.Time,
|
||||
) {
|
||||
maxAge := int(time.Until(expiresAt).Seconds())
|
||||
if maxAge < 1 {
|
||||
maxAge = 1
|
||||
}
|
||||
|
||||
h.writeSessionCookie(w, token, expiresAt, maxAge)
|
||||
}
|
||||
|
||||
func (h *Handler) clearSessionCookie(w http.ResponseWriter) {
|
||||
h.writeSessionCookie(w, "", time.Unix(1, 0).UTC(), -1)
|
||||
}
|
||||
|
||||
func (h *Handler) writeSessionCookie(
|
||||
w http.ResponseWriter,
|
||||
value string,
|
||||
expiresAt time.Time,
|
||||
maxAge int,
|
||||
) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: sessionCookieName, Value: value, Path: "/",
|
||||
Expires: expiresAt, MaxAge: maxAge,
|
||||
HttpOnly: true, Secure: h.sessionCookieSecure,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSessionCookieIsHardened(t *testing.T) {
|
||||
handler := &Handler{sessionCookieSecure: true}
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
handler.setSessionCookie(
|
||||
recorder,
|
||||
"secret-token",
|
||||
time.Now().Add(time.Hour),
|
||||
)
|
||||
|
||||
cookies := recorder.Result().Cookies()
|
||||
if len(cookies) != 1 {
|
||||
t.Fatalf("cookie count = %d, want 1", len(cookies))
|
||||
}
|
||||
|
||||
cookie := cookies[0]
|
||||
if cookie.Name != sessionCookieName || cookie.Value != "secret-token" {
|
||||
t.Fatalf("unexpected cookie: %#v", cookie)
|
||||
}
|
||||
if cookie.Path != "/" || cookie.Domain != "" {
|
||||
t.Fatalf("cookie scope = path %q domain %q", cookie.Path, cookie.Domain)
|
||||
}
|
||||
if !cookie.HttpOnly || !cookie.Secure {
|
||||
t.Fatalf("cookie flags: HttpOnly=%v Secure=%v", cookie.HttpOnly, cookie.Secure)
|
||||
}
|
||||
if cookie.SameSite != http.SameSiteStrictMode {
|
||||
t.Fatalf("SameSite = %v, want Strict", cookie.SameSite)
|
||||
}
|
||||
if cookie.MaxAge < 1 {
|
||||
t.Fatalf("MaxAge = %d, want positive", cookie.MaxAge)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClearSessionCookieExpiresIt(t *testing.T) {
|
||||
handler := &Handler{}
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
handler.clearSessionCookie(recorder)
|
||||
|
||||
cookies := recorder.Result().Cookies()
|
||||
if len(cookies) != 1 {
|
||||
t.Fatalf("cookie count = %d, want 1", len(cookies))
|
||||
}
|
||||
|
||||
cookie := cookies[0]
|
||||
if cookie.Value != "" || cookie.MaxAge != -1 {
|
||||
t.Fatalf("clear cookie = value %q MaxAge %d", cookie.Value, cookie.MaxAge)
|
||||
}
|
||||
if !cookie.Expires.Before(time.Now()) {
|
||||
t.Fatalf("clear cookie expiry %v is not in the past", cookie.Expires)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
const basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
|
||||
func (h *Handler) CreateSession(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || username == "" ||
|
||||
!utf8.ValidString(username) || !utf8.ValidString(password) {
|
||||
writeBasicUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
identifierHash := sha256.Sum256([]byte(strings.ToLower(username)))
|
||||
if h.loginRateLimiter != nil {
|
||||
allowed, retryAfter, err := h.loginRateLimiter.AllowLoginAttempt(
|
||||
r.Context(), identifierHash, time.Now().UTC(), h.loginRateWindow, h.loginRateLimit,
|
||||
)
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
if !allowed {
|
||||
seconds := int(math.Ceil(retryAfter.Seconds()))
|
||||
if seconds < 1 {
|
||||
seconds = 1
|
||||
}
|
||||
w.Header().Set("Retry-After", strconv.Itoa(seconds))
|
||||
response.WriteError(w, http.StatusTooManyRequests, response.CodeRateLimited,
|
||||
"too many login attempts", requestID)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
session, err := h.service.CreateSession(r.Context(), application.CreateSessionCommand{
|
||||
Username: username,
|
||||
Password: password,
|
||||
})
|
||||
if errors.Is(err, application.ErrCredentialState) {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusInternalServerError,
|
||||
response.CodeInternalError,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, application.ErrInvalidCredentials) {
|
||||
writeBasicUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
if h.loginRateLimiter != nil {
|
||||
if err = h.loginRateLimiter.ResetLoginAttempts(r.Context(), identifierHash); err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
h.setSessionCookie(w, session.Token, session.ExpiresAt)
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusCreated,
|
||||
dto.SessionFromDomain(session),
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
func writeBasicUnauthorized(
|
||||
w http.ResponseWriter,
|
||||
requestID string,
|
||||
) {
|
||||
w.Header().Set("WWW-Authenticate", basicChallenge)
|
||||
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusUnauthorized,
|
||||
response.CodeUnauthorized,
|
||||
"invalid username or password",
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func (h *Handler) UploadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
parsedChatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"invalid chat_id uuid", requestID)
|
||||
return
|
||||
}
|
||||
filename := r.URL.Query().Get("filename")
|
||||
if filename == "" {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"filename query parameter is required", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
contentType, parameters, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil || len(parameters) != 0 ||
|
||||
(contentType != "image/png" && contentType != "image/jpeg") {
|
||||
response.WriteError(w, http.StatusUnsupportedMediaType,
|
||||
response.CodeUnsupportedMediaType,
|
||||
"Content-Type must be image/png or image/jpeg", requestID)
|
||||
return
|
||||
}
|
||||
if r.ContentLength > domain.MaxAttachmentSizeBytes {
|
||||
response.WriteError(w, http.StatusRequestEntityTooLarge,
|
||||
response.CodePayloadTooLarge,
|
||||
"attachment exceeds 10 MiB", requestID)
|
||||
return
|
||||
}
|
||||
if r.Body == nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"attachment body is required", requestID)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
attachment, err := h.service.UploadAttachment(
|
||||
r.Context(),
|
||||
application.UploadAttachmentCommand{
|
||||
ActorID: currentUser.ID,
|
||||
ChatID: parsedChatID.String(),
|
||||
Filename: filename,
|
||||
DeclaredContentType: contentType,
|
||||
Body: r.Body,
|
||||
},
|
||||
)
|
||||
switch {
|
||||
case errors.Is(err, application.ErrPayloadTooLarge):
|
||||
response.WriteError(w, http.StatusRequestEntityTooLarge,
|
||||
response.CodePayloadTooLarge,
|
||||
"attachment exceeds 10 MiB or 40 million pixels", requestID)
|
||||
return
|
||||
case errors.Is(err, application.ErrUnsupportedMediaType), errors.Is(err, application.ErrInvalidImage):
|
||||
response.WriteError(w, http.StatusUnsupportedMediaType,
|
||||
response.CodeUnsupportedMediaType,
|
||||
"body is not a valid PNG/JPEG matching the declared Content-Type", requestID)
|
||||
return
|
||||
case errors.Is(err, application.ErrInvalidInput):
|
||||
message := strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": ")
|
||||
response.WriteError(w, http.StatusBadRequest,
|
||||
response.CodeInvalidRequest, message, requestID)
|
||||
return
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
response.WriteError(w, http.StatusNotFound,
|
||||
response.CodeNotFound, "chat not found", requestID)
|
||||
return
|
||||
case errors.Is(err, application.ErrStorageUnavailable):
|
||||
response.WriteError(w, http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable, "object storage is temporarily unavailable", requestID)
|
||||
return
|
||||
case err != nil:
|
||||
response.WriteError(w, http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable, "service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(w, http.StatusAccepted, dto.AttachmentFromDomain(attachment), requestID)
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
var request dto.CreateUserRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeDecodeJSONError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
|
||||
createdUser, err := h.service.CreateUser(r.Context(), application.CreateUserCommand{
|
||||
Username: request.Username, DisplayName: request.DisplayName, Password: request.Password,
|
||||
})
|
||||
if errors.Is(err, application.ErrInvalidInput) {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "),
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if errors.Is(err, domain.ErrConflict) {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusConflict,
|
||||
response.CodeConflict,
|
||||
"username already exists",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusCreated,
|
||||
dto.UserFromDomain(createdUser),
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user