forked from mtusi2026/mtusi2026lab2
refactor: update project structure
This commit is contained in:
@@ -24,6 +24,10 @@ target/
|
|||||||
bin/
|
bin/
|
||||||
obj/
|
obj/
|
||||||
coverage/
|
coverage/
|
||||||
|
.vite/
|
||||||
|
*.tsbuildinfo
|
||||||
|
*.test
|
||||||
|
*.out
|
||||||
*.log
|
*.log
|
||||||
.DS_Store
|
.DS_Store
|
||||||
.idea/
|
.idea/
|
||||||
|
|||||||
+2
-2
@@ -6,7 +6,7 @@ COPY go.mod go.sum ./
|
|||||||
|
|
||||||
RUN go mod download
|
RUN go mod download
|
||||||
|
|
||||||
COPY src ./src
|
COPY src/backend ./src/backend
|
||||||
|
|
||||||
RUN CGO_ENABLED=0 \
|
RUN CGO_ENABLED=0 \
|
||||||
GOOS=linux \
|
GOOS=linux \
|
||||||
@@ -14,7 +14,7 @@ RUN CGO_ENABLED=0 \
|
|||||||
-trimpath \
|
-trimpath \
|
||||||
-ldflags="-s -w" \
|
-ldflags="-s -w" \
|
||||||
-o /out/messenger \
|
-o /out/messenger \
|
||||||
./src
|
./src/backend
|
||||||
|
|
||||||
|
|
||||||
FROM debian:12.15-slim
|
FROM debian:12.15-slim
|
||||||
|
|||||||
@@ -1,26 +1,47 @@
|
|||||||
PYTHON ?= python3
|
PYTHON ?= python3
|
||||||
BASE_URL ?= http://localhost:8080
|
BASE_URL ?= http://localhost:8080
|
||||||
CA_FILE ?=
|
CA_FILE ?=
|
||||||
ACTION_SCRIPT ?=
|
ACTION_SCRIPT ?=
|
||||||
|
COMPOSE = docker compose --env-file .env
|
||||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||||
|
|
||||||
.PHONY: help check validate test load test-persistence
|
.PHONY: help app-up app-down app-logs check validate test test-backend load test-persistence
|
||||||
|
|
||||||
help:
|
help:
|
||||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
@echo "app-up: build and start API, database and frontend (http://localhost:5173)"
|
||||||
|
@echo "app-down: stop the application and keep PostgreSQL data"
|
||||||
|
@echo "app-logs: follow service logs"
|
||||||
|
@echo "check: offline contract structure"
|
||||||
|
@echo "validate: full OpenAPI validation (install requirements-dev.txt first)"
|
||||||
|
@echo "test: public API smoke test (run app-up first)"
|
||||||
|
@echo "test-backend: Go tests with PostgreSQL and race detection in isolated schemas"
|
||||||
|
@echo "test-persistence ACTION_SCRIPT=scripts/restart.sh: restart API and DB, verify saved data and session (run app-up first)"
|
||||||
|
@echo "load: synthetic API writes"
|
||||||
|
|
||||||
check:
|
app-up:
|
||||||
$(PYTHON) scripts/check_contract.py
|
$(COMPOSE) up -d --build --wait
|
||||||
|
|
||||||
validate:
|
app-down:
|
||||||
$(PYTHON) scripts/validate_openapi.py
|
$(COMPOSE) down
|
||||||
|
|
||||||
|
app-logs:
|
||||||
|
$(COMPOSE) logs -f
|
||||||
|
|
||||||
|
check:
|
||||||
|
$(PYTHON) scripts/check_contract.py
|
||||||
|
|
||||||
|
validate:
|
||||||
|
$(PYTHON) scripts/validate_openapi.py
|
||||||
|
|
||||||
test:
|
test:
|
||||||
$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
load:
|
test-backend:
|
||||||
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(COMPOSE) --profile test run --build --rm backend-tests
|
||||||
|
|
||||||
test-persistence:
|
load:
|
||||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
|
||||||
|
test-persistence:
|
||||||
|
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
||||||
|
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|||||||
@@ -29,6 +29,35 @@ services:
|
|||||||
interval: 5s
|
interval: 5s
|
||||||
timeout: 3s
|
timeout: 3s
|
||||||
retries: 20
|
retries: 20
|
||||||
|
backend-tests:
|
||||||
|
profiles: ["test"]
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
target: builder
|
||||||
|
environment:
|
||||||
|
TEST_DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}?sslmode=disable
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
command: ["go", "test", "-race", "-count=1", "-v", "./src/backend/..."]
|
||||||
|
frontend:
|
||||||
|
build:
|
||||||
|
context: ./src/frontend
|
||||||
|
environment:
|
||||||
|
API_PROXY_TARGET: http://api:8080
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:5173:5173"
|
||||||
|
volumes:
|
||||||
|
- ./src/frontend:/app
|
||||||
|
- /app/node_modules
|
||||||
|
depends_on:
|
||||||
|
api:
|
||||||
|
condition: service_healthy
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:5173/').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
postgres_data:
|
postgres_data:
|
||||||
|
|||||||
@@ -18,5 +18,6 @@ require (
|
|||||||
github.com/jackc/puddle/v2 v2.2.1 // indirect
|
github.com/jackc/puddle/v2 v2.2.1 // indirect
|
||||||
go.uber.org/atomic v1.7.0 // indirect
|
go.uber.org/atomic v1.7.0 // indirect
|
||||||
golang.org/x/sync v0.5.0 // indirect
|
golang.org/x/sync v0.5.0 // indirect
|
||||||
|
golang.org/x/sys v0.19.0 // indirect
|
||||||
golang.org/x/text v0.14.0 // indirect
|
golang.org/x/text v0.14.0 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,128 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"messenger/src/backend/services"
|
||||||
|
)
|
||||||
|
|
||||||
|
type createChatRequest struct {
|
||||||
|
Title string `json:"title"`
|
||||||
|
MemberIDs []string `json:"member_ids"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func createChatHandler(chats *services.ChatService) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
requestID := newRequestID()
|
||||||
|
w.Header().Set("X-Request-Id", requestID)
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
userID, ok := requestUserID(w, r, requestID)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {
|
||||||
|
writeError(w, 415, "unsupported_media_type", "content type must be application/json", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var request createChatRequest
|
||||||
|
if err := decodeJSONBody(r, &request); err != nil {
|
||||||
|
writeError(w, 400, "invalid_request", "invalid JSON body", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
chat, err := chats.Create(r.Context(), userID, request.Title, request.MemberIDs)
|
||||||
|
if err != nil {
|
||||||
|
writeServiceError(w, err, requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, 201, chat)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func getChatHandler(chats *services.ChatService) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
requestID := newRequestID()
|
||||||
|
w.Header().Set("X-Request-Id", requestID)
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
userID, ok := requestUserID(w, r, requestID)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
chatID := strings.TrimPrefix(r.URL.Path, "/api/v1/chats/")
|
||||||
|
if chatID == "" || strings.Contains(chatID, "/") {
|
||||||
|
writeError(w, 400, "invalid_request", "invalid chat id", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err := uuid.Parse(chatID); err != nil {
|
||||||
|
writeError(w, 400, "invalid_request", "invalid chat id", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
chat, err := chats.Get(r.Context(), userID, chatID)
|
||||||
|
if err != nil {
|
||||||
|
writeServiceError(w, err, requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, 200, chat)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func listChatsHandler(chats *services.ChatService) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
requestID := newRequestID()
|
||||||
|
w.Header().Set("X-Request-Id", requestID)
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
userID, ok := requestUserID(w, r, requestID)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
limit, cursor, ok := pageParams(w, r, requestID)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page, err := chats.List(r.Context(), userID, limit, cursor)
|
||||||
|
if err != nil {
|
||||||
|
writeServiceError(w, err, requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, 200, page)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func chatCollectionHandler(chats *services.ChatService) http.HandlerFunc {
|
||||||
|
create := createChatHandler(chats)
|
||||||
|
list := listChatsHandler(chats)
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method == http.MethodGet {
|
||||||
|
list(w, r)
|
||||||
|
} else {
|
||||||
|
create(w, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func chatSubresourceHandler(chats *services.ChatService, messages *services.MessageService) http.HandlerFunc {
|
||||||
|
get := getChatHandler(chats)
|
||||||
|
createMessage := createMessageHandler(chats, messages)
|
||||||
|
listMessages := listMessagesHandler(chats, messages)
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if strings.HasSuffix(r.URL.Path, "/messages") {
|
||||||
|
if r.Method == http.MethodGet {
|
||||||
|
listMessages(w, r)
|
||||||
|
} else {
|
||||||
|
createMessage(w, r)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
get(w, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"messenger/src/backend/services"
|
||||||
|
)
|
||||||
|
|
||||||
|
type healthResponse struct {
|
||||||
|
Status string `json:"status"`
|
||||||
|
}
|
||||||
|
type apiError struct {
|
||||||
|
Code string `json:"code"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
RequestID string `json:"request_id"`
|
||||||
|
}
|
||||||
|
type errorResponse struct {
|
||||||
|
Error apiError `json:"error"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func newRequestID() string {
|
||||||
|
bytes := make([]byte, 16)
|
||||||
|
if _, err := rand.Read(bytes); err != nil {
|
||||||
|
return "request-id-generation-failed"
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeError(w http.ResponseWriter, status int, code, message, requestID string) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(status)
|
||||||
|
response := errorResponse{Error: apiError{Code: code, Message: message, RequestID: requestID}}
|
||||||
|
if err := json.NewEncoder(w).Encode(response); err != nil {
|
||||||
|
log.Printf("failed to encode error response: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeServiceError(w http.ResponseWriter, err error, requestID string) {
|
||||||
|
var invalid services.InvalidInput
|
||||||
|
switch {
|
||||||
|
case errors.As(err, &invalid):
|
||||||
|
writeError(w, 400, "invalid_request", invalid.Message, requestID)
|
||||||
|
case errors.Is(err, services.ErrConflict):
|
||||||
|
writeError(w, 409, "conflict", "username is already taken", requestID)
|
||||||
|
case errors.Is(err, services.ErrUnknownUser):
|
||||||
|
writeError(w, 401, "unauthorized", "unknown user", requestID)
|
||||||
|
case errors.Is(err, services.ErrChatNotFound):
|
||||||
|
writeError(w, 404, "not_found", "chat not found", requestID)
|
||||||
|
default:
|
||||||
|
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(status)
|
||||||
|
if err := json.NewEncoder(w).Encode(value); err != nil {
|
||||||
|
log.Printf("failed to encode response: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func requestUserID(w http.ResponseWriter, r *http.Request, requestID string) (string, bool) {
|
||||||
|
id := currentUserID(r)
|
||||||
|
if id == "" {
|
||||||
|
writeError(w, 401, "unauthorized", "valid Bearer session is required", requestID)
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return id, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func pageParams(w http.ResponseWriter, r *http.Request, requestID string) (int, string, bool) {
|
||||||
|
limit := 50
|
||||||
|
if values, exists := r.URL.Query()["limit"]; exists {
|
||||||
|
if len(values) != 1 || values[0] == "" {
|
||||||
|
writeError(w, 400, "invalid_request", "invalid limit", requestID)
|
||||||
|
return 0, "", false
|
||||||
|
}
|
||||||
|
parsed, err := strconv.Atoi(values[0])
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, 400, "invalid_request", "limit must be between 1 and 100", requestID)
|
||||||
|
return 0, "", false
|
||||||
|
}
|
||||||
|
limit = parsed
|
||||||
|
}
|
||||||
|
var cursor string
|
||||||
|
if values, exists := r.URL.Query()["cursor"]; exists {
|
||||||
|
if len(values) != 1 || values[0] == "" {
|
||||||
|
writeError(w, 400, "invalid_request", "invalid cursor", requestID)
|
||||||
|
return 0, "", false
|
||||||
|
}
|
||||||
|
cursor = values[0]
|
||||||
|
}
|
||||||
|
return limit, cursor, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func healthHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
requestID := newRequestID()
|
||||||
|
w.Header().Set("X-Request-Id", requestID)
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, 200, healthResponse{"ok"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func readyHandler(health *services.HealthService) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
requestID := newRequestID()
|
||||||
|
w.Header().Set("X-Request-Id", requestID)
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err := health.Ready(ctx); err != nil {
|
||||||
|
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, 200, healthResponse{"ok"})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRouter(health *services.HealthService, users *services.UserService, sessions *services.SessionService, chats *services.ChatService, messages *services.MessageService) http.Handler {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("/health/live", healthHandler)
|
||||||
|
mux.HandleFunc("/health/ready", readyHandler(health))
|
||||||
|
mux.Handle("/api/v1/users", createUserHandler(users))
|
||||||
|
mux.Handle("/api/v1/auth/sessions", sessionHandler(sessions))
|
||||||
|
mux.Handle("/api/v1/auth/sessions/current", authRequired(sessions, logoutHandler(sessions)))
|
||||||
|
mux.Handle("/api/v1/users/me", authRequired(sessions, currentUserHandler(users)))
|
||||||
|
mux.Handle("/api/v1/chats", authRequired(sessions, chatCollectionHandler(chats)))
|
||||||
|
mux.Handle("/api/v1/chats/", authRequired(sessions, chatSubresourceHandler(chats, messages)))
|
||||||
|
return mux
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"messenger/src/backend/services"
|
||||||
|
)
|
||||||
|
|
||||||
|
type createMessageRequest struct {
|
||||||
|
Text string `json:"text"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func messageChatID(path string) (string, bool) {
|
||||||
|
const prefix = "/api/v1/chats/"
|
||||||
|
const suffix = "/messages"
|
||||||
|
if !strings.HasPrefix(path, prefix) || !strings.HasSuffix(path, suffix) {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
chatID := strings.TrimSuffix(strings.TrimPrefix(path, prefix), suffix)
|
||||||
|
if chatID == "" || strings.Contains(chatID, "/") {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return chatID, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func createMessageHandler(chats *services.ChatService, messages *services.MessageService) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
requestID := newRequestID()
|
||||||
|
w.Header().Set("X-Request-Id", requestID)
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
userID, ok := requestUserID(w, r, requestID)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
chatID, ok := messageChatID(r.URL.Path)
|
||||||
|
if !ok {
|
||||||
|
writeError(w, 400, "invalid_request", "invalid chat id", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err := uuid.Parse(chatID); err != nil {
|
||||||
|
writeError(w, 400, "invalid_request", "invalid chat id", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
chat, err := chats.Get(r.Context(), userID, chatID)
|
||||||
|
if err != nil {
|
||||||
|
writeServiceError(w, err, requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {
|
||||||
|
writeError(w, 415, "unsupported_media_type", "content type must be application/json", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var request createMessageRequest
|
||||||
|
if err := decodeJSONBody(r, &request); err != nil {
|
||||||
|
writeError(w, 400, "invalid_request", "invalid JSON body", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
message, err := messages.Create(r.Context(), userID, chat, request.Text)
|
||||||
|
if err != nil {
|
||||||
|
writeServiceError(w, err, requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, 201, message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func listMessagesHandler(chats *services.ChatService, messages *services.MessageService) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
requestID := newRequestID()
|
||||||
|
w.Header().Set("X-Request-Id", requestID)
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
userID, ok := requestUserID(w, r, requestID)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
chatID, ok := messageChatID(r.URL.Path)
|
||||||
|
if !ok {
|
||||||
|
writeError(w, 400, "invalid_request", "invalid chat id", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
chat, err := chats.Get(r.Context(), userID, chatID)
|
||||||
|
if err != nil {
|
||||||
|
writeServiceError(w, err, requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
limit, cursor, ok := pageParams(w, r, requestID)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page, err := messages.List(r.Context(), userID, chat, limit, cursor)
|
||||||
|
if err != nil {
|
||||||
|
writeServiceError(w, err, requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, 200, page)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"messenger/src/backend/services"
|
||||||
|
)
|
||||||
|
|
||||||
|
type authenticatedUserKey struct{}
|
||||||
|
|
||||||
|
func currentUserID(r *http.Request) string {
|
||||||
|
id, _ := r.Context().Value(authenticatedUserKey{}).(string)
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
func authRequired(sessions *services.SessionService, next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
authorization := r.Header.Get("Authorization")
|
||||||
|
if !strings.HasPrefix(authorization, "Bearer ") || strings.TrimSpace(strings.TrimPrefix(authorization, "Bearer ")) == "" {
|
||||||
|
unauthorized(w, "Bearer", newRequestID())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user, err := sessions.User(r.Context(), strings.TrimPrefix(authorization, "Bearer "))
|
||||||
|
if errors.Is(err, services.ErrInvalidSession) {
|
||||||
|
unauthorized(w, "Bearer", newRequestID())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
requestID := newRequestID()
|
||||||
|
w.Header().Set("X-Request-Id", requestID)
|
||||||
|
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), authenticatedUserKey{}, user.ID)))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func unauthorized(w http.ResponseWriter, scheme, requestID string) {
|
||||||
|
w.Header().Set("X-Request-Id", requestID)
|
||||||
|
if scheme == "Basic" {
|
||||||
|
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||||
|
} else {
|
||||||
|
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||||
|
}
|
||||||
|
writeError(w, 401, "unauthorized", "invalid credentials", requestID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sessionHandler(sessions *services.SessionService) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
requestID := newRequestID()
|
||||||
|
w.Header().Set("X-Request-Id", requestID)
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
username, password, ok := r.BasicAuth()
|
||||||
|
if !ok || r.ContentLength > 0 {
|
||||||
|
unauthorized(w, "Basic", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user, token, expires, valid, err := sessions.Login(r.Context(), username, password)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !valid {
|
||||||
|
unauthorized(w, "Basic", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, 201, struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
TokenType string `json:"token_type"`
|
||||||
|
ExpiresAt time.Time `json:"expires_at"`
|
||||||
|
User any `json:"user"`
|
||||||
|
}{token, "Bearer", expires, user})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func logoutHandler(sessions *services.SessionService) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
requestID := newRequestID()
|
||||||
|
w.Header().Set("X-Request-Id", requestID)
|
||||||
|
if r.Method != http.MethodDelete {
|
||||||
|
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||||
|
if err := sessions.Revoke(r.Context(), token); err != nil {
|
||||||
|
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(204)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"messenger/src/backend/services"
|
||||||
|
)
|
||||||
|
|
||||||
|
type createUserRequest struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
DisplayName string `json:"display_name"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeJSONBody(r *http.Request, destination any) error {
|
||||||
|
decoder := json.NewDecoder(r.Body)
|
||||||
|
decoder.DisallowUnknownFields()
|
||||||
|
if err := decoder.Decode(destination); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var extra any
|
||||||
|
if err := decoder.Decode(&extra); err != io.EOF {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return fmt.Errorf("more than one JSON value")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func createUserHandler(users *services.UserService) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
requestID := newRequestID()
|
||||||
|
w.Header().Set("X-Request-Id", requestID)
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {
|
||||||
|
writeError(w, 415, "unsupported_media_type", "content type must be application/json", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var request createUserRequest
|
||||||
|
if err := decodeJSONBody(r, &request); err != nil {
|
||||||
|
writeError(w, 400, "invalid_request", "invalid JSON body", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user, err := users.Create(r.Context(), request.Username, request.DisplayName, request.Password)
|
||||||
|
if err != nil {
|
||||||
|
writeServiceError(w, err, requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, 201, user)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func currentUserHandler(users *services.UserService) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
requestID := newRequestID()
|
||||||
|
w.Header().Set("X-Request-Id", requestID)
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
userID, ok := requestUserID(w, r, requestID)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user, err := users.Get(r.Context(), userID)
|
||||||
|
if err != nil {
|
||||||
|
writeServiceError(w, err, requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, 200, user)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"log"
|
||||||
|
"messenger/src/backend/handlers"
|
||||||
|
"messenger/src/backend/repositories"
|
||||||
|
"messenger/src/backend/services"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func serverAddress() string {
|
||||||
|
host := os.Getenv("APP_HOST")
|
||||||
|
if host == "" {
|
||||||
|
host = "0.0.0.0"
|
||||||
|
}
|
||||||
|
|
||||||
|
port := os.Getenv("APP_PORT")
|
||||||
|
if port == "" {
|
||||||
|
port = "8080"
|
||||||
|
}
|
||||||
|
|
||||||
|
return net.JoinHostPort(host, port)
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
if len(os.Args) > 1 {
|
||||||
|
if len(os.Args) == 2 && os.Args[1] == "healthcheck" {
|
||||||
|
client := http.Client{Timeout: 2 * time.Second}
|
||||||
|
response, err := client.Get("http://127.0.0.1:8080/health/ready")
|
||||||
|
if err != nil {
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
response.Body.Close()
|
||||||
|
if response.StatusCode != http.StatusOK {
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(os.Args) != 3 || os.Args[1] != "migrate" || (os.Args[2] != "up" && os.Args[2] != "down") {
|
||||||
|
log.Fatal("usage: messenger migrate up|down")
|
||||||
|
}
|
||||||
|
url, err := repositories.DatabaseURL()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
if err = repositories.RunMigrations(url, os.Args[2]); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
log.Printf("migration %s complete", os.Args[2])
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||||
|
db, err := repositories.OpenDatabase(ctx)
|
||||||
|
cancel()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("database initialization failed: %v", err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
userStore := repositories.NewUserStore(db)
|
||||||
|
chatStore := repositories.NewChatStore(db)
|
||||||
|
messageStore := repositories.NewMessageStore(db)
|
||||||
|
ttl, err := services.SessionTTL()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
userService := services.NewUserService(userStore)
|
||||||
|
sessionService := services.NewSessionService(userService, repositories.NewSessionStore(db), ttl)
|
||||||
|
chatService := services.NewChatService(chatStore)
|
||||||
|
messageService := services.NewMessageService(messageStore)
|
||||||
|
mux := handlers.NewRouter(services.NewHealthService(repositories.NewHealthStore(db)), userService, sessionService, chatService, messageService)
|
||||||
|
|
||||||
|
server := &http.Server{
|
||||||
|
Addr: serverAddress(),
|
||||||
|
Handler: mux,
|
||||||
|
}
|
||||||
|
|
||||||
|
shutdownContext, stop := signal.NotifyContext(
|
||||||
|
context.Background(),
|
||||||
|
os.Interrupt,
|
||||||
|
syscall.SIGTERM,
|
||||||
|
)
|
||||||
|
defer stop()
|
||||||
|
|
||||||
|
serverErrors := make(chan error, 1)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
log.Printf("server is listening on %s", server.Addr)
|
||||||
|
|
||||||
|
if err := server.ListenAndServe(); err != nil &&
|
||||||
|
!errors.Is(err, http.ErrServerClosed) {
|
||||||
|
serverErrors <- err
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case err := <-serverErrors:
|
||||||
|
log.Printf("server error: %v", err)
|
||||||
|
|
||||||
|
case <-shutdownContext.Done():
|
||||||
|
log.Printf("shutdown signal received")
|
||||||
|
|
||||||
|
shutdownDeadline, cancel := context.WithTimeout(
|
||||||
|
context.Background(),
|
||||||
|
10*time.Second,
|
||||||
|
)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
if err := server.Shutdown(shutdownDeadline); err != nil {
|
||||||
|
log.Printf("graceful shutdown failed: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("server stopped gracefully")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package main
|
package repositories
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -16,17 +16,17 @@ type Chat struct {
|
|||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type chatStore struct {
|
type ChatStore struct {
|
||||||
db *pgxpool.Pool
|
db *pgxpool.Pool
|
||||||
}
|
}
|
||||||
|
|
||||||
func newChatStore(db *pgxpool.Pool) *chatStore {
|
func NewChatStore(db *pgxpool.Pool) *ChatStore {
|
||||||
return &chatStore{db: db}
|
return &ChatStore{db: db}
|
||||||
}
|
}
|
||||||
|
|
||||||
var errUnknownMember = errors.New("unknown member")
|
var ErrUnknownMember = errors.New("unknown member")
|
||||||
|
|
||||||
func (s *chatStore) create(ctx context.Context, title string, memberIDs []string) (Chat, error) {
|
func (s *ChatStore) Create(ctx context.Context, title string, memberIDs []string) (Chat, error) {
|
||||||
membersCopy := append([]string(nil), memberIDs...)
|
membersCopy := append([]string(nil), memberIDs...)
|
||||||
chat := Chat{
|
chat := Chat{
|
||||||
ID: uuid.New().String(),
|
ID: uuid.New().String(),
|
||||||
@@ -46,7 +46,7 @@ func (s *chatStore) create(ctx context.Context, title string, memberIDs []string
|
|||||||
return Chat{}, err
|
return Chat{}, err
|
||||||
}
|
}
|
||||||
if !exists {
|
if !exists {
|
||||||
return Chat{}, errUnknownMember
|
return Chat{}, ErrUnknownMember
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if _, err = tx.Exec(ctx, "INSERT INTO chats(id,title,created_at) VALUES($1,$2,$3)", chat.ID, title, chat.CreatedAt); err != nil {
|
if _, err = tx.Exec(ctx, "INSERT INTO chats(id,title,created_at) VALUES($1,$2,$3)", chat.ID, title, chat.CreatedAt); err != nil {
|
||||||
@@ -63,7 +63,7 @@ func (s *chatStore) create(ctx context.Context, title string, memberIDs []string
|
|||||||
return chat, nil
|
return chat, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *chatStore) getByID(ctx context.Context, id string) (Chat, error) {
|
func (s *ChatStore) GetByID(ctx context.Context, id string) (Chat, error) {
|
||||||
var chat Chat
|
var chat Chat
|
||||||
err := s.db.QueryRow(ctx, "SELECT id,title,created_at FROM chats WHERE id=$1", id).Scan(&chat.ID, &chat.Title, &chat.CreatedAt)
|
err := s.db.QueryRow(ctx, "SELECT id,title,created_at FROM chats WHERE id=$1", id).Scan(&chat.ID, &chat.Title, &chat.CreatedAt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -85,17 +85,7 @@ func (s *chatStore) getByID(ctx context.Context, id string) (Chat, error) {
|
|||||||
return chat, rows.Err()
|
return chat, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *chatStore) isMember(chat Chat, userID string) bool {
|
func (s *ChatStore) ListPageForUser(ctx context.Context, userID string, cursor *ChatCursor, limit int) ([]Chat, bool, error) {
|
||||||
for _, memberID := range chat.MemberIDs {
|
|
||||||
if memberID == userID {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *chatStore) listPageForUser(ctx context.Context, userID string, cursor *chatCursor, limit int) ([]Chat, bool, error) {
|
|
||||||
afterTime := time.Time{}
|
afterTime := time.Time{}
|
||||||
afterID := "00000000-0000-0000-0000-000000000000"
|
afterID := "00000000-0000-0000-0000-000000000000"
|
||||||
if cursor != nil {
|
if cursor != nil {
|
||||||
@@ -123,7 +113,7 @@ func (s *chatStore) listPageForUser(ctx context.Context, userID string, cursor *
|
|||||||
chats = chats[:limit]
|
chats = chats[:limit]
|
||||||
}
|
}
|
||||||
for i := range chats {
|
for i := range chats {
|
||||||
chat, err := s.getByID(ctx, chats[i].ID)
|
chat, err := s.GetByID(ctx, chats[i].ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, false, err
|
return nil, false, err
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package repositories
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type ChatCursor struct {
|
||||||
|
UserID string `json:"user_id"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
ChatID string `json:"chat_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type MessageCursor struct {
|
||||||
|
ChatID string `json:"chat_id"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
MessageID string `json:"message_id"`
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package main
|
package repositories
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -12,7 +12,6 @@ import (
|
|||||||
"github.com/golang-migrate/migrate/v4"
|
"github.com/golang-migrate/migrate/v4"
|
||||||
pgxmigrate "github.com/golang-migrate/migrate/v4/database/pgx/v5"
|
pgxmigrate "github.com/golang-migrate/migrate/v4/database/pgx/v5"
|
||||||
"github.com/golang-migrate/migrate/v4/source/iofs"
|
"github.com/golang-migrate/migrate/v4/source/iofs"
|
||||||
"github.com/jackc/pgx/v5/pgconn"
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
_ "github.com/jackc/pgx/v5/stdlib"
|
_ "github.com/jackc/pgx/v5/stdlib"
|
||||||
)
|
)
|
||||||
@@ -20,7 +19,7 @@ import (
|
|||||||
//go:embed migrations/*.sql
|
//go:embed migrations/*.sql
|
||||||
var migrationFiles embed.FS
|
var migrationFiles embed.FS
|
||||||
|
|
||||||
func databaseURL() (string, error) {
|
func DatabaseURL() (string, error) {
|
||||||
if path := os.Getenv("DATABASE_URL_FILE"); path != "" {
|
if path := os.Getenv("DATABASE_URL_FILE"); path != "" {
|
||||||
data, err := os.ReadFile(path)
|
data, err := os.ReadFile(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -34,8 +33,8 @@ func databaseURL() (string, error) {
|
|||||||
return "", errors.New("DATABASE_URL_FILE or DATABASE_URL is required")
|
return "", errors.New("DATABASE_URL_FILE or DATABASE_URL is required")
|
||||||
}
|
}
|
||||||
|
|
||||||
func openDatabase(ctx context.Context) (*pgxpool.Pool, error) {
|
func OpenDatabase(ctx context.Context) (*pgxpool.Pool, error) {
|
||||||
url, err := databaseURL()
|
url, err := DatabaseURL()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -53,16 +52,16 @@ func openDatabase(ctx context.Context) (*pgxpool.Pool, error) {
|
|||||||
db.Close()
|
db.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if err = runMigrations(url, "up"); err != nil {
|
if err = RunMigrations(url, "up"); err != nil {
|
||||||
db.Close()
|
db.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return db, nil
|
return db, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// runMigrations uses versioned up/down SQL embedded in the API binary.
|
// RunMigrations uses versioned up/down SQL embedded in the API binary.
|
||||||
// "down" rolls back exactly one version and is an explicit operator command.
|
// "down" rolls back exactly one version and is an explicit operator command.
|
||||||
func runMigrations(url, direction string) error {
|
func RunMigrations(url, direction string) error {
|
||||||
source, err := iofs.New(migrationFiles, "migrations")
|
source, err := iofs.New(migrationFiles, "migrations")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -92,8 +91,3 @@ func runMigrations(url, direction string) error {
|
|||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func uniqueViolation(err error) bool {
|
|
||||||
var pgerr *pgconn.PgError
|
|
||||||
return errors.As(err, &pgerr) && pgerr.Code == "23505"
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package repositories
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NotFound(err error) bool {
|
||||||
|
return errors.Is(err, pgx.ErrNoRows)
|
||||||
|
}
|
||||||
|
|
||||||
|
func CheckViolation(err error) bool {
|
||||||
|
var pgerr *pgconn.PgError
|
||||||
|
return errors.As(err, &pgerr) && pgerr.Code == "23514"
|
||||||
|
}
|
||||||
|
|
||||||
|
func UniqueViolation(err error) bool {
|
||||||
|
var pgerr *pgconn.PgError
|
||||||
|
return errors.As(err, &pgerr) && pgerr.Code == "23505"
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package repositories
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
type HealthStore struct {
|
||||||
|
db *pgxpool.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHealthStore(db *pgxpool.Pool) *HealthStore {
|
||||||
|
return &HealthStore{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *HealthStore) Ping(ctx context.Context) error {
|
||||||
|
return s.db.Ping(ctx)
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package main
|
package repositories
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -16,15 +16,15 @@ type Message struct {
|
|||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type messageStore struct {
|
type MessageStore struct {
|
||||||
db *pgxpool.Pool
|
db *pgxpool.Pool
|
||||||
}
|
}
|
||||||
|
|
||||||
func newMessageStore(db *pgxpool.Pool) *messageStore {
|
func NewMessageStore(db *pgxpool.Pool) *MessageStore {
|
||||||
return &messageStore{db: db}
|
return &MessageStore{db: db}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *messageStore) create(
|
func (s *MessageStore) Create(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
chatID string,
|
chatID string,
|
||||||
senderID string,
|
senderID string,
|
||||||
@@ -42,23 +42,10 @@ func (s *messageStore) create(
|
|||||||
return message, err
|
return message, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func messageLess(left Message, right Message) bool {
|
func (s *MessageStore) ListPageByChat(
|
||||||
if left.CreatedAt.Equal(right.CreatedAt) {
|
|
||||||
return left.ID < right.ID
|
|
||||||
}
|
|
||||||
|
|
||||||
return left.CreatedAt.Before(right.CreatedAt)
|
|
||||||
}
|
|
||||||
|
|
||||||
func messageAfterCursor(message Message, cursor messageCursor) bool {
|
|
||||||
return message.CreatedAt.After(cursor.CreatedAt) ||
|
|
||||||
(message.CreatedAt.Equal(cursor.CreatedAt) && message.ID > cursor.MessageID)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *messageStore) listPageByChat(
|
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
chatID string,
|
chatID string,
|
||||||
cursor *messageCursor,
|
cursor *MessageCursor,
|
||||||
limit int,
|
limit int,
|
||||||
) ([]Message, bool, error) {
|
) ([]Message, bool, error) {
|
||||||
afterTime := time.Time{}
|
afterTime := time.Time{}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package repositories
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SessionStore struct {
|
||||||
|
db *pgxpool.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSessionStore(db *pgxpool.Pool) *SessionStore {
|
||||||
|
return &SessionStore{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SessionStore) Create(ctx context.Context, tokenHash []byte, userID string, expires time.Time) error {
|
||||||
|
_, err := s.db.Exec(ctx, "INSERT INTO sessions(token_hash,user_id,expires_at) VALUES($1,$2,$3)", tokenHash, userID, expires)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SessionStore) User(ctx context.Context, tokenHash []byte) (User, error) {
|
||||||
|
var user User
|
||||||
|
err := s.db.QueryRow(ctx, `SELECT u.id,u.username,u.display_name,u.created_at FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.token_hash=$1 AND s.expires_at>now()`, tokenHash).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
||||||
|
return user, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SessionStore) Revoke(ctx context.Context, tokenHash []byte) error {
|
||||||
|
_, err := s.db.Exec(ctx, "DELETE FROM sessions WHERE token_hash=$1", tokenHash)
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package repositories
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
type User struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
DisplayName string `json:"display_name"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UserStore struct {
|
||||||
|
db *pgxpool.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUserStore(db *pgxpool.Pool) *UserStore {
|
||||||
|
return &UserStore{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *UserStore) Create(ctx context.Context, username, displayName string, passwordHash []byte) (User, error) {
|
||||||
|
user := User{
|
||||||
|
ID: uuid.New().String(),
|
||||||
|
Username: username,
|
||||||
|
DisplayName: displayName,
|
||||||
|
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := s.db.Exec(ctx, "INSERT INTO users(id,username,display_name,password_hash,created_at) VALUES($1,$2,$3,$4,$5)", user.ID, user.Username, user.DisplayName, passwordHash, user.CreatedAt)
|
||||||
|
return user, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *UserStore) GetByID(ctx context.Context, id string) (User, error) {
|
||||||
|
var user User
|
||||||
|
err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at FROM users WHERE id=$1", id).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
||||||
|
return user, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *UserStore) GetCredentials(ctx context.Context, username string) (User, []byte, error) {
|
||||||
|
var user User
|
||||||
|
var packedHash []byte
|
||||||
|
err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at,password_hash FROM users WHERE username=$1", username).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &packedHash)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return User{}, nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return User{}, nil, err
|
||||||
|
}
|
||||||
|
return user, packedHash, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"messenger/src/backend/repositories"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ChatPage struct {
|
||||||
|
Items []repositories.Chat `json:"items"`
|
||||||
|
NextCursor *string `json:"next_cursor"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ChatService struct {
|
||||||
|
chats *repositories.ChatStore
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewChatService(chats *repositories.ChatStore) *ChatService {
|
||||||
|
return &ChatService{chats: chats}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ChatHasMember(chat repositories.Chat, userID string) bool {
|
||||||
|
for _, memberID := range chat.MemberIDs {
|
||||||
|
if memberID == userID {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ChatService) Create(ctx context.Context, currentUserID, title string, memberIDs []string) (repositories.Chat, error) {
|
||||||
|
if strings.TrimSpace(title) == "" {
|
||||||
|
return repositories.Chat{}, InvalidInput{"title must not be blank"}
|
||||||
|
}
|
||||||
|
if utf8.RuneCountInString(title) > 100 {
|
||||||
|
return repositories.Chat{}, InvalidInput{"title is too long"}
|
||||||
|
}
|
||||||
|
if len(memberIDs) == 0 || len(memberIDs) > 100 {
|
||||||
|
return repositories.Chat{}, InvalidInput{"member_ids must contain from 1 to 100 users"}
|
||||||
|
}
|
||||||
|
seen := make(map[string]struct{}, len(memberIDs))
|
||||||
|
for _, memberID := range memberIDs {
|
||||||
|
if _, err := uuid.Parse(memberID); err != nil {
|
||||||
|
return repositories.Chat{}, InvalidInput{"member_ids must contain valid UUIDs"}
|
||||||
|
}
|
||||||
|
if _, exists := seen[memberID]; exists {
|
||||||
|
return repositories.Chat{}, InvalidInput{"member_ids must not contain duplicates"}
|
||||||
|
}
|
||||||
|
seen[memberID] = struct{}{}
|
||||||
|
}
|
||||||
|
if _, exists := seen[currentUserID]; !exists {
|
||||||
|
return repositories.Chat{}, InvalidInput{"current user must be a chat member"}
|
||||||
|
}
|
||||||
|
chat, err := s.chats.Create(ctx, title, memberIDs)
|
||||||
|
if errors.Is(err, repositories.ErrUnknownMember) {
|
||||||
|
return repositories.Chat{}, InvalidInput{"all members must be existing users"}
|
||||||
|
}
|
||||||
|
return chat, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ChatService) Get(ctx context.Context, currentUserID, chatID string) (repositories.Chat, error) {
|
||||||
|
chat, err := s.chats.GetByID(ctx, chatID)
|
||||||
|
if repositories.NotFound(err) {
|
||||||
|
return repositories.Chat{}, ErrChatNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return repositories.Chat{}, err
|
||||||
|
}
|
||||||
|
if !ChatHasMember(chat, currentUserID) {
|
||||||
|
return repositories.Chat{}, ErrChatNotFound
|
||||||
|
}
|
||||||
|
return chat, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func EncodeChatCursor(cursor repositories.ChatCursor) (string, error) {
|
||||||
|
data, err := json.Marshal(cursor)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return base64.RawURLEncoding.EncodeToString(data), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func DecodeChatCursor(value string) (repositories.ChatCursor, error) {
|
||||||
|
data, err := base64.RawURLEncoding.DecodeString(value)
|
||||||
|
if err != nil {
|
||||||
|
return repositories.ChatCursor{}, err
|
||||||
|
}
|
||||||
|
var cursor repositories.ChatCursor
|
||||||
|
if err := json.Unmarshal(data, &cursor); err != nil {
|
||||||
|
return repositories.ChatCursor{}, err
|
||||||
|
}
|
||||||
|
if cursor.UserID == "" || cursor.ChatID == "" || cursor.CreatedAt.IsZero() {
|
||||||
|
return repositories.ChatCursor{}, strconv.ErrSyntax
|
||||||
|
}
|
||||||
|
return cursor, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ChatService) List(ctx context.Context, userID string, limit int, cursorToken string) (ChatPage, error) {
|
||||||
|
if limit < 1 || limit > 100 {
|
||||||
|
return ChatPage{}, InvalidInput{"limit must be between 1 and 100"}
|
||||||
|
}
|
||||||
|
var cursor *repositories.ChatCursor
|
||||||
|
if cursorToken != "" {
|
||||||
|
decoded, err := DecodeChatCursor(cursorToken)
|
||||||
|
if err != nil || decoded.UserID != userID {
|
||||||
|
return ChatPage{}, InvalidInput{"invalid cursor"}
|
||||||
|
}
|
||||||
|
cursor = &decoded
|
||||||
|
}
|
||||||
|
items, more, err := s.chats.ListPageForUser(ctx, userID, cursor, limit)
|
||||||
|
if err != nil {
|
||||||
|
return ChatPage{}, err
|
||||||
|
}
|
||||||
|
page := ChatPage{Items: items}
|
||||||
|
if page.Items == nil {
|
||||||
|
page.Items = []repositories.Chat{}
|
||||||
|
}
|
||||||
|
if more {
|
||||||
|
last := items[len(items)-1]
|
||||||
|
next, err := EncodeChatCursor(repositories.ChatCursor{UserID: userID, CreatedAt: last.CreatedAt, ChatID: last.ID})
|
||||||
|
if err != nil {
|
||||||
|
return ChatPage{}, err
|
||||||
|
}
|
||||||
|
page.NextCursor = &next
|
||||||
|
}
|
||||||
|
return page, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrConflict = errors.New("conflict")
|
||||||
|
ErrUnknownUser = errors.New("unknown user")
|
||||||
|
ErrChatNotFound = errors.New("chat not found")
|
||||||
|
ErrInvalidSession = errors.New("invalid session")
|
||||||
|
)
|
||||||
|
|
||||||
|
type InvalidInput struct {
|
||||||
|
Message string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e InvalidInput) Error() string { return e.Message }
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"messenger/src/backend/repositories"
|
||||||
|
)
|
||||||
|
|
||||||
|
type HealthService struct {
|
||||||
|
health *repositories.HealthStore
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHealthService(health *repositories.HealthStore) *HealthService {
|
||||||
|
return &HealthService{health: health}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *HealthService) Ready(ctx context.Context) error {
|
||||||
|
return s.health.Ping(ctx)
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"messenger/src/backend/repositories"
|
||||||
|
)
|
||||||
|
|
||||||
|
type MessagePage struct {
|
||||||
|
Items []repositories.Message `json:"items"`
|
||||||
|
NextCursor *string `json:"next_cursor"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type MessageService struct {
|
||||||
|
messages *repositories.MessageStore
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMessageService(messages *repositories.MessageStore) *MessageService {
|
||||||
|
return &MessageService{messages: messages}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *MessageService) Create(ctx context.Context, userID string, chat repositories.Chat, text string) (repositories.Message, error) {
|
||||||
|
if !ChatHasMember(chat, userID) {
|
||||||
|
return repositories.Message{}, ErrChatNotFound
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(text) == "" {
|
||||||
|
return repositories.Message{}, InvalidInput{"text must not be blank"}
|
||||||
|
}
|
||||||
|
if utf8.RuneCountInString(text) > 4000 {
|
||||||
|
return repositories.Message{}, InvalidInput{"text is too long"}
|
||||||
|
}
|
||||||
|
return s.messages.Create(ctx, chat.ID, userID, text)
|
||||||
|
}
|
||||||
|
|
||||||
|
func MessageLess(left, right repositories.Message) bool {
|
||||||
|
if left.CreatedAt.Equal(right.CreatedAt) {
|
||||||
|
return left.ID < right.ID
|
||||||
|
}
|
||||||
|
return left.CreatedAt.Before(right.CreatedAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
func MessageAfterCursor(message repositories.Message, cursor repositories.MessageCursor) bool {
|
||||||
|
return message.CreatedAt.After(cursor.CreatedAt) ||
|
||||||
|
(message.CreatedAt.Equal(cursor.CreatedAt) && message.ID > cursor.MessageID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func EncodeMessageCursor(cursor repositories.MessageCursor) (string, error) {
|
||||||
|
data, err := json.Marshal(cursor)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return base64.RawURLEncoding.EncodeToString(data), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func DecodeMessageCursor(value string) (repositories.MessageCursor, error) {
|
||||||
|
data, err := base64.RawURLEncoding.DecodeString(value)
|
||||||
|
if err != nil {
|
||||||
|
return repositories.MessageCursor{}, err
|
||||||
|
}
|
||||||
|
var cursor repositories.MessageCursor
|
||||||
|
if err := json.Unmarshal(data, &cursor); err != nil {
|
||||||
|
return repositories.MessageCursor{}, err
|
||||||
|
}
|
||||||
|
if cursor.ChatID == "" || cursor.MessageID == "" || cursor.CreatedAt.IsZero() {
|
||||||
|
return repositories.MessageCursor{}, strconv.ErrSyntax
|
||||||
|
}
|
||||||
|
return cursor, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *MessageService) List(ctx context.Context, userID string, chat repositories.Chat, limit int, cursorToken string) (MessagePage, error) {
|
||||||
|
if !ChatHasMember(chat, userID) {
|
||||||
|
return MessagePage{}, ErrChatNotFound
|
||||||
|
}
|
||||||
|
if limit < 1 || limit > 100 {
|
||||||
|
return MessagePage{}, InvalidInput{"limit must be between 1 and 100"}
|
||||||
|
}
|
||||||
|
var cursor *repositories.MessageCursor
|
||||||
|
if cursorToken != "" {
|
||||||
|
decoded, err := DecodeMessageCursor(cursorToken)
|
||||||
|
if err != nil || decoded.ChatID != chat.ID {
|
||||||
|
return MessagePage{}, InvalidInput{"invalid cursor"}
|
||||||
|
}
|
||||||
|
cursor = &decoded
|
||||||
|
}
|
||||||
|
items, more, err := s.messages.ListPageByChat(ctx, chat.ID, cursor, limit)
|
||||||
|
if err != nil {
|
||||||
|
return MessagePage{}, err
|
||||||
|
}
|
||||||
|
page := MessagePage{Items: items}
|
||||||
|
if page.Items == nil {
|
||||||
|
page.Items = []repositories.Message{}
|
||||||
|
}
|
||||||
|
if more {
|
||||||
|
last := items[len(items)-1]
|
||||||
|
next, err := EncodeMessageCursor(repositories.MessageCursor{ChatID: chat.ID, CreatedAt: last.CreatedAt, MessageID: last.ID})
|
||||||
|
if err != nil {
|
||||||
|
return MessagePage{}, err
|
||||||
|
}
|
||||||
|
page.NextCursor = &next
|
||||||
|
}
|
||||||
|
return page, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/subtle"
|
||||||
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/argon2"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
argonMemory uint32 = 64 * 1024
|
||||||
|
argonIterations uint32 = 3
|
||||||
|
argonParallelism uint8 = 2
|
||||||
|
passwordSaltSize = 16
|
||||||
|
passwordHashSize = 32
|
||||||
|
)
|
||||||
|
|
||||||
|
// HashPassword stores the salt and Argon2id parameters in one PHC-encoded value.
|
||||||
|
func HashPassword(password string) ([]byte, error) {
|
||||||
|
salt := make([]byte, passwordSaltSize)
|
||||||
|
if _, err := rand.Read(salt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
hash := argon2.IDKey([]byte(password), salt, argonIterations, argonMemory, argonParallelism, passwordHashSize)
|
||||||
|
encoded := fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||||
|
argon2.Version, argonMemory, argonIterations, argonParallelism,
|
||||||
|
base64.RawStdEncoding.EncodeToString(salt),
|
||||||
|
base64.RawStdEncoding.EncodeToString(hash),
|
||||||
|
)
|
||||||
|
return []byte(encoded), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func VerifyPassword(password string, encoded []byte) (bool, error) {
|
||||||
|
parts := strings.Split(string(encoded), "$")
|
||||||
|
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" || parts[2] != fmt.Sprintf("v=%d", argon2.Version) {
|
||||||
|
return false, errors.New("invalid password hash format")
|
||||||
|
}
|
||||||
|
var memory, iterations uint32
|
||||||
|
var parallelism uint8
|
||||||
|
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &iterations, ¶llelism); err != nil ||
|
||||||
|
fmt.Sprintf("m=%d,t=%d,p=%d", memory, iterations, parallelism) != parts[3] ||
|
||||||
|
memory < 8*1024 || memory > 128*1024 || iterations < 1 || iterations > 10 || parallelism < 1 || parallelism > 8 {
|
||||||
|
return false, errors.New("invalid password hash parameters")
|
||||||
|
}
|
||||||
|
salt, err := base64.RawStdEncoding.Strict().DecodeString(parts[4])
|
||||||
|
if err != nil || len(salt) != passwordSaltSize {
|
||||||
|
return false, errors.New("invalid password salt")
|
||||||
|
}
|
||||||
|
expected, err := base64.RawStdEncoding.Strict().DecodeString(parts[5])
|
||||||
|
if err != nil || len(expected) != passwordHashSize {
|
||||||
|
return false, errors.New("invalid password hash")
|
||||||
|
}
|
||||||
|
actual := argon2.IDKey([]byte(password), salt, iterations, memory, parallelism, passwordHashSize)
|
||||||
|
return subtle.ConstantTimeCompare(expected, actual) == 1, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"messenger/src/backend/repositories"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SessionService struct {
|
||||||
|
users *UserService
|
||||||
|
sessions *repositories.SessionStore
|
||||||
|
ttl time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func SessionTTL() (time.Duration, error) {
|
||||||
|
value := os.Getenv("SESSION_TTL_SECONDS")
|
||||||
|
if value == "" {
|
||||||
|
return time.Hour, nil
|
||||||
|
}
|
||||||
|
seconds, err := strconv.Atoi(value)
|
||||||
|
if err != nil || seconds < 1 {
|
||||||
|
return 0, errors.New("invalid SESSION_TTL_SECONDS")
|
||||||
|
}
|
||||||
|
return time.Duration(seconds) * time.Second, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSessionService(users *UserService, sessions *repositories.SessionStore, ttl time.Duration) *SessionService {
|
||||||
|
return &SessionService{users: users, sessions: sessions, ttl: ttl}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SessionService) Login(ctx context.Context, username, password string) (repositories.User, string, time.Time, bool, error) {
|
||||||
|
user, valid, err := s.users.Authenticate(ctx, username, password)
|
||||||
|
if err != nil || !valid {
|
||||||
|
return repositories.User{}, "", time.Time{}, valid, err
|
||||||
|
}
|
||||||
|
token, expires, err := s.CreateForUser(ctx, user.ID)
|
||||||
|
if err != nil {
|
||||||
|
return repositories.User{}, "", time.Time{}, false, err
|
||||||
|
}
|
||||||
|
return user, token, expires, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SessionService) CreateForUser(ctx context.Context, userID string) (string, time.Time, error) {
|
||||||
|
raw := make([]byte, 32)
|
||||||
|
if _, err := rand.Read(raw); err != nil {
|
||||||
|
return "", time.Time{}, err
|
||||||
|
}
|
||||||
|
token := hex.EncodeToString(raw)
|
||||||
|
hash := sha256.Sum256([]byte(token))
|
||||||
|
expires := time.Now().UTC().Add(s.ttl).Truncate(time.Microsecond)
|
||||||
|
if err := s.sessions.Create(ctx, hash[:], userID, expires); err != nil {
|
||||||
|
return "", time.Time{}, err
|
||||||
|
}
|
||||||
|
return token, expires, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SessionService) User(ctx context.Context, token string) (repositories.User, error) {
|
||||||
|
hash := sha256.Sum256([]byte(token))
|
||||||
|
user, err := s.sessions.User(ctx, hash[:])
|
||||||
|
if repositories.NotFound(err) {
|
||||||
|
return repositories.User{}, ErrInvalidSession
|
||||||
|
}
|
||||||
|
return user, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SessionService) Revoke(ctx context.Context, token string) error {
|
||||||
|
hash := sha256.Sum256([]byte(token))
|
||||||
|
return s.sessions.Revoke(ctx, hash[:])
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"messenger/src/backend/repositories"
|
||||||
|
)
|
||||||
|
|
||||||
|
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||||
|
|
||||||
|
type UserService struct {
|
||||||
|
users *repositories.UserStore
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUserService(users *repositories.UserStore) *UserService {
|
||||||
|
return &UserService{users: users}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *UserService) Create(ctx context.Context, username, displayName, password string) (repositories.User, error) {
|
||||||
|
if !usernamePattern.MatchString(username) {
|
||||||
|
return repositories.User{}, InvalidInput{"username must contain 3-32 lowercase latin letters, digits or underscores"}
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(displayName) == "" {
|
||||||
|
return repositories.User{}, InvalidInput{"display_name must not be blank"}
|
||||||
|
}
|
||||||
|
if utf8.RuneCountInString(displayName) > 100 {
|
||||||
|
return repositories.User{}, InvalidInput{"display_name is too long"}
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(password) == "" || utf8.RuneCountInString(password) < 12 || utf8.RuneCountInString(password) > 128 {
|
||||||
|
return repositories.User{}, InvalidInput{"password must contain 12-128 characters"}
|
||||||
|
}
|
||||||
|
hash, err := HashPassword(password)
|
||||||
|
if err != nil {
|
||||||
|
return repositories.User{}, err
|
||||||
|
}
|
||||||
|
user, err := s.users.Create(ctx, username, displayName, hash)
|
||||||
|
if repositories.UniqueViolation(err) {
|
||||||
|
return repositories.User{}, ErrConflict
|
||||||
|
}
|
||||||
|
if repositories.CheckViolation(err) {
|
||||||
|
return repositories.User{}, InvalidInput{"invalid user fields"}
|
||||||
|
}
|
||||||
|
return user, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *UserService) Get(ctx context.Context, id string) (repositories.User, error) {
|
||||||
|
user, err := s.users.GetByID(ctx, id)
|
||||||
|
if repositories.NotFound(err) {
|
||||||
|
return repositories.User{}, ErrUnknownUser
|
||||||
|
}
|
||||||
|
return user, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *UserService) Authenticate(ctx context.Context, username, password string) (repositories.User, bool, error) {
|
||||||
|
if !usernamePattern.MatchString(username) || utf8.RuneCountInString(password) < 12 || utf8.RuneCountInString(password) > 128 {
|
||||||
|
return repositories.User{}, false, nil
|
||||||
|
}
|
||||||
|
user, packedHash, err := s.users.GetCredentials(ctx, username)
|
||||||
|
if err != nil || packedHash == nil {
|
||||||
|
return repositories.User{}, false, err
|
||||||
|
}
|
||||||
|
valid, err := VerifyPassword(password, packedHash)
|
||||||
|
if err != nil {
|
||||||
|
return repositories.User{}, false, err
|
||||||
|
}
|
||||||
|
return user, valid, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
package tests
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"messenger/src/backend/repositories"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strconv"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestConcurrentMessageCreation(t *testing.T) {
|
||||||
|
fixture := newTestFixture(t)
|
||||||
|
userStore, chatStore := fixture.users, fixture.chats
|
||||||
|
|
||||||
|
const clientsCount = 10
|
||||||
|
const messagesPerClient = 10
|
||||||
|
const expectedMessages = clientsCount * messagesPerClient
|
||||||
|
|
||||||
|
memberIDs := make([]string, 0, clientsCount)
|
||||||
|
users := make([]User, 0, clientsCount)
|
||||||
|
|
||||||
|
for i := range clientsCount {
|
||||||
|
user, created := createTestUser(t, userStore,
|
||||||
|
"user"+strconv.Itoa(i),
|
||||||
|
"Пользователь "+strconv.Itoa(i),
|
||||||
|
)
|
||||||
|
|
||||||
|
if !created {
|
||||||
|
t.Fatalf("failed to create test user %d", i)
|
||||||
|
}
|
||||||
|
|
||||||
|
users = append(users, user)
|
||||||
|
memberIDs = append(memberIDs, user.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
chat := createTestChat(t, chatStore,
|
||||||
|
"Конкурентный чат",
|
||||||
|
memberIDs,
|
||||||
|
)
|
||||||
|
|
||||||
|
server := httptest.NewServer(fixture.router)
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
client := server.Client()
|
||||||
|
tokens := make([]string, clientsCount)
|
||||||
|
for i, user := range users {
|
||||||
|
request := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
authorizeTestRequest(t, fixture, request, user.ID)
|
||||||
|
tokens[i] = request.Header.Get("Authorization")
|
||||||
|
}
|
||||||
|
|
||||||
|
var waitGroup sync.WaitGroup
|
||||||
|
messageIDs := make(chan string, expectedMessages)
|
||||||
|
errors := make(chan error, expectedMessages)
|
||||||
|
|
||||||
|
for clientIndex := range clientsCount {
|
||||||
|
waitGroup.Add(1)
|
||||||
|
|
||||||
|
go func(index int) {
|
||||||
|
defer waitGroup.Done()
|
||||||
|
|
||||||
|
for messageIndex := range messagesPerClient {
|
||||||
|
body := fmt.Appendf(nil,
|
||||||
|
`{"text":"client-%d message-%d"}`,
|
||||||
|
index,
|
||||||
|
messageIndex,
|
||||||
|
)
|
||||||
|
|
||||||
|
request, err := http.NewRequest(
|
||||||
|
http.MethodPost,
|
||||||
|
server.URL+"/api/v1/chats/"+chat.ID+"/messages",
|
||||||
|
bytes.NewReader(body),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
errors <- fmt.Errorf(
|
||||||
|
"client %d: create request: %w",
|
||||||
|
index,
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
request.Header.Set("Authorization", tokens[index])
|
||||||
|
|
||||||
|
response, err := client.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
errors <- fmt.Errorf(
|
||||||
|
"client %d: send request: %w",
|
||||||
|
index,
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
responseBody, readErr := io.ReadAll(response.Body)
|
||||||
|
response.Body.Close()
|
||||||
|
|
||||||
|
if readErr != nil {
|
||||||
|
errors <- fmt.Errorf(
|
||||||
|
"client %d: read response: %w",
|
||||||
|
index,
|
||||||
|
readErr,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if response.StatusCode != http.StatusCreated {
|
||||||
|
errors <- fmt.Errorf(
|
||||||
|
"client %d: expected status %d, got %d; body: %s",
|
||||||
|
index,
|
||||||
|
http.StatusCreated,
|
||||||
|
response.StatusCode,
|
||||||
|
string(responseBody),
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
var message repositories.Message
|
||||||
|
|
||||||
|
if err := json.Unmarshal(responseBody, &message); err != nil {
|
||||||
|
errors <- fmt.Errorf(
|
||||||
|
"client %d: decode response: %w",
|
||||||
|
index,
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if message.ID == "" {
|
||||||
|
errors <- fmt.Errorf(
|
||||||
|
"client %d: response contains empty message ID",
|
||||||
|
index,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
messageIDs <- message.ID
|
||||||
|
}
|
||||||
|
}(clientIndex)
|
||||||
|
}
|
||||||
|
|
||||||
|
waitGroup.Wait()
|
||||||
|
|
||||||
|
close(errors)
|
||||||
|
close(messageIDs)
|
||||||
|
|
||||||
|
for err := range errors {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
createdIDs := make(map[string]bool)
|
||||||
|
|
||||||
|
for messageID := range messageIDs {
|
||||||
|
if createdIDs[messageID] {
|
||||||
|
t.Fatalf("duplicate message ID returned: %s", messageID)
|
||||||
|
}
|
||||||
|
|
||||||
|
createdIDs[messageID] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(createdIDs) != expectedMessages {
|
||||||
|
t.Fatalf(
|
||||||
|
"expected %d unique created messages, got %d",
|
||||||
|
expectedMessages,
|
||||||
|
len(createdIDs),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Дополнительно проверяем историю через HTTP API.
|
||||||
|
request, err := http.NewRequest(
|
||||||
|
http.MethodGet,
|
||||||
|
server.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=100",
|
||||||
|
nil,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create history request: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
request.Header.Set("Authorization", tokens[0])
|
||||||
|
|
||||||
|
response, err := client.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("request message history: %v", err)
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
|
||||||
|
if response.StatusCode != http.StatusOK {
|
||||||
|
body, _ := io.ReadAll(response.Body)
|
||||||
|
|
||||||
|
t.Fatalf(
|
||||||
|
"expected history status %d, got %d; body: %s",
|
||||||
|
http.StatusOK,
|
||||||
|
response.StatusCode,
|
||||||
|
string(body),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
var page messagePage
|
||||||
|
|
||||||
|
if err := json.NewDecoder(response.Body).Decode(&page); err != nil {
|
||||||
|
t.Fatalf("decode message history: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(page.Items) != expectedMessages {
|
||||||
|
t.Fatalf(
|
||||||
|
"expected %d messages in history, got %d",
|
||||||
|
expectedMessages,
|
||||||
|
len(page.Items),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package tests
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMessengerWorkflow(t *testing.T) {
|
||||||
|
router := newTestFixture(t).router
|
||||||
|
|
||||||
|
call := func(method, path, body, auth string, expected int) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
request := httptest.NewRequest(method, path, bytes.NewBufferString(body))
|
||||||
|
if body != "" {
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
}
|
||||||
|
if auth != "" {
|
||||||
|
request.Header.Set("Authorization", auth)
|
||||||
|
}
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(response, request)
|
||||||
|
if response.Code != expected {
|
||||||
|
t.Fatalf("%s %s: status %d, want %d: %s", method, path, response.Code, expected, response.Body.String())
|
||||||
|
}
|
||||||
|
if response.Header().Get("X-Request-Id") == "" {
|
||||||
|
t.Fatalf("%s %s: missing request ID", method, path)
|
||||||
|
}
|
||||||
|
if response.Code == http.StatusNoContent {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var result map[string]any
|
||||||
|
if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
user := call("POST", "/api/v1/users", `{"username":"alice","display_name":"Алиса","password":"lab2-test-password"}`, "", 201)
|
||||||
|
userID := user["id"].(string)
|
||||||
|
basic := "Basic " + base64.StdEncoding.EncodeToString([]byte("alice:lab2-test-password"))
|
||||||
|
session := call("POST", "/api/v1/auth/sessions", "", basic, 201)
|
||||||
|
bearer := "Bearer " + session["token"].(string)
|
||||||
|
call("GET", "/api/v1/users/me", "", bearer, 200)
|
||||||
|
chat := call("POST", "/api/v1/chats", `{"title":"Тестовый чат","member_ids":["`+userID+`"]}`, bearer, 201)
|
||||||
|
chatID := chat["id"].(string)
|
||||||
|
path := "/api/v1/chats/" + chatID + "/messages"
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
call("POST", path, `{"text":"message"}`, bearer, 201)
|
||||||
|
}
|
||||||
|
page1 := call("GET", path+"?limit=2", "", bearer, 200)
|
||||||
|
first := page1["items"].([]any)
|
||||||
|
if len(first) != 2 || page1["next_cursor"] == nil {
|
||||||
|
t.Fatalf("unexpected first page: %v", page1)
|
||||||
|
}
|
||||||
|
page2 := call("GET", path+"?limit=2&cursor="+url.QueryEscape(page1["next_cursor"].(string)), "", bearer, 200)
|
||||||
|
second := page2["items"].([]any)
|
||||||
|
if len(second) != 1 || page2["next_cursor"] != nil || first[0].(map[string]any)["id"] == second[0].(map[string]any)["id"] {
|
||||||
|
t.Fatalf("unexpected second page: %v", page2)
|
||||||
|
}
|
||||||
|
call("DELETE", "/api/v1/auth/sessions/current", "", bearer, 204)
|
||||||
|
call("GET", "/api/v1/users/me", "", bearer, 401)
|
||||||
|
}
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
package tests
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCreateMessageBlankText(t *testing.T) {
|
||||||
|
fixture := newTestFixture(t)
|
||||||
|
userStore, chatStore, messageStore := fixture.users, fixture.chats, fixture.messages
|
||||||
|
|
||||||
|
user, created := createTestUser(t, userStore, "alice", "Алиса")
|
||||||
|
if !created {
|
||||||
|
t.Fatal("expected user to be created")
|
||||||
|
}
|
||||||
|
|
||||||
|
chat := createTestChat(t, chatStore,
|
||||||
|
"Тестовый чат",
|
||||||
|
[]string{user.ID},
|
||||||
|
)
|
||||||
|
|
||||||
|
handler := fixture.router
|
||||||
|
|
||||||
|
request := httptest.NewRequest(
|
||||||
|
http.MethodPost,
|
||||||
|
"/api/v1/chats/"+chat.ID+"/messages",
|
||||||
|
strings.NewReader(`{"text":" \t\n"}`),
|
||||||
|
)
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
authorizeTestRequest(t, fixture, request, user.ID)
|
||||||
|
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler.ServeHTTP(response, request)
|
||||||
|
|
||||||
|
if response.Code != http.StatusBadRequest {
|
||||||
|
t.Fatalf(
|
||||||
|
"expected status %d, got %d; body: %s",
|
||||||
|
http.StatusBadRequest,
|
||||||
|
response.Code,
|
||||||
|
response.Body.String(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if response.Header().Get("X-Request-Id") == "" {
|
||||||
|
t.Fatal("expected non-empty X-Request-Id header")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !strings.Contains(
|
||||||
|
response.Body.String(),
|
||||||
|
`"code":"invalid_request"`,
|
||||||
|
) {
|
||||||
|
t.Fatalf(
|
||||||
|
"expected invalid_request error code, got body: %s",
|
||||||
|
response.Body.String(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
messages := listTestMessages(t, messageStore, chat.ID)
|
||||||
|
|
||||||
|
if len(messages) != 0 {
|
||||||
|
t.Fatalf(
|
||||||
|
"expected no messages to be stored, got %d",
|
||||||
|
len(messages),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestCreateMessageFromChatOutsider(t *testing.T) {
|
||||||
|
fixture := newTestFixture(t)
|
||||||
|
userStore, chatStore, messageStore := fixture.users, fixture.chats, fixture.messages
|
||||||
|
|
||||||
|
alice, created := createTestUser(t, userStore, "alice", "Алиса")
|
||||||
|
if !created {
|
||||||
|
t.Fatal("expected Alice to be created")
|
||||||
|
}
|
||||||
|
|
||||||
|
bob, created := createTestUser(t, userStore, "bob", "Боб")
|
||||||
|
if !created {
|
||||||
|
t.Fatal("expected Bob to be created")
|
||||||
|
}
|
||||||
|
|
||||||
|
chat := createTestChat(t, chatStore,
|
||||||
|
"Чат Алисы",
|
||||||
|
[]string{alice.ID},
|
||||||
|
)
|
||||||
|
|
||||||
|
handler := fixture.router
|
||||||
|
|
||||||
|
request := httptest.NewRequest(
|
||||||
|
http.MethodPost,
|
||||||
|
"/api/v1/chats/"+chat.ID+"/messages",
|
||||||
|
strings.NewReader(`{"text":"Сообщение чужому чату"}`),
|
||||||
|
)
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
authorizeTestRequest(t, fixture, request, bob.ID)
|
||||||
|
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler.ServeHTTP(response, request)
|
||||||
|
|
||||||
|
if response.Code != http.StatusNotFound {
|
||||||
|
t.Fatalf(
|
||||||
|
"expected status %d, got %d; body: %s",
|
||||||
|
http.StatusNotFound,
|
||||||
|
response.Code,
|
||||||
|
response.Body.String(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if response.Header().Get("X-Request-Id") == "" {
|
||||||
|
t.Fatal("expected non-empty X-Request-Id header")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !strings.Contains(
|
||||||
|
response.Body.String(),
|
||||||
|
`"code":"not_found"`,
|
||||||
|
) {
|
||||||
|
t.Fatalf(
|
||||||
|
"expected not_found error code, got body: %s",
|
||||||
|
response.Body.String(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
messages := listTestMessages(t, messageStore, chat.ID)
|
||||||
|
|
||||||
|
if len(messages) != 0 {
|
||||||
|
t.Fatalf(
|
||||||
|
"expected no messages to be stored, got %d",
|
||||||
|
len(messages),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestListMessagesPagination(t *testing.T) {
|
||||||
|
fixture := newTestFixture(t)
|
||||||
|
userStore, chatStore, messageStore := fixture.users, fixture.chats, fixture.messages
|
||||||
|
|
||||||
|
user, created := createTestUser(t, userStore, "alice", "Алиса")
|
||||||
|
if !created {
|
||||||
|
t.Fatal("expected user to be created")
|
||||||
|
}
|
||||||
|
|
||||||
|
chat := createTestChat(t, chatStore,
|
||||||
|
"Тестовый чат",
|
||||||
|
[]string{user.ID},
|
||||||
|
)
|
||||||
|
|
||||||
|
first := createTestMessage(t, messageStore, chat.ID, user.ID, "Первое сообщение")
|
||||||
|
second := createTestMessage(t, messageStore, chat.ID, user.ID, "Второе сообщение")
|
||||||
|
third := createTestMessage(t, messageStore, chat.ID, user.ID, "Третье сообщение")
|
||||||
|
|
||||||
|
expectedIDs := map[string]bool{
|
||||||
|
first.ID: true,
|
||||||
|
second.ID: true,
|
||||||
|
third.ID: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
handler := fixture.router
|
||||||
|
|
||||||
|
// Запрашиваем только два сообщения из трёх.
|
||||||
|
firstRequest := httptest.NewRequest(
|
||||||
|
http.MethodGet,
|
||||||
|
"/api/v1/chats/"+chat.ID+"/messages?limit=2",
|
||||||
|
nil,
|
||||||
|
)
|
||||||
|
authorizeTestRequest(t, fixture, firstRequest, user.ID)
|
||||||
|
|
||||||
|
firstResponse := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler.ServeHTTP(firstResponse, firstRequest)
|
||||||
|
|
||||||
|
if firstResponse.Code != http.StatusOK {
|
||||||
|
t.Fatalf(
|
||||||
|
"expected first page status %d, got %d; body: %s",
|
||||||
|
http.StatusOK,
|
||||||
|
firstResponse.Code,
|
||||||
|
firstResponse.Body.String(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
var firstPage messagePage
|
||||||
|
|
||||||
|
if err := json.NewDecoder(firstResponse.Body).Decode(&firstPage); err != nil {
|
||||||
|
t.Fatalf("failed to decode first page: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(firstPage.Items) != 2 {
|
||||||
|
t.Fatalf(
|
||||||
|
"expected 2 messages on first page, got %d",
|
||||||
|
len(firstPage.Items),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if firstPage.NextCursor == nil || *firstPage.NextCursor == "" {
|
||||||
|
t.Fatal("expected non-empty next cursor on first page")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Проверяем, что сообщения на первой странице уникальны
|
||||||
|
// и принадлежат исходному набору.
|
||||||
|
seenIDs := make(map[string]bool)
|
||||||
|
|
||||||
|
for _, message := range firstPage.Items {
|
||||||
|
if !expectedIDs[message.ID] {
|
||||||
|
t.Fatalf("unexpected message ID on first page: %s", message.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
if seenIDs[message.ID] {
|
||||||
|
t.Fatalf("duplicate message on first page: %s", message.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
seenIDs[message.ID] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Используем cursor первой страницы для получения второй.
|
||||||
|
secondRequest := httptest.NewRequest(
|
||||||
|
http.MethodGet,
|
||||||
|
"/api/v1/chats/"+chat.ID+"/messages?limit=2&cursor="+
|
||||||
|
url.QueryEscape(*firstPage.NextCursor),
|
||||||
|
nil,
|
||||||
|
)
|
||||||
|
authorizeTestRequest(t, fixture, secondRequest, user.ID)
|
||||||
|
|
||||||
|
secondResponse := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler.ServeHTTP(secondResponse, secondRequest)
|
||||||
|
|
||||||
|
if secondResponse.Code != http.StatusOK {
|
||||||
|
t.Fatalf(
|
||||||
|
"expected second page status %d, got %d; body: %s",
|
||||||
|
http.StatusOK,
|
||||||
|
secondResponse.Code,
|
||||||
|
secondResponse.Body.String(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
var secondPage messagePage
|
||||||
|
|
||||||
|
if err := json.NewDecoder(secondResponse.Body).Decode(&secondPage); err != nil {
|
||||||
|
t.Fatalf("failed to decode second page: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(secondPage.Items) != 1 {
|
||||||
|
t.Fatalf(
|
||||||
|
"expected 1 message on second page, got %d",
|
||||||
|
len(secondPage.Items),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if secondPage.NextCursor != nil {
|
||||||
|
t.Fatalf("expected second page to be final, got cursor %q", *secondPage.NextCursor)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Проверяем, что вторая страница не повторяет первую.
|
||||||
|
for _, message := range secondPage.Items {
|
||||||
|
if seenIDs[message.ID] {
|
||||||
|
t.Fatalf("message repeated on second page: %s", message.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !expectedIDs[message.ID] {
|
||||||
|
t.Fatalf("unexpected message ID on second page: %s", message.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
seenIDs[message.ID] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(seenIDs) != len(expectedIDs) {
|
||||||
|
t.Fatalf(
|
||||||
|
"pagination lost messages: expected %d unique messages, got %d",
|
||||||
|
len(expectedIDs),
|
||||||
|
len(seenIDs),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package tests
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"messenger/src/backend/services"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMessageLessUsesIDForEqualTimestamps(t *testing.T) {
|
||||||
|
createdAt := time.Date(2026, 9, 18, 12, 0, 0, 0, time.UTC)
|
||||||
|
first := Message{ID: "a", CreatedAt: createdAt}
|
||||||
|
second := Message{ID: "b", CreatedAt: createdAt}
|
||||||
|
if !services.MessageLess(first, second) || services.MessageLess(second, first) {
|
||||||
|
t.Fatal("equal timestamps must be ordered by ID")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListPageByChatUsesCursorAndLimit(t *testing.T) {
|
||||||
|
f := newTestFixture(t)
|
||||||
|
user, _ := createTestUser(t, f.users, "alice", "Алиса")
|
||||||
|
chat := createTestChat(t, f.chats, "Пагинация", []string{user.ID})
|
||||||
|
other := createTestChat(t, f.chats, "Другой чат", []string{user.ID})
|
||||||
|
createTestMessage(t, f.messages, other.ID, user.ID, "Не должно попасть в страницу")
|
||||||
|
createdAt := time.Date(2026, 9, 18, 12, 0, 0, 0, time.UTC)
|
||||||
|
ids := []string{
|
||||||
|
"00000000-0000-4000-8000-000000000001", "00000000-0000-4000-8000-000000000002",
|
||||||
|
"00000000-0000-4000-8000-000000000003", "00000000-0000-4000-8000-000000000004",
|
||||||
|
}
|
||||||
|
// Insert in reverse order to exercise SQL ordering, including equal timestamps.
|
||||||
|
for i := len(ids) - 1; i >= 0; i-- {
|
||||||
|
at := createdAt
|
||||||
|
if i > 1 {
|
||||||
|
at = at.Add(time.Duration(i-1) * time.Second)
|
||||||
|
}
|
||||||
|
_, err := f.db.Exec(context.Background(), "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)", ids[i], chat.ID, user.ID, "message", at)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
first, more, err := f.messages.ListPageByChat(context.Background(), chat.ID, nil, 2)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !more || len(first) != 2 || first[0].ID != ids[0] || first[1].ID != ids[1] {
|
||||||
|
t.Fatalf("unexpected first page: %v, more=%v", first, more)
|
||||||
|
}
|
||||||
|
cursor := &messageCursor{ChatID: chat.ID, CreatedAt: first[1].CreatedAt, MessageID: first[1].ID}
|
||||||
|
second, more, err := f.messages.ListPageByChat(context.Background(), chat.ID, cursor, 2)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if more || len(second) != 2 || second[0].ID != ids[2] || second[1].ID != ids[3] {
|
||||||
|
t.Fatalf("unexpected second page: %v, more=%v", second, more)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListPageByChatReturnsNonNilEmptyPage(t *testing.T) {
|
||||||
|
f := newTestFixture(t)
|
||||||
|
page, more, err := f.messages.ListPageByChat(context.Background(), uuid.NewString(), nil, 100)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if page == nil || len(page) != 0 || more {
|
||||||
|
t.Fatalf("unexpected empty page: %v, more=%v", page, more)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package tests
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"messenger/src/backend/handlers"
|
||||||
|
"messenger/src/backend/services"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPasswordKDFUsesSaltAndFullUTF8Password(t *testing.T) {
|
||||||
|
password := "длинный-пароль-с-эмодзи-🔒-0123456789"
|
||||||
|
first, err := services.HashPassword(password)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
second, err := services.HashPassword(password)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !bytes.HasPrefix(first, []byte("$argon2id$v=19$m=65536,t=3,p=2$")) || bytes.Equal(first, second) {
|
||||||
|
t.Fatal("password hashes must use Argon2id with independent salts")
|
||||||
|
}
|
||||||
|
valid, err := services.VerifyPassword(password, first)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
invalid, err := services.VerifyPassword(password+"другое", first)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !valid || invalid {
|
||||||
|
t.Fatal("Argon2id verification lost the full UTF-8 password")
|
||||||
|
}
|
||||||
|
if _, err := services.VerifyPassword(password, bytes.Repeat([]byte{1}, 64)); err == nil {
|
||||||
|
t.Fatal("legacy scrypt hash must not be accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStoredPasswordUsesArgon2id(t *testing.T) {
|
||||||
|
fixture := newTestFixture(t)
|
||||||
|
user, _ := createTestUser(t, fixture.users, "alice", "Алиса")
|
||||||
|
var stored []byte
|
||||||
|
if err := fixture.db.QueryRow(context.Background(), "SELECT password_hash FROM users WHERE id=$1", user.ID).Scan(&stored); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !bytes.HasPrefix(stored, []byte("$argon2id$")) {
|
||||||
|
t.Fatalf("unexpected stored password hash format: %q", stored)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBearerRequiredIgnoresXUserID(t *testing.T) {
|
||||||
|
handler := handlers.NewRouter(nil, nil, nil, nil, nil)
|
||||||
|
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
||||||
|
request.Header.Set("X-User-Id", "11111111-1111-4111-8111-111111111111")
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(response, request)
|
||||||
|
if response.Code != 401 || response.Header().Get("WWW-Authenticate") != `Bearer realm="messenger"` {
|
||||||
|
t.Fatalf("unexpected response: %d %v", response.Code, response.Header())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMessageCursorPreservesPosition(t *testing.T) {
|
||||||
|
original := messageCursor{ChatID: "11111111-1111-4111-8111-111111111111", CreatedAt: time.Date(2026, 9, 23, 10, 0, 0, 123000, time.UTC), MessageID: "22222222-2222-4222-8222-222222222222"}
|
||||||
|
token, err := services.EncodeMessageCursor(original)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
decoded, err := services.DecodeMessageCursor(token)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if decoded != original {
|
||||||
|
t.Fatalf("cursor changed: %+v", decoded)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
package tests
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"messenger/src/backend/handlers"
|
||||||
|
"messenger/src/backend/repositories"
|
||||||
|
"messenger/src/backend/services"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
type testFixture struct {
|
||||||
|
db *pgxpool.Pool
|
||||||
|
users *repositories.UserStore
|
||||||
|
chats *repositories.ChatStore
|
||||||
|
messages *repositories.MessageStore
|
||||||
|
sessions *services.SessionService
|
||||||
|
router http.Handler
|
||||||
|
}
|
||||||
|
|
||||||
|
// Each test owns a new schema; public application tables are never modified.
|
||||||
|
func newTestFixture(t *testing.T) *testFixture {
|
||||||
|
t.Helper()
|
||||||
|
url := os.Getenv("TEST_DATABASE_URL")
|
||||||
|
if url == "" {
|
||||||
|
t.Skip("PostgreSQL tests: run make test-backend, or set TEST_DATABASE_URL")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
admin, err := pgxpool.New(ctx, url)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(admin.Close)
|
||||||
|
schema := "test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||||
|
identifier := pgx.Identifier{schema}.Sanitize()
|
||||||
|
if _, err = admin.Exec(ctx, "CREATE SCHEMA "+identifier); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if _, err := admin.Exec(ctx, "DROP SCHEMA "+identifier+" CASCADE"); err != nil {
|
||||||
|
t.Errorf("cleanup test schema: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
cfg, err := pgxpool.ParseConfig(url)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cfg.ConnConfig.RuntimeParams["search_path"] = schema
|
||||||
|
db, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(db.Close)
|
||||||
|
ddl, err := os.ReadFile("../repositories/migrations/000001_initial.up.sql")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = db.Exec(ctx, string(ddl)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
users := repositories.NewUserStore(db)
|
||||||
|
chats := repositories.NewChatStore(db)
|
||||||
|
messages := repositories.NewMessageStore(db)
|
||||||
|
userService := services.NewUserService(users)
|
||||||
|
sessions := services.NewSessionService(userService, repositories.NewSessionStore(db), time.Hour)
|
||||||
|
router := handlers.NewRouter(services.NewHealthService(repositories.NewHealthStore(db)), userService, sessions, services.NewChatService(chats), services.NewMessageService(messages))
|
||||||
|
return &testFixture{db, users, chats, messages, sessions, router}
|
||||||
|
}
|
||||||
|
|
||||||
|
func createTestUser(t *testing.T, store *repositories.UserStore, username, name string) (repositories.User, bool) {
|
||||||
|
t.Helper()
|
||||||
|
user, err := services.NewUserService(store).Create(context.Background(), username, name, "lab2-test-password")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return user, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func createTestChat(t *testing.T, store *repositories.ChatStore, title string, members []string) repositories.Chat {
|
||||||
|
t.Helper()
|
||||||
|
chat, err := store.Create(context.Background(), title, members)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return chat
|
||||||
|
}
|
||||||
|
|
||||||
|
func createTestMessage(t *testing.T, store *repositories.MessageStore, chatID, userID, text string) repositories.Message {
|
||||||
|
t.Helper()
|
||||||
|
message, err := store.Create(context.Background(), chatID, userID, text)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return message
|
||||||
|
}
|
||||||
|
|
||||||
|
func listTestMessages(t *testing.T, store *repositories.MessageStore, chatID string) []repositories.Message {
|
||||||
|
t.Helper()
|
||||||
|
items, _, err := store.ListPageByChat(context.Background(), chatID, nil, 100)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return items
|
||||||
|
}
|
||||||
|
|
||||||
|
func authorizeTestRequest(t *testing.T, fixture *testFixture, request *http.Request, userID string) {
|
||||||
|
t.Helper()
|
||||||
|
token, _, err := fixture.sessions.CreateForUser(request.Context(), userID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
request.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package tests
|
||||||
|
|
||||||
|
import (
|
||||||
|
"messenger/src/backend/repositories"
|
||||||
|
"messenger/src/backend/services"
|
||||||
|
)
|
||||||
|
|
||||||
|
type User = repositories.User
|
||||||
|
type Chat = repositories.Chat
|
||||||
|
type Message = repositories.Message
|
||||||
|
type messagePage = services.MessagePage
|
||||||
|
type messageCursor = repositories.MessageCursor
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
package tests
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"messenger/src/backend/handlers"
|
||||||
|
"messenger/src/backend/repositories"
|
||||||
|
"messenger/src/backend/services"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCreateUserInvalidJSON(t *testing.T) {
|
||||||
|
store := repositories.NewUserStore(nil)
|
||||||
|
handler := handlers.NewRouter(nil, services.NewUserService(store), nil, nil, nil)
|
||||||
|
|
||||||
|
request := httptest.NewRequest(
|
||||||
|
http.MethodPost,
|
||||||
|
"/api/v1/users",
|
||||||
|
strings.NewReader(`{"username":`),
|
||||||
|
)
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler.ServeHTTP(response, request)
|
||||||
|
|
||||||
|
if response.Code != http.StatusBadRequest {
|
||||||
|
t.Fatalf(
|
||||||
|
"expected status %d, got %d; body: %s",
|
||||||
|
http.StatusBadRequest,
|
||||||
|
response.Code,
|
||||||
|
response.Body.String(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if response.Header().Get("Content-Type") != "application/json" {
|
||||||
|
t.Fatalf(
|
||||||
|
"expected Content-Type application/json, got %q",
|
||||||
|
response.Header().Get("Content-Type"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if response.Header().Get("X-Request-Id") == "" {
|
||||||
|
t.Fatal("expected non-empty X-Request-Id header")
|
||||||
|
}
|
||||||
|
|
||||||
|
body := response.Body.String()
|
||||||
|
|
||||||
|
if !strings.Contains(body, `"code":"invalid_request"`) {
|
||||||
|
t.Fatalf(
|
||||||
|
"expected invalid_request error code, got body: %s",
|
||||||
|
body,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !strings.Contains(body, "request_id") {
|
||||||
|
t.Fatalf(
|
||||||
|
"expected request_id in error body, got body: %s",
|
||||||
|
body,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateUserDuplicateUsername(t *testing.T) {
|
||||||
|
fixture := newTestFixture(t)
|
||||||
|
handler := fixture.router
|
||||||
|
|
||||||
|
firstRequest := httptest.NewRequest(
|
||||||
|
http.MethodPost,
|
||||||
|
"/api/v1/users",
|
||||||
|
strings.NewReader(`{
|
||||||
|
"username": "alice",
|
||||||
|
"display_name": "Алиса", "password": "lab2-test-password"
|
||||||
|
}`),
|
||||||
|
)
|
||||||
|
firstRequest.Header.Set("Content-Type", "application/json")
|
||||||
|
|
||||||
|
firstResponse := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler.ServeHTTP(firstResponse, firstRequest)
|
||||||
|
|
||||||
|
if firstResponse.Code != http.StatusCreated {
|
||||||
|
t.Fatalf(
|
||||||
|
"expected first request status %d, got %d; body: %s",
|
||||||
|
http.StatusCreated,
|
||||||
|
firstResponse.Code,
|
||||||
|
firstResponse.Body.String(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
secondRequest := httptest.NewRequest(
|
||||||
|
http.MethodPost,
|
||||||
|
"/api/v1/users",
|
||||||
|
strings.NewReader(`{
|
||||||
|
"username": "alice",
|
||||||
|
"display_name": "Другая Алиса", "password": "lab2-test-password"
|
||||||
|
}`),
|
||||||
|
)
|
||||||
|
secondRequest.Header.Set("Content-Type", "application/json")
|
||||||
|
|
||||||
|
secondResponse := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler.ServeHTTP(secondResponse, secondRequest)
|
||||||
|
|
||||||
|
if secondResponse.Code != http.StatusConflict {
|
||||||
|
t.Fatalf(
|
||||||
|
"expected duplicate username status %d, got %d; body: %s",
|
||||||
|
http.StatusConflict,
|
||||||
|
secondResponse.Code,
|
||||||
|
secondResponse.Body.String(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if secondResponse.Header().Get("X-Request-Id") == "" {
|
||||||
|
t.Fatal("expected non-empty X-Request-Id header")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !strings.Contains(
|
||||||
|
secondResponse.Body.String(),
|
||||||
|
`"code":"conflict"`,
|
||||||
|
) {
|
||||||
|
t.Fatalf(
|
||||||
|
"expected conflict error code, got body: %s",
|
||||||
|
secondResponse.Body.String(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
var count int
|
||||||
|
if err := fixture.db.QueryRow(context.Background(), "SELECT count(*) FROM users").Scan(&count); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if count != 1 {
|
||||||
|
t.Fatalf("expected one user, got %d", count)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,105 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
)
|
|
||||||
|
|
||||||
func getChatHandler(
|
|
||||||
userStore *userStore,
|
|
||||||
chatStore *chatStore,
|
|
||||||
) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
requestID := newRequestID()
|
|
||||||
w.Header().Set("X-Request-Id", requestID)
|
|
||||||
|
|
||||||
if r.Method != http.MethodGet {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusMethodNotAllowed,
|
|
||||||
"method_not_allowed",
|
|
||||||
"method not allowed",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
currentUserID := currentUserID(r)
|
|
||||||
|
|
||||||
if currentUserID == "" {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusUnauthorized,
|
|
||||||
"unauthorized",
|
|
||||||
"valid Bearer session is required",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := userStore.getByID(r.Context(), currentUserID); err != nil {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusUnauthorized,
|
|
||||||
"unauthorized",
|
|
||||||
"unknown user",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
chatID := strings.TrimPrefix(
|
|
||||||
r.URL.Path,
|
|
||||||
"/api/v1/chats/",
|
|
||||||
)
|
|
||||||
|
|
||||||
if chatID == "" || strings.Contains(chatID, "/") {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"invalid chat id",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := uuid.Parse(chatID); err != nil {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"invalid chat id",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
chat, err := chatStore.getByID(r.Context(), chatID)
|
|
||||||
|
|
||||||
if err != nil || !chatStore.isMember(chat, currentUserID) {
|
|
||||||
// Для неизвестного и чужого чата используется одинаковый 404.
|
|
||||||
// Это не раскрывает постороннему пользователю наличие чата.
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusNotFound,
|
|
||||||
"not_found",
|
|
||||||
"chat not found",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
|
|
||||||
if err := json.NewEncoder(w).Encode(chat); err != nil {
|
|
||||||
log.Printf("failed to encode chat response: %v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,194 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
"unicode/utf8"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
)
|
|
||||||
|
|
||||||
type createChatRequest struct {
|
|
||||||
Title string `json:"title"`
|
|
||||||
MemberIDs []string `json:"member_ids"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func createChatHandler(
|
|
||||||
userStore *userStore,
|
|
||||||
chatStore *chatStore,
|
|
||||||
) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
requestID := newRequestID()
|
|
||||||
w.Header().Set("X-Request-Id", requestID)
|
|
||||||
|
|
||||||
if r.Method != http.MethodPost {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusMethodNotAllowed,
|
|
||||||
"method_not_allowed",
|
|
||||||
"method not allowed",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
currentUserID := currentUserID(r)
|
|
||||||
|
|
||||||
if currentUserID == "" {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusUnauthorized,
|
|
||||||
"unauthorized",
|
|
||||||
"valid Bearer session is required",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := userStore.getByID(r.Context(), currentUserID); err != nil {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusUnauthorized,
|
|
||||||
"unauthorized",
|
|
||||||
"unknown user",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if !strings.HasPrefix(
|
|
||||||
r.Header.Get("Content-Type"),
|
|
||||||
"application/json",
|
|
||||||
) {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusUnsupportedMediaType,
|
|
||||||
"unsupported_media_type",
|
|
||||||
"content type must be application/json",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var request createChatRequest
|
|
||||||
|
|
||||||
if err := decodeJSONBody(r, &request); err != nil {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"invalid JSON body",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.TrimSpace(request.Title) == "" {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"title must not be blank",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if utf8.RuneCountInString(request.Title) > 100 {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"title is too long",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(request.MemberIDs) == 0 || len(request.MemberIDs) > 100 {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"member_ids must contain from 1 to 100 users",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
seenMembers := make(map[string]struct{})
|
|
||||||
|
|
||||||
for _, memberID := range request.MemberIDs {
|
|
||||||
if _, err := uuid.Parse(memberID); err != nil {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"member_ids must contain valid UUIDs",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, duplicate := seenMembers[memberID]; duplicate {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"member_ids must not contain duplicates",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
seenMembers[memberID] = struct{}{}
|
|
||||||
|
|
||||||
if _, err := userStore.getByID(r.Context(), memberID); err != nil {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"all members must be existing users",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, included := seenMembers[currentUserID]; !included {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"current user must be a chat member",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
chat, err := chatStore.create(
|
|
||||||
r.Context(),
|
|
||||||
request.Title,
|
|
||||||
request.MemberIDs,
|
|
||||||
)
|
|
||||||
if errors.Is(err, errUnknownMember) {
|
|
||||||
writeError(w, 400, "invalid_request", "all members must be existing users", requestID)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(http.StatusCreated)
|
|
||||||
|
|
||||||
if err := json.NewEncoder(w).Encode(chat); err != nil {
|
|
||||||
log.Printf("failed to encode chat response: %v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,219 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/base64"
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type chatPage struct {
|
|
||||||
Items []Chat `json:"items"`
|
|
||||||
NextCursor *string `json:"next_cursor"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type chatCursor struct {
|
|
||||||
UserID string `json:"user_id"`
|
|
||||||
CreatedAt time.Time `json:"created_at"`
|
|
||||||
ChatID string `json:"chat_id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func encodeChatCursor(cursor chatCursor) (string, error) {
|
|
||||||
data, err := json.Marshal(cursor)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
return base64.RawURLEncoding.EncodeToString(data), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func decodeChatCursor(value string) (chatCursor, error) {
|
|
||||||
data, err := base64.RawURLEncoding.DecodeString(value)
|
|
||||||
if err != nil {
|
|
||||||
return chatCursor{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var cursor chatCursor
|
|
||||||
|
|
||||||
if err := json.Unmarshal(data, &cursor); err != nil {
|
|
||||||
return chatCursor{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if cursor.UserID == "" ||
|
|
||||||
cursor.ChatID == "" ||
|
|
||||||
cursor.CreatedAt.IsZero() {
|
|
||||||
return chatCursor{}, strconv.ErrSyntax
|
|
||||||
}
|
|
||||||
|
|
||||||
return cursor, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func listChatsHandler(
|
|
||||||
userStore *userStore,
|
|
||||||
chatStore *chatStore,
|
|
||||||
) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
requestID := newRequestID()
|
|
||||||
w.Header().Set("X-Request-Id", requestID)
|
|
||||||
|
|
||||||
if r.Method != http.MethodGet {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusMethodNotAllowed,
|
|
||||||
"method_not_allowed",
|
|
||||||
"method not allowed",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
currentUserID := currentUserID(r)
|
|
||||||
|
|
||||||
if currentUserID == "" {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusUnauthorized,
|
|
||||||
"unauthorized",
|
|
||||||
"valid Bearer session is required",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := userStore.getByID(r.Context(), currentUserID); err != nil {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusUnauthorized,
|
|
||||||
"unauthorized",
|
|
||||||
"unknown user",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
limit := 50
|
|
||||||
|
|
||||||
if values, exists := r.URL.Query()["limit"]; exists {
|
|
||||||
if len(values) != 1 || values[0] == "" {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"invalid limit",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
parsedLimit, err := strconv.Atoi(values[0])
|
|
||||||
if err != nil || parsedLimit < 1 || parsedLimit > 100 {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"limit must be between 1 and 100",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
limit = parsedLimit
|
|
||||||
}
|
|
||||||
|
|
||||||
var cursor *chatCursor
|
|
||||||
|
|
||||||
if values, exists := r.URL.Query()["cursor"]; exists {
|
|
||||||
if len(values) != 1 || values[0] == "" {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"invalid cursor",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
decoded, err := decodeChatCursor(values[0])
|
|
||||||
if err != nil || decoded.UserID != currentUserID {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"invalid cursor",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
cursor = &decoded
|
|
||||||
}
|
|
||||||
|
|
||||||
pageItems, hasMore, err := chatStore.listPageForUser(r.Context(), currentUserID, cursor, limit)
|
|
||||||
if err != nil {
|
|
||||||
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
page := chatPage{
|
|
||||||
Items: pageItems,
|
|
||||||
NextCursor: nil,
|
|
||||||
}
|
|
||||||
|
|
||||||
if hasMore {
|
|
||||||
last := pageItems[len(pageItems)-1]
|
|
||||||
|
|
||||||
nextCursor, err := encodeChatCursor(chatCursor{
|
|
||||||
UserID: currentUserID,
|
|
||||||
CreatedAt: last.CreatedAt,
|
|
||||||
ChatID: last.ID,
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusInternalServerError,
|
|
||||||
"internal_error",
|
|
||||||
"internal server error",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
page.NextCursor = &nextCursor
|
|
||||||
}
|
|
||||||
|
|
||||||
if page.Items == nil {
|
|
||||||
page.Items = make([]Chat, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
|
|
||||||
if err := json.NewEncoder(w).Encode(page); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func chatCollectionHandler(
|
|
||||||
userStore *userStore,
|
|
||||||
chatStore *chatStore,
|
|
||||||
) http.HandlerFunc {
|
|
||||||
createHandler := createChatHandler(userStore, chatStore)
|
|
||||||
listHandler := listChatsHandler(userStore, chatStore)
|
|
||||||
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
switch r.Method {
|
|
||||||
case http.MethodPost:
|
|
||||||
createHandler(w, r)
|
|
||||||
case http.MethodGet:
|
|
||||||
listHandler(w, r)
|
|
||||||
default:
|
|
||||||
// Передаём обработку createHandler, чтобы получить
|
|
||||||
// единый JSON-формат ошибки.
|
|
||||||
createHandler(w, r)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
func chatSubresourceHandler(
|
|
||||||
userStore *userStore,
|
|
||||||
chatStore *chatStore,
|
|
||||||
messageStore *messageStore,
|
|
||||||
) http.HandlerFunc {
|
|
||||||
getChat := getChatHandler(userStore, chatStore)
|
|
||||||
createMessage := createMessageHandler(
|
|
||||||
userStore,
|
|
||||||
chatStore,
|
|
||||||
messageStore,
|
|
||||||
)
|
|
||||||
listMessages := listMessagesHandler(
|
|
||||||
userStore,
|
|
||||||
chatStore,
|
|
||||||
messageStore,
|
|
||||||
)
|
|
||||||
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if strings.HasSuffix(r.URL.Path, "/messages") {
|
|
||||||
switch r.Method {
|
|
||||||
case http.MethodPost:
|
|
||||||
createMessage(w, r)
|
|
||||||
case http.MethodGet:
|
|
||||||
listMessages(w, r)
|
|
||||||
default:
|
|
||||||
createMessage(w, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
getChat(w, r)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
func currentUserHandler(store *userStore) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
requestID := newRequestID()
|
|
||||||
w.Header().Set("X-Request-Id", requestID)
|
|
||||||
|
|
||||||
if r.Method != http.MethodGet {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusMethodNotAllowed,
|
|
||||||
"method_not_allowed",
|
|
||||||
"method not allowed",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
userID := currentUserID(r)
|
|
||||||
|
|
||||||
if userID == "" {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusUnauthorized,
|
|
||||||
"unauthorized",
|
|
||||||
"valid Bearer session is required",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
user, err := store.getByID(r.Context(), userID)
|
|
||||||
if err != nil {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusUnauthorized,
|
|
||||||
"unauthorized",
|
|
||||||
"unknown user",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
|
|
||||||
if err := json.NewEncoder(w).Encode(user); err != nil {
|
|
||||||
log.Printf("failed to encode user response: %v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
.vite/
|
||||||
|
*.tsbuildinfo
|
||||||
|
*.local
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
FROM node:22-bookworm-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package.json package-lock.json ./
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
EXPOSE 5173
|
||||||
|
|
||||||
|
CMD ["npm", "run", "dev"]
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Мессенджер · проверка API</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Generated
+1288
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"name": "messenger-test-ui",
|
||||||
|
"private": true,
|
||||||
|
"version": "1.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc --noEmit && vite build",
|
||||||
|
"typecheck": "tsc --noEmit"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"react": "19.3.0",
|
||||||
|
"react-dom": "19.3.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.15.0",
|
||||||
|
"@types/react": "19.3.0",
|
||||||
|
"@types/react-dom": "19.3.0",
|
||||||
|
"@vitejs/plugin-react": "6.1.1",
|
||||||
|
"typescript": "7.0.2",
|
||||||
|
"vite": "8.3.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
import { useCallback, useEffect, useState, type FormEvent } from "react";
|
||||||
|
import { api, ApiError, type Chat, type Session, type User } from "./api";
|
||||||
|
|
||||||
|
import Pagination from "./Pagination";
|
||||||
|
import { useCursorPage } from "./useCursorPage";
|
||||||
|
|
||||||
|
const tokenKey = "messenger_test_token";
|
||||||
|
|
||||||
|
function errorText(error: unknown): string {
|
||||||
|
if (error instanceof ApiError) {
|
||||||
|
return error.requestId
|
||||||
|
? `${error.message} · запрос ${error.requestId}`
|
||||||
|
: error.message;
|
||||||
|
}
|
||||||
|
return error instanceof Error ? error.message : "Неизвестная ошибка";
|
||||||
|
}
|
||||||
|
|
||||||
|
function dateText(value: string): string {
|
||||||
|
return new Date(value).toLocaleString("ru-RU", {
|
||||||
|
dateStyle: "short",
|
||||||
|
timeStyle: "short",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function AuthForm({ onSuccess }: { onSuccess: (session: Session) => void }) {
|
||||||
|
const [mode, setMode] = useState<"login" | "register">("login");
|
||||||
|
const [username, setUsername] = useState("");
|
||||||
|
const [displayName, setDisplayName] = useState("");
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
|
||||||
|
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||||
|
event.preventDefault();
|
||||||
|
setBusy(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
if (mode === "register") {
|
||||||
|
await api.register(username, displayName, password);
|
||||||
|
}
|
||||||
|
const session = await api.login(username, password);
|
||||||
|
setPassword("");
|
||||||
|
onSuccess(session);
|
||||||
|
} catch (cause) {
|
||||||
|
setError(errorText(cause));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="auth-page">
|
||||||
|
<div className="auth-card">
|
||||||
|
<div className="brand-mark" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M5 4h14v12H9l-4 4V4Z"/><path d="M9 8h6M9 12h4"/></svg></div>
|
||||||
|
<h1>Мессенджер</h1>
|
||||||
|
<div className="tabs" aria-label="Режим входа">
|
||||||
|
<button type="button" aria-pressed={mode === "login"} className={mode === "login" ? "active" : ""} onClick={() => { setMode("login"); setError(""); }}>Вход</button>
|
||||||
|
<button type="button" aria-pressed={mode === "register"} className={mode === "register" ? "active" : ""} onClick={() => { setMode("register"); setError(""); }}>Регистрация</button>
|
||||||
|
</div>
|
||||||
|
<form onSubmit={submit} className="stack">
|
||||||
|
<label>
|
||||||
|
Имя пользователя
|
||||||
|
<input value={username} onChange={(event) => setUsername(event.target.value)} required minLength={3} maxLength={32} pattern="[a-z0-9_]+" autoComplete="username" placeholder="ivan_01" />
|
||||||
|
</label>
|
||||||
|
{mode === "register" && (
|
||||||
|
<label>
|
||||||
|
Отображаемое имя
|
||||||
|
<input value={displayName} onChange={(event) => setDisplayName(event.target.value)} required maxLength={100} placeholder="Иван" />
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
<label>
|
||||||
|
Пароль
|
||||||
|
<input type="password" value={password} onChange={(event) => setPassword(event.target.value)} required minLength={12} maxLength={128} autoComplete={mode === "register" ? "new-password" : "current-password"} placeholder="Не менее 12 символов" />
|
||||||
|
</label>
|
||||||
|
{error && <p className="error" role="alert">{error}</p>}
|
||||||
|
<button type="submit" className="primary" disabled={busy}>{busy ? "Подождите…" : mode === "register" ? "Создать аккаунт и войти" : "Войти"}</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Workspace({ token, user, onLogout }: { token: string; user: User; onLogout: (notice?: string) => void }) {
|
||||||
|
const [selectedChat, setSelectedChat] = useState<Chat | null>(null);
|
||||||
|
const [showCreate, setShowCreate] = useState(false);
|
||||||
|
const [title, setTitle] = useState("");
|
||||||
|
const [members, setMembers] = useState("");
|
||||||
|
const [drafts, setDrafts] = useState<Record<string, string>>({});
|
||||||
|
const [creating, setCreating] = useState(false);
|
||||||
|
const [sending, setSending] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [notice, setNotice] = useState("");
|
||||||
|
const reportError = useCallback((cause: unknown) => {
|
||||||
|
if (cause instanceof ApiError && cause.status === 401) onLogout("Сессия истекла. Войдите снова.");
|
||||||
|
else setError(errorText(cause));
|
||||||
|
}, [onLogout]);
|
||||||
|
const fetchChats = useCallback((cursor: string | undefined, limit: number) => api.chats(token, cursor, limit), [token]);
|
||||||
|
const chatId = selectedChat?.id || "";
|
||||||
|
const fetchMessages = useCallback((cursor: string | undefined, limit: number) => api.messages(token, chatId, cursor, limit), [token, chatId]);
|
||||||
|
const chats = useCursorPage(token, fetchChats, reportError);
|
||||||
|
const messages = useCursorPage(chatId, fetchMessages, reportError);
|
||||||
|
|
||||||
|
async function createChat(event: FormEvent<HTMLFormElement>) {
|
||||||
|
event.preventDefault();
|
||||||
|
if (!title.trim()) return;
|
||||||
|
setCreating(true); setError("");
|
||||||
|
try {
|
||||||
|
const memberIds = Array.from(new Set([user.id, ...members.split(/[\s,;]+/).filter(Boolean)]));
|
||||||
|
const chat = await api.createChat(token, title.trim(), memberIds);
|
||||||
|
setSelectedChat(chat); setTitle(""); setMembers(""); setShowCreate(false); chats.refresh();
|
||||||
|
} catch (cause) { reportError(cause); }
|
||||||
|
finally { setCreating(false); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendMessage(event: FormEvent<HTMLFormElement>) {
|
||||||
|
event.preventDefault();
|
||||||
|
const text = (drafts[chatId] || "").trim();
|
||||||
|
if (!text) return;
|
||||||
|
setSending(true); setError("");
|
||||||
|
try {
|
||||||
|
await api.sendMessage(token, chatId, text);
|
||||||
|
setDrafts((previous) => ({ ...previous, [chatId]: "" }));
|
||||||
|
messages.reload(); setNotice("Сообщение отправлено");
|
||||||
|
} catch (cause) { reportError(cause); }
|
||||||
|
finally { setSending(false); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function logout() {
|
||||||
|
try { await api.logout(token); onLogout(); }
|
||||||
|
catch (cause) { reportError(cause); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copyId() {
|
||||||
|
try { await navigator.clipboard.writeText(user.id); setNotice("ID скопирован"); }
|
||||||
|
catch { setError("Не удалось скопировать ID. Выделите его вручную."); }
|
||||||
|
}
|
||||||
|
|
||||||
|
return <div className="app-shell">
|
||||||
|
<header className="app-header">
|
||||||
|
<a className="brand" href="/">Мессенджер<span className="brand-dot" /></a>
|
||||||
|
<div className="account"><span className="avatar">{user.display_name.slice(0, 1).toUpperCase()}</span><div><strong>{user.display_name}</strong><small>@{user.username}</small></div><button className="quiet" onClick={() => void logout()}>Выйти</button></div>
|
||||||
|
</header>
|
||||||
|
{(error || notice) && <div className={error ? "banner error" : "banner"} role={error ? "alert" : "status"}><span>{error || notice}</span><button className="quiet" aria-label="Закрыть уведомление" onClick={() => { setError(""); setNotice(""); }}>Закрыть</button></div>}
|
||||||
|
<div className="app-content">
|
||||||
|
<aside className="sidebar">
|
||||||
|
<div className="sidebar-heading"><h1>Чаты</h1><button className="primary compact" aria-expanded={showCreate} onClick={() => setShowCreate(!showCreate)}>{showCreate ? "Отмена" : "Новый чат"}</button></div>
|
||||||
|
{showCreate && <form className="create-form stack" onSubmit={createChat}>
|
||||||
|
<label>Название<input autoFocus required maxLength={100} value={title} onChange={(event) => setTitle(event.target.value)} /></label>
|
||||||
|
<label>Участники<textarea rows={2} placeholder="ID через запятую · вы уже добавлены" value={members} onChange={(event) => setMembers(event.target.value)} /></label>
|
||||||
|
<button className="primary" disabled={creating}>{creating ? "Создание…" : "Создать"}</button>
|
||||||
|
</form>}
|
||||||
|
<div className="list-toolbar"><span>{chats.items.length} на странице</span><button className="quiet" disabled={chats.busy} onClick={chats.refresh}>Обновить</button></div>
|
||||||
|
<div className="chat-list" aria-busy={chats.busy}>
|
||||||
|
{chats.busy ? <p className="empty-note">Загрузка…</p> : chats.failed ? <p className="empty-note">Не удалось загрузить чаты</p> : !chats.items.length && <p className="empty-note">Нет чатов</p>}
|
||||||
|
{chats.items.map((chat) => <button key={chat.id} className={`chat-item ${chatId === chat.id ? "selected" : ""}`} aria-pressed={chatId === chat.id} disabled={sending} onClick={() => setSelectedChat(chat)}><span className="chat-avatar">{chat.title.slice(0, 1).toUpperCase()}</span><span className="chat-copy"><strong>{chat.title}</strong><small>{chat.member_ids.length} участн.</small></span></button>)}
|
||||||
|
</div>
|
||||||
|
<Pagination label="Чаты" page={chats} />
|
||||||
|
<details className="identity"><summary>Мой ID</summary><code>{user.id}</code><button className="quiet" onClick={() => void copyId()}>Копировать</button></details>
|
||||||
|
</aside>
|
||||||
|
<main className="conversation">
|
||||||
|
{!selectedChat ? <div className="conversation-empty"><svg viewBox="0 0 48 48" aria-hidden="true"><path d="M8 8h32v26H18L8 42V8Z"/><path d="M17 18h14M17 25h9"/></svg><h2>Выберите чат</h2></div> : <>
|
||||||
|
<header className="conversation-header"><div><h2>{selectedChat.title}</h2><details className="members"><summary>{selectedChat.member_ids.length} участн.</summary>{selectedChat.member_ids.map((id) => <code key={id}>{id}{id === user.id ? " · вы" : ""}</code>)}</details></div><button className="quiet" disabled={messages.busy || sending} onClick={messages.reload}>Обновить</button></header>
|
||||||
|
<div className="messages" aria-busy={messages.busy}>
|
||||||
|
{messages.busy ? <p className="empty-note">Загрузка…</p> : messages.failed ? <p className="empty-note">Не удалось загрузить сообщения</p> : !messages.items.length && <p className="empty-note">Нет сообщений</p>}
|
||||||
|
{messages.items.map((message) => <article key={message.id} className={`message ${message.sender_id === user.id ? "own" : ""}`}><div className="message-meta"><strong title={message.sender_id}>{message.sender_id === user.id ? "Вы" : message.sender_id.slice(0, 8)}</strong><time dateTime={message.created_at}>{dateText(message.created_at)}</time></div><p>{message.text}</p></article>)}
|
||||||
|
</div>
|
||||||
|
<Pagination label="Сообщения" page={messages} />
|
||||||
|
<form className="composer" onSubmit={sendMessage}><textarea aria-label="Сообщение" value={drafts[chatId] || ""} onChange={(event) => setDrafts({ ...drafts, [chatId]: event.target.value })} rows={2} maxLength={4000} required placeholder="Сообщение…" /><button className="primary" disabled={sending || messages.busy || !(drafts[chatId] || "").trim()}>{sending ? "Отправка…" : "Отправить"}</button></form>
|
||||||
|
</>}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function App() {
|
||||||
|
const [session, setSession] = useState<{ token: string; user: User } | null>(null);
|
||||||
|
const [restoring, setRestoring] = useState(true);
|
||||||
|
const [notice, setNotice] = useState("");
|
||||||
|
const logout = useCallback((message = "") => {
|
||||||
|
sessionStorage.removeItem(tokenKey); setSession(null); setNotice(message);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const token = sessionStorage.getItem(tokenKey);
|
||||||
|
if (!token) { setRestoring(false); return; }
|
||||||
|
let active = true;
|
||||||
|
api.me(token).then((user) => {
|
||||||
|
if (active) setSession({ token, user });
|
||||||
|
}).catch((cause: unknown) => {
|
||||||
|
if (!active) return;
|
||||||
|
sessionStorage.removeItem(tokenKey);
|
||||||
|
setNotice(cause instanceof ApiError && cause.status === 401 ? "Сессия истекла. Войдите снова." : errorText(cause));
|
||||||
|
}).finally(() => { if (active) setRestoring(false); });
|
||||||
|
return () => { active = false; };
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (restoring) return <main className="loading-page">Загрузка…</main>;
|
||||||
|
if (session) return <Workspace key={session.token} {...session} onLogout={logout} />;
|
||||||
|
return <><AuthForm onSuccess={(next) => { sessionStorage.setItem(tokenKey, next.token); setSession(next); setNotice(""); }} />{notice && <div className="toast" role="status">{notice}</div>}</>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
interface PaginationProps {
|
||||||
|
label: string;
|
||||||
|
page: {
|
||||||
|
number: number; size: number; range: string; busy: boolean;
|
||||||
|
hasPrevious: boolean; hasNext: boolean;
|
||||||
|
previous: () => void; next: () => void; resize: (size: number) => void;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Pagination({ label, page }: PaginationProps) {
|
||||||
|
return <nav className="pagination" aria-label={label}>
|
||||||
|
<div className="page-settings">
|
||||||
|
<label>По <select aria-label={`${label}: размер страницы`} value={page.size} disabled={page.busy} onChange={(event) => page.resize(Number(event.target.value))}>
|
||||||
|
{[2, 5, 10, 25, 50].map((size) => <option key={size} value={size}>{size}</option>)}
|
||||||
|
</select></label>
|
||||||
|
<span className="page-range" aria-live="polite">{page.busy ? "Загрузка…" : `Записи ${page.range}`}</span>
|
||||||
|
</div>
|
||||||
|
<div className="page-navigation">
|
||||||
|
<button type="button" aria-label={`${label}: назад`} onClick={page.previous} disabled={page.busy || !page.hasPrevious}>Назад</button>
|
||||||
|
<span aria-live="polite">Стр. {page.number}</span>
|
||||||
|
<button type="button" aria-label={`${label}: далее`} onClick={page.next} disabled={page.busy || !page.hasNext}>Далее</button>
|
||||||
|
</div>
|
||||||
|
</nav>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
export interface User {
|
||||||
|
id: string;
|
||||||
|
username: string;
|
||||||
|
display_name: string;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Chat {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
member_ids: string[];
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Message {
|
||||||
|
id: string;
|
||||||
|
chat_id: string;
|
||||||
|
sender_id: string;
|
||||||
|
text: string;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Page<T> {
|
||||||
|
items: T[];
|
||||||
|
next_cursor: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Session {
|
||||||
|
token: string;
|
||||||
|
token_type: string;
|
||||||
|
expires_at: string;
|
||||||
|
user: User;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ApiError extends Error {
|
||||||
|
constructor(
|
||||||
|
message: string,
|
||||||
|
public readonly status: number,
|
||||||
|
public readonly requestId?: string,
|
||||||
|
) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||||
|
let response: Response;
|
||||||
|
try {
|
||||||
|
response = await fetch(path, init);
|
||||||
|
} catch {
|
||||||
|
throw new Error("Не удалось связаться с сервером.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.status === 204) return undefined as T;
|
||||||
|
|
||||||
|
const data: unknown = await response.json().catch(() => null);
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = data as { error?: { message?: string; request_id?: string } } | null;
|
||||||
|
throw new ApiError(
|
||||||
|
error?.error?.message || `Ошибка HTTP ${response.status}`,
|
||||||
|
response.status,
|
||||||
|
error?.error?.request_id,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return data as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
function jsonBody(value: unknown): Pick<RequestInit, "body" | "headers"> {
|
||||||
|
return {
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(value),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function bearer(token: string): HeadersInit {
|
||||||
|
return { Authorization: `Bearer ${token}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
function basic(username: string, password: string): string {
|
||||||
|
const bytes = new TextEncoder().encode(`${username}:${password}`);
|
||||||
|
return `Basic ${btoa(String.fromCharCode(...bytes))}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const api = {
|
||||||
|
register: (username: string, displayName: string, password: string) =>
|
||||||
|
request<User>("/api/v1/users", {
|
||||||
|
method: "POST",
|
||||||
|
...jsonBody({ username, display_name: displayName, password }),
|
||||||
|
}),
|
||||||
|
login: (username: string, password: string) =>
|
||||||
|
request<Session>("/api/v1/auth/sessions", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { Authorization: basic(username, password) },
|
||||||
|
}),
|
||||||
|
logout: (token: string) =>
|
||||||
|
request<void>("/api/v1/auth/sessions/current", {
|
||||||
|
method: "DELETE",
|
||||||
|
headers: bearer(token),
|
||||||
|
}),
|
||||||
|
me: (token: string) =>
|
||||||
|
request<User>("/api/v1/users/me", { headers: bearer(token) }),
|
||||||
|
chats: (token: string, cursor?: string, limit = 10) => {
|
||||||
|
const query = new URLSearchParams({ limit: String(limit) });
|
||||||
|
if (cursor) query.set("cursor", cursor);
|
||||||
|
return request<Page<Chat>>(`/api/v1/chats?${query}`, {
|
||||||
|
headers: bearer(token),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
createChat: (token: string, title: string, memberIds: string[]) =>
|
||||||
|
request<Chat>("/api/v1/chats", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { ...bearer(token), "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ title, member_ids: memberIds }),
|
||||||
|
}),
|
||||||
|
messages: (token: string, chatId: string, cursor?: string, limit = 10) => {
|
||||||
|
const query = new URLSearchParams({ limit: String(limit) });
|
||||||
|
if (cursor) query.set("cursor", cursor);
|
||||||
|
return request<Page<Message>>(`/api/v1/chats/${encodeURIComponent(chatId)}/messages?${query}`, {
|
||||||
|
headers: bearer(token),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
sendMessage: (token: string, chatId: string, text: string) =>
|
||||||
|
request<Message>(`/api/v1/chats/${encodeURIComponent(chatId)}/messages`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { ...bearer(token), "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ text }),
|
||||||
|
}),
|
||||||
|
};
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { StrictMode } from "react";
|
||||||
|
import { createRoot } from "react-dom/client";
|
||||||
|
import App from "./App";
|
||||||
|
import "./styles.css";
|
||||||
|
|
||||||
|
createRoot(document.getElementById("root")!).render(
|
||||||
|
<StrictMode>
|
||||||
|
<App />
|
||||||
|
</StrictMode>,
|
||||||
|
);
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
@import url("https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&display=swap");
|
||||||
|
|
||||||
|
:root {
|
||||||
|
font-family: "Manrope", "Segoe UI", sans-serif;
|
||||||
|
color: #242925;
|
||||||
|
background: #eef0ed;
|
||||||
|
font-synthesis: none;
|
||||||
|
--accent: #25634b;
|
||||||
|
--muted: #697169;
|
||||||
|
--line: #e4e8e1;
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
body { margin: 0; }
|
||||||
|
button, input, textarea, select { font: inherit; }
|
||||||
|
button, summary, select { cursor: pointer; }
|
||||||
|
button { border: 1px solid var(--line); border-radius: 8px; background: white; padding: 9px 14px; color: inherit; font-size: 13px; font-weight: 650; transition: background .15s ease, color .15s ease; }
|
||||||
|
button:hover:not(:disabled) { background: #f0f3ee; }
|
||||||
|
button:disabled { cursor: default; color: #879084; background: #f5f6f3; }
|
||||||
|
button:focus-visible, input:focus-visible, textarea:focus-visible, select:focus-visible, summary:focus-visible, a:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
|
||||||
|
::selection { background: #d2e6d8; }
|
||||||
|
* { scrollbar-width: thin; scrollbar-color: #c4cec3 transparent; }
|
||||||
|
input, textarea { caret-color: var(--accent); }
|
||||||
|
h1, h2, p { margin: 0; }
|
||||||
|
h1 { font-size: 24px; letter-spacing: -.035em; font-weight: 800; }
|
||||||
|
h2 { font-size: 18px; letter-spacing: -.025em; }
|
||||||
|
.primary { background: var(--accent); border-color: transparent; color: white; }
|
||||||
|
.primary:hover:not(:disabled) { background: #194c38; }
|
||||||
|
.primary:disabled { background: #e0e6de; border-color: transparent; }
|
||||||
|
.quiet { border-color: transparent; background: transparent; color: var(--muted); padding: 7px 9px; }
|
||||||
|
.compact { font-size: 12px; padding: 9px 12px; }
|
||||||
|
.stack { display: grid; gap: 18px; }
|
||||||
|
label { display: grid; gap: 7px; font-size: 12px; font-weight: 700; }
|
||||||
|
input, textarea { width: 100%; min-width: 0; padding: 12px; border: 1px solid #d6ded3; border-radius: 8px; background: #fff; color: inherit; font-size: 14px; font-weight: 400; }
|
||||||
|
input::placeholder, textarea::placeholder { color: #71796f; }
|
||||||
|
textarea { resize: vertical; }
|
||||||
|
.error { color: #a32f33; font-size: 13px; overflow-wrap: anywhere; }
|
||||||
|
.auth-page, .loading-page { min-height: 100dvh; display: grid; place-items: center; padding: 24px; }
|
||||||
|
.auth-card { width: min(100%, 390px); }
|
||||||
|
.auth-card h1 { font-size: 32px; margin: 20px 0 28px; }
|
||||||
|
.brand-mark { width: 48px; height: 48px; border-radius: 14px; background: var(--accent); display: grid; place-items: center; }
|
||||||
|
.brand-mark svg { width: 28px; stroke: white; stroke-width: 1.5; stroke-linejoin: round; fill: none; }
|
||||||
|
.tabs { display: flex; gap: 4px; padding: 4px; border-radius: 10px; background: #e1e7de; margin-bottom: 28px; }
|
||||||
|
.tabs button { flex: 1; border: 0; background: transparent; color: #596554; }
|
||||||
|
.tabs button.active { background: white; color: #242925; }
|
||||||
|
.auth-card .primary { padding: 13px; margin-top: 6px; }
|
||||||
|
.app-shell { width: min(1440px, 100%); height: calc(100dvh - 48px); min-height: 580px; margin: 24px auto; display: flex; flex-direction: column; background: white; border: 1px solid var(--line); border-radius: 16px; overflow: hidden; }
|
||||||
|
.app-header { min-height: 84px; padding: 18px 28px; display: flex; align-items: center; justify-content: space-between; gap: 20px; border-bottom: 1px solid var(--line); }
|
||||||
|
.brand { color: inherit; text-decoration: none; font-size: 21px; font-weight: 800; letter-spacing: -.035em; display: flex; align-items: center; gap: 8px; }
|
||||||
|
.brand-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--accent); }
|
||||||
|
.account { display: flex; gap: 12px; align-items: center; font-size: 13px; }
|
||||||
|
.account strong, .account small { display: block; }
|
||||||
|
.account small { color: var(--muted); font-size: 11px; margin-top: 2px; }
|
||||||
|
.avatar, .chat-avatar { display: grid; place-items: center; flex-shrink: 0; background: #e7eee3; color: #435d3b; border-radius: 12px; width: 38px; height: 38px; font-size: 14px; font-weight: 700; }
|
||||||
|
.banner { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 8px 24px; background: #edf5ee; color: #295735; font-size: 12px; }
|
||||||
|
.banner.error { background: #fff0ee; color: #a32f33; }
|
||||||
|
.banner .quiet { color: inherit; }
|
||||||
|
.toast { position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%); background: #242925; color: white; padding: 12px 18px; border-radius: 10px; font-size: 13px; }
|
||||||
|
.app-content { display: grid; grid-template-columns: 320px minmax(0, 1fr); flex: 1; min-height: 0; }
|
||||||
|
.sidebar { min-height: 0; display: flex; flex-direction: column; border-right: 1px solid var(--line); }
|
||||||
|
.sidebar-heading { padding: 26px 22px 20px; display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||||
|
.sidebar-heading h1 { font-size: 23px; }
|
||||||
|
.create-form { margin: 0 20px 16px; padding-bottom: 20px; border-bottom: 1px solid var(--line); gap: 12px; overflow-y: auto; flex-shrink: 0; max-height: 38vh; }
|
||||||
|
.list-toolbar { padding: 0 16px 12px 24px; display: flex; justify-content: space-between; align-items: center; color: var(--muted); font-size: 11px; }
|
||||||
|
.chat-list { padding: 0 12px 16px; flex: 1; min-height: 60px; overflow-y: auto; }
|
||||||
|
.chat-item { display: flex; align-items: center; gap: 12px; text-align: left; width: 100%; padding: 14px 12px; border: 0; background: transparent; margin-bottom: 4px; border-radius: 10px; }
|
||||||
|
.chat-item.selected { background: #edf3e9; }
|
||||||
|
.chat-item.selected .chat-avatar { background: #dce8d4; color: #315c27; }
|
||||||
|
.chat-copy { min-width: 0; display: grid; gap: 5px; }
|
||||||
|
.chat-copy strong { font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.chat-copy small { font-size: 11px; font-weight: 400; color: var(--muted); }
|
||||||
|
.identity { border-top: 1px solid var(--line); padding: 14px 24px; font-size: 12px; color: var(--muted); }
|
||||||
|
.identity code { display: block; font-size: 10px; margin-top: 12px; overflow-wrap: anywhere; user-select: all; }
|
||||||
|
.identity .quiet { padding-left: 0; }
|
||||||
|
.conversation { min-height: 0; min-width: 0; display: flex; flex-direction: column; background: #fafbf8; }
|
||||||
|
.conversation-empty { display: grid; justify-items: center; gap: 20px; margin: auto; color: var(--muted); padding: 40px; }
|
||||||
|
.conversation-empty svg { width: 48px; stroke: #95a38c; stroke-width: 1.5; fill: none; stroke-linejoin: round; }
|
||||||
|
.conversation-empty h2 { font-size: 16px; font-weight: 500; }
|
||||||
|
.conversation-header { background: white; padding: 24px 28px; display: flex; justify-content: space-between; align-items: start; gap: 16px; border-bottom: 1px solid var(--line); }
|
||||||
|
.conversation-header h2 { overflow-wrap: anywhere; }
|
||||||
|
.members { margin-top: 5px; color: var(--muted); font-size: 11px; }
|
||||||
|
.members code { display: block; overflow-wrap: anywhere; margin-top: 8px; font-size: 10px; }
|
||||||
|
.messages { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; align-items: flex-start; gap: 16px; padding: 28px; }
|
||||||
|
.message { max-width: min(85%, 620px); border-radius: 12px 12px 12px 3px; background: #eaece7; padding: 12px 16px; }
|
||||||
|
.message.own { align-self: flex-end; background: #e2edda; border-radius: 12px 12px 3px 12px; }
|
||||||
|
.message-meta { display: flex; gap: 24px; justify-content: space-between; align-items: baseline; color: #596453; font-size: 10px; font-variant-numeric: tabular-nums; }
|
||||||
|
.message p { margin-top: 7px; line-height: 1.6; font-size: 14px; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||||
|
.empty-note { margin: auto; padding: 24px; text-align: center; color: var(--muted); font-size: 13px; }
|
||||||
|
.pagination { flex-shrink: 0; border-top: 1px solid var(--line); padding: 14px 22px; background: white; display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px 24px; font-size: 11px; font-variant-numeric: tabular-nums; }
|
||||||
|
.page-settings, .page-navigation { display: flex; align-items: center; gap: 12px; }
|
||||||
|
.page-settings label { display: flex; align-items: center; gap: 6px; color: var(--muted); font-weight: 500; font-size: 11px; }
|
||||||
|
.page-settings select { border: 1px solid var(--line); background: #fafbf8; border-radius: 6px; padding: 5px; color: inherit; }
|
||||||
|
.page-range { color: var(--muted); }
|
||||||
|
.page-navigation button { padding: 6px 10px; font-size: 11px; }
|
||||||
|
.page-navigation span { min-width: 44px; text-align: center; }
|
||||||
|
.sidebar .page-navigation { width: 100%; justify-content: space-between; }
|
||||||
|
.sidebar .page-settings { width: 100%; justify-content: space-between; }
|
||||||
|
.composer { display: flex; align-items: end; gap: 12px; padding: 20px 28px; background: white; border-top: 1px solid var(--line); }
|
||||||
|
.composer textarea { background: #f7f8f5; border-color: transparent; resize: vertical; max-height: 180px; }
|
||||||
|
.composer .primary { padding: 13px 20px; }
|
||||||
|
@media (max-width: 1488px) { .app-shell { width: calc(100% - 48px); } }
|
||||||
|
@media (max-width: 900px) { .app-shell { width: 100%; height: 100dvh; margin: 0; border: 0; border-radius: 0; } .app-content { grid-template-columns: 280px minmax(0, 1fr); } .messages, .conversation-header { padding: 20px; } .message { max-width: 95%; } .message-meta { gap: 12px; flex-wrap: wrap; } .composer { padding: 16px; } }
|
||||||
|
@media (max-width: 620px) { .app-shell { height: auto; min-height: 100dvh; } .app-header { padding: 18px; } .brand { font-size: 18px; } .account .avatar, .account small { display: none; } .account { gap: 4px; } .app-content { display: flex; flex-direction: column; } .sidebar { border-right: 0; border-bottom: 1px solid var(--line); } .sidebar-heading { padding: 20px; } .chat-list { max-height: 240px; } .sidebar .pagination { flex-wrap: nowrap; } .sidebar .page-settings, .sidebar .page-navigation { width: auto; } .sidebar .page-range { display: none; } .conversation { min-height: 480px; } .messages { max-height: 55dvh; min-height: 180px; } .pagination { padding: 12px 16px; } .composer { gap: 8px; } .composer .primary { padding: 12px; } }
|
||||||
|
@media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import type { Page } from "./api";
|
||||||
|
|
||||||
|
// The API supplies only a next cursor. Remember visited cursors for Back.
|
||||||
|
export function useCursorPage<T>(
|
||||||
|
resource: string,
|
||||||
|
fetchPage: (cursor: string | undefined, limit: number) => Promise<Page<T>>,
|
||||||
|
onError: (error: unknown) => void,
|
||||||
|
) {
|
||||||
|
const [query, setQuery] = useState({ resource, cursors: [""], index: 0, size: 5, revision: 0 });
|
||||||
|
const current = query.resource === resource ? query : { ...query, resource, cursors: [""], index: 0 };
|
||||||
|
const cursor = current.cursors[current.index];
|
||||||
|
const queryKey = JSON.stringify([resource, cursor, current.index, current.size, current.revision]);
|
||||||
|
const [result, setResult] = useState<{ key: string; page: Page<T>; busy: boolean; failed: boolean }>({
|
||||||
|
key: "", page: { items: [], next_cursor: null }, busy: false, failed: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!resource) return;
|
||||||
|
let active = true;
|
||||||
|
setResult({ key: queryKey, page: { items: [], next_cursor: null }, busy: true, failed: false });
|
||||||
|
fetchPage(cursor || undefined, current.size).then((page) => {
|
||||||
|
if (active) setResult({ key: queryKey, page, busy: false, failed: false });
|
||||||
|
}).catch((error: unknown) => {
|
||||||
|
if (!active) return;
|
||||||
|
setResult({ key: queryKey, page: { items: [], next_cursor: null }, busy: false, failed: true });
|
||||||
|
onError(error);
|
||||||
|
});
|
||||||
|
return () => { active = false; };
|
||||||
|
}, [resource, queryKey, cursor, current.size, fetchPage, onError]);
|
||||||
|
|
||||||
|
const matches = result.key === queryKey;
|
||||||
|
const items = matches ? result.page.items : [];
|
||||||
|
const busy = Boolean(resource) && (!matches || result.busy);
|
||||||
|
const nextCursor = matches ? result.page.next_cursor : null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
items, busy, failed: matches && result.failed,
|
||||||
|
number: current.index + 1,
|
||||||
|
size: current.size,
|
||||||
|
hasPrevious: current.index > 0,
|
||||||
|
hasNext: Boolean(nextCursor),
|
||||||
|
range: items.length ? `${current.index * current.size + 1}–${current.index * current.size + items.length}` : "0",
|
||||||
|
next() {
|
||||||
|
if (!nextCursor || busy) return;
|
||||||
|
setQuery({ ...current, cursors: [...current.cursors.slice(0, current.index + 1), nextCursor], index: current.index + 1 });
|
||||||
|
},
|
||||||
|
previous() {
|
||||||
|
if (current.index > 0 && !busy) setQuery({ ...current, index: current.index - 1 });
|
||||||
|
},
|
||||||
|
resize(size: number) { setQuery({ ...current, size, index: 0, cursors: [""] }); },
|
||||||
|
refresh() { setQuery({ ...current, index: 0, cursors: [""], revision: current.revision + 1 }); },
|
||||||
|
reload() { setQuery({ ...current, revision: current.revision + 1 }); },
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "Bundler",
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"strict": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"types": ["vite/client", "node"]
|
||||||
|
},
|
||||||
|
"include": ["src", "vite.config.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { defineConfig } from "vite";
|
||||||
|
import react from "@vitejs/plugin-react";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
server: {
|
||||||
|
host: "0.0.0.0",
|
||||||
|
port: 5173,
|
||||||
|
strictPort: true,
|
||||||
|
watch: { usePolling: true },
|
||||||
|
proxy: {
|
||||||
|
"/api/v1": {
|
||||||
|
target: process.env.API_PROXY_TARGET || "http://localhost:8080",
|
||||||
|
changeOrigin: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
-218
@@ -1,218 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/rand"
|
|
||||||
"encoding/hex"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
"log"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"os/signal"
|
|
||||||
"syscall"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type healthResponse struct {
|
|
||||||
Status string `json:"status"`
|
|
||||||
}
|
|
||||||
type apiError struct {
|
|
||||||
Code string `json:"code"`
|
|
||||||
Message string `json:"message"`
|
|
||||||
RequestID string `json:"request_id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type errorResponse struct {
|
|
||||||
Error apiError `json:"error"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func newRequestID() string {
|
|
||||||
bytes := make([]byte, 16)
|
|
||||||
|
|
||||||
if _, err := rand.Read(bytes); err != nil {
|
|
||||||
return "request-id-generation-failed"
|
|
||||||
}
|
|
||||||
|
|
||||||
return hex.EncodeToString(bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeError(w http.ResponseWriter, status int, code string, message string, requestID string) {
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(status)
|
|
||||||
|
|
||||||
response := errorResponse{
|
|
||||||
Error: apiError{
|
|
||||||
Code: code,
|
|
||||||
Message: message,
|
|
||||||
RequestID: requestID,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := json.NewEncoder(w).Encode(response); err != nil {
|
|
||||||
log.Printf("failed to encode error response: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func healthHandler(w http.ResponseWriter, r *http.Request) {
|
|
||||||
requestID := newRequestID()
|
|
||||||
w.Header().Set("X-Request-Id", requestID)
|
|
||||||
|
|
||||||
if r.Method != http.MethodGet {
|
|
||||||
writeError(w, http.StatusMethodNotAllowed, "method_not_allowed", "method not allowed", requestID)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
|
|
||||||
response := healthResponse{
|
|
||||||
Status: "ok",
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := json.NewEncoder(w).Encode(response); err != nil {
|
|
||||||
log.Printf("failed to encode health response: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func readyHandler(db *pgxpool.Pool) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
requestID := newRequestID()
|
|
||||||
w.Header().Set("X-Request-Id", requestID)
|
|
||||||
if r.Method != http.MethodGet {
|
|
||||||
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
if err := db.Ping(ctx); err != nil {
|
|
||||||
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
json.NewEncoder(w).Encode(healthResponse{"ok"})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func serverAddress() string {
|
|
||||||
host := os.Getenv("APP_HOST")
|
|
||||||
if host == "" {
|
|
||||||
host = "0.0.0.0"
|
|
||||||
}
|
|
||||||
|
|
||||||
port := os.Getenv("APP_PORT")
|
|
||||||
if port == "" {
|
|
||||||
port = "8080"
|
|
||||||
}
|
|
||||||
|
|
||||||
return net.JoinHostPort(host, port)
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
if len(os.Args) > 1 {
|
|
||||||
if len(os.Args) == 2 && os.Args[1] == "healthcheck" {
|
|
||||||
client := http.Client{Timeout: 2 * time.Second}
|
|
||||||
response, err := client.Get("http://127.0.0.1:8080/health/ready")
|
|
||||||
if err != nil {
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
response.Body.Close()
|
|
||||||
if response.StatusCode != http.StatusOK {
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if len(os.Args) != 3 || os.Args[1] != "migrate" || (os.Args[2] != "up" && os.Args[2] != "down") {
|
|
||||||
log.Fatal("usage: messenger migrate up|down")
|
|
||||||
}
|
|
||||||
url, err := databaseURL()
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
if err = runMigrations(url, os.Args[2]); err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
log.Printf("migration %s complete", os.Args[2])
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
||||||
db, err := openDatabase(ctx)
|
|
||||||
cancel()
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("database initialization failed: %v", err)
|
|
||||||
}
|
|
||||||
defer db.Close()
|
|
||||||
userStore := newUserStore(db)
|
|
||||||
chatStore := newChatStore(db)
|
|
||||||
messageStore := newMessageStore(db)
|
|
||||||
sessions, err := newSessionStore(db)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
|
||||||
|
|
||||||
mux.HandleFunc("/health/live", healthHandler)
|
|
||||||
mux.HandleFunc("/health/ready", readyHandler(db))
|
|
||||||
mux.Handle("/api/v1/users", createUserHandler(userStore))
|
|
||||||
mux.Handle("/api/v1/auth/sessions", sessionHandler(userStore, sessions))
|
|
||||||
mux.Handle("/api/v1/auth/sessions/current", authRequired(sessions, logoutHandler(sessions)))
|
|
||||||
mux.Handle("/api/v1/users/me", authRequired(sessions, currentUserHandler(userStore)))
|
|
||||||
mux.Handle(
|
|
||||||
"/api/v1/chats",
|
|
||||||
authRequired(sessions, chatCollectionHandler(userStore, chatStore)),
|
|
||||||
)
|
|
||||||
mux.Handle(
|
|
||||||
"/api/v1/chats/",
|
|
||||||
authRequired(sessions, chatSubresourceHandler(
|
|
||||||
userStore,
|
|
||||||
chatStore,
|
|
||||||
messageStore,
|
|
||||||
)),
|
|
||||||
)
|
|
||||||
|
|
||||||
server := &http.Server{
|
|
||||||
Addr: serverAddress(),
|
|
||||||
Handler: mux,
|
|
||||||
}
|
|
||||||
|
|
||||||
shutdownContext, stop := signal.NotifyContext(
|
|
||||||
context.Background(),
|
|
||||||
os.Interrupt,
|
|
||||||
syscall.SIGTERM,
|
|
||||||
)
|
|
||||||
defer stop()
|
|
||||||
|
|
||||||
serverErrors := make(chan error, 1)
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
log.Printf("server is listening on %s", server.Addr)
|
|
||||||
|
|
||||||
if err := server.ListenAndServe(); err != nil &&
|
|
||||||
!errors.Is(err, http.ErrServerClosed) {
|
|
||||||
serverErrors <- err
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
select {
|
|
||||||
case err := <-serverErrors:
|
|
||||||
log.Printf("server error: %v", err)
|
|
||||||
|
|
||||||
case <-shutdownContext.Done():
|
|
||||||
log.Printf("shutdown signal received")
|
|
||||||
|
|
||||||
shutdownDeadline, cancel := context.WithTimeout(
|
|
||||||
context.Background(),
|
|
||||||
10*time.Second,
|
|
||||||
)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
if err := server.Shutdown(shutdownDeadline); err != nil {
|
|
||||||
log.Printf("graceful shutdown failed: %v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Printf("server stopped gracefully")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,184 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
"unicode/utf8"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
)
|
|
||||||
|
|
||||||
type createMessageRequest struct {
|
|
||||||
Text string `json:"text"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func createMessageHandler(
|
|
||||||
userStore *userStore,
|
|
||||||
chatStore *chatStore,
|
|
||||||
messageStore *messageStore,
|
|
||||||
) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
requestID := newRequestID()
|
|
||||||
w.Header().Set("X-Request-Id", requestID)
|
|
||||||
|
|
||||||
if r.Method != http.MethodPost {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusMethodNotAllowed,
|
|
||||||
"method_not_allowed",
|
|
||||||
"method not allowed",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
currentUserID := currentUserID(r)
|
|
||||||
|
|
||||||
if currentUserID == "" {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusUnauthorized,
|
|
||||||
"unauthorized",
|
|
||||||
"valid Bearer session is required",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := userStore.getByID(r.Context(), currentUserID); err != nil {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusUnauthorized,
|
|
||||||
"unauthorized",
|
|
||||||
"unknown user",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
chatID, ok := messageChatID(r.URL.Path)
|
|
||||||
if !ok {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"invalid chat id",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := uuid.Parse(chatID); err != nil {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"invalid chat id",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
chat, err := chatStore.getByID(r.Context(), chatID)
|
|
||||||
|
|
||||||
if err != nil || !chatStore.isMember(chat, currentUserID) {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusNotFound,
|
|
||||||
"not_found",
|
|
||||||
"chat not found",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if !strings.HasPrefix(
|
|
||||||
r.Header.Get("Content-Type"),
|
|
||||||
"application/json",
|
|
||||||
) {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusUnsupportedMediaType,
|
|
||||||
"unsupported_media_type",
|
|
||||||
"content type must be application/json",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var request createMessageRequest
|
|
||||||
|
|
||||||
if err := decodeJSONBody(r, &request); err != nil {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"invalid JSON body",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.TrimSpace(request.Text) == "" {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"text must not be blank",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if utf8.RuneCountInString(request.Text) > 4000 {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"text is too long",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
message, err := messageStore.create(
|
|
||||||
r.Context(),
|
|
||||||
chatID,
|
|
||||||
currentUserID,
|
|
||||||
request.Text,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(http.StatusCreated)
|
|
||||||
|
|
||||||
if err := json.NewEncoder(w).Encode(message); err != nil {
|
|
||||||
log.Printf("failed to encode message response: %v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func messageChatID(path string) (string, bool) {
|
|
||||||
const prefix = "/api/v1/chats/"
|
|
||||||
const suffix = "/messages"
|
|
||||||
|
|
||||||
if !strings.HasPrefix(path, prefix) ||
|
|
||||||
!strings.HasSuffix(path, suffix) {
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
|
|
||||||
chatID := strings.TrimPrefix(path, prefix)
|
|
||||||
chatID = strings.TrimSuffix(chatID, suffix)
|
|
||||||
|
|
||||||
if chatID == "" || strings.Contains(chatID, "/") {
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
|
|
||||||
return chatID, true
|
|
||||||
}
|
|
||||||
@@ -1,229 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/base64"
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type messagePage struct {
|
|
||||||
Items []Message `json:"items"`
|
|
||||||
NextCursor *string `json:"next_cursor"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type messageCursor struct {
|
|
||||||
ChatID string `json:"chat_id"`
|
|
||||||
CreatedAt time.Time `json:"created_at"`
|
|
||||||
MessageID string `json:"message_id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func encodeMessageCursor(cursor messageCursor) (string, error) {
|
|
||||||
data, err := json.Marshal(cursor)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
return base64.RawURLEncoding.EncodeToString(data), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func decodeMessageCursor(value string) (messageCursor, error) {
|
|
||||||
data, err := base64.RawURLEncoding.DecodeString(value)
|
|
||||||
if err != nil {
|
|
||||||
return messageCursor{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var cursor messageCursor
|
|
||||||
|
|
||||||
if err := json.Unmarshal(data, &cursor); err != nil {
|
|
||||||
return messageCursor{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if cursor.ChatID == "" ||
|
|
||||||
cursor.MessageID == "" ||
|
|
||||||
cursor.CreatedAt.IsZero() {
|
|
||||||
return messageCursor{}, strconv.ErrSyntax
|
|
||||||
}
|
|
||||||
|
|
||||||
return cursor, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func listMessagesHandler(
|
|
||||||
userStore *userStore,
|
|
||||||
chatStore *chatStore,
|
|
||||||
messageStore *messageStore,
|
|
||||||
) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
requestID := newRequestID()
|
|
||||||
w.Header().Set("X-Request-Id", requestID)
|
|
||||||
|
|
||||||
if r.Method != http.MethodGet {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusMethodNotAllowed,
|
|
||||||
"method_not_allowed",
|
|
||||||
"method not allowed",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
currentUserID := currentUserID(r)
|
|
||||||
|
|
||||||
if currentUserID == "" {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusUnauthorized,
|
|
||||||
"unauthorized",
|
|
||||||
"valid Bearer session is required",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := userStore.getByID(r.Context(), currentUserID); err != nil {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusUnauthorized,
|
|
||||||
"unauthorized",
|
|
||||||
"unknown user",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
chatID, ok := messageChatID(r.URL.Path)
|
|
||||||
if !ok {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"invalid chat id",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
chat, err := chatStore.getByID(r.Context(), chatID)
|
|
||||||
|
|
||||||
if err != nil || !chatStore.isMember(chat, currentUserID) {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusNotFound,
|
|
||||||
"not_found",
|
|
||||||
"chat not found",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
limit := 50
|
|
||||||
|
|
||||||
if values, exists := r.URL.Query()["limit"]; exists {
|
|
||||||
if len(values) != 1 || values[0] == "" {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"invalid limit",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
parsedLimit, err := strconv.Atoi(values[0])
|
|
||||||
if err != nil || parsedLimit < 1 || parsedLimit > 100 {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"limit must be between 1 and 100",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
limit = parsedLimit
|
|
||||||
}
|
|
||||||
|
|
||||||
var cursor *messageCursor
|
|
||||||
|
|
||||||
if values, exists := r.URL.Query()["cursor"]; exists {
|
|
||||||
if len(values) != 1 || values[0] == "" {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"invalid cursor",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
decoded, err := decodeMessageCursor(values[0])
|
|
||||||
if err != nil || decoded.ChatID != chatID {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"invalid cursor",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
cursor = &decoded
|
|
||||||
}
|
|
||||||
|
|
||||||
pageItems, hasMore, err := messageStore.listPageByChat(
|
|
||||||
r.Context(),
|
|
||||||
chatID,
|
|
||||||
cursor,
|
|
||||||
limit,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
page := messagePage{
|
|
||||||
Items: pageItems,
|
|
||||||
NextCursor: nil,
|
|
||||||
}
|
|
||||||
|
|
||||||
if hasMore {
|
|
||||||
last := pageItems[len(pageItems)-1]
|
|
||||||
|
|
||||||
nextCursor, err := encodeMessageCursor(messageCursor{
|
|
||||||
ChatID: chatID,
|
|
||||||
CreatedAt: last.CreatedAt,
|
|
||||||
MessageID: last.ID,
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusInternalServerError,
|
|
||||||
"internal_error",
|
|
||||||
"internal server error",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
page.NextCursor = &nextCursor
|
|
||||||
}
|
|
||||||
|
|
||||||
if page.Items == nil {
|
|
||||||
page.Items = make([]Message, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
|
|
||||||
if err := json.NewEncoder(w).Encode(page); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestPasswordKDFUsesSaltAndFullUTF8Password(t *testing.T) {
|
|
||||||
password := "длинный-пароль-с-эмодзи-🔒-0123456789"
|
|
||||||
first, err := derivePassword(password, bytes.Repeat([]byte{1}, 32))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
same, err := derivePassword(password, bytes.Repeat([]byte{1}, 32))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
changed, err := derivePassword(password, bytes.Repeat([]byte{2}, 32))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if !bytes.Equal(first, same) || bytes.Equal(first, changed) {
|
|
||||||
t.Fatal("password derivation lost salt or determinism")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestBearerRequiredIgnoresXUserID(t *testing.T) {
|
|
||||||
handler := authRequired(&sessionStore{}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { t.Fatal("business handler reached without bearer") }))
|
|
||||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
|
||||||
request.Header.Set("X-User-Id", "11111111-1111-4111-8111-111111111111")
|
|
||||||
response := httptest.NewRecorder()
|
|
||||||
handler.ServeHTTP(response, request)
|
|
||||||
if response.Code != 401 || response.Header().Get("WWW-Authenticate") != `Bearer realm="messenger"` {
|
|
||||||
t.Fatalf("unexpected response: %d %v", response.Code, response.Header())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMessageCursorPreservesPosition(t *testing.T) {
|
|
||||||
original := messageCursor{ChatID: "11111111-1111-4111-8111-111111111111", CreatedAt: time.Date(2026, 9, 23, 10, 0, 0, 123000, time.UTC), MessageID: "22222222-2222-4222-8222-222222222222"}
|
|
||||||
token, err := encodeMessageCursor(original)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
decoded, err := decodeMessageCursor(token)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if decoded != original {
|
|
||||||
t.Fatalf("cursor changed: %+v", decoded)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-157
@@ -1,157 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/rand"
|
|
||||||
"crypto/sha256"
|
|
||||||
"encoding/hex"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
"unicode/utf8"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
type sessionStore struct {
|
|
||||||
db *pgxpool.Pool
|
|
||||||
ttl time.Duration
|
|
||||||
}
|
|
||||||
|
|
||||||
type authenticatedUserKey struct{}
|
|
||||||
|
|
||||||
func currentUserID(r *http.Request) string {
|
|
||||||
id, _ := r.Context().Value(authenticatedUserKey{}).(string)
|
|
||||||
return id
|
|
||||||
}
|
|
||||||
|
|
||||||
func newSessionStore(db *pgxpool.Pool) (*sessionStore, error) {
|
|
||||||
seconds := 3600
|
|
||||||
if value := os.Getenv("SESSION_TTL_SECONDS"); value != "" {
|
|
||||||
n, err := strconv.Atoi(value)
|
|
||||||
if err != nil || n < 1 {
|
|
||||||
return nil, errors.New("invalid SESSION_TTL_SECONDS")
|
|
||||||
}
|
|
||||||
seconds = n
|
|
||||||
}
|
|
||||||
return &sessionStore{db: db, ttl: time.Duration(seconds) * time.Second}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *sessionStore) create(r *http.Request, userID string) (string, time.Time, error) {
|
|
||||||
raw := make([]byte, 32)
|
|
||||||
if _, err := rand.Read(raw); err != nil {
|
|
||||||
return "", time.Time{}, err
|
|
||||||
}
|
|
||||||
token := hex.EncodeToString(raw)
|
|
||||||
hash := sha256.Sum256([]byte(token))
|
|
||||||
expires := time.Now().UTC().Add(s.ttl).Truncate(time.Microsecond)
|
|
||||||
_, err := s.db.Exec(r.Context(), "INSERT INTO sessions(token_hash,user_id,expires_at) VALUES($1,$2,$3)", hash[:], userID, expires)
|
|
||||||
return token, expires, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *sessionStore) user(r *http.Request, token string) (User, error) {
|
|
||||||
hash := sha256.Sum256([]byte(token))
|
|
||||||
var user User
|
|
||||||
err := s.db.QueryRow(r.Context(), `SELECT u.id,u.username,u.display_name,u.created_at FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.token_hash=$1 AND s.expires_at>now()`, hash[:]).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
|
||||||
return user, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *sessionStore) revoke(r *http.Request, token string) error {
|
|
||||||
hash := sha256.Sum256([]byte(token))
|
|
||||||
_, err := s.db.Exec(r.Context(), "DELETE FROM sessions WHERE token_hash=$1", hash[:])
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// authRequired replaces the lab1 X-User-Id trust model before any business handler runs.
|
|
||||||
func authRequired(s *sessionStore, next http.Handler) http.Handler {
|
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
authorization := r.Header.Get("Authorization")
|
|
||||||
if !strings.HasPrefix(authorization, "Bearer ") || strings.TrimSpace(strings.TrimPrefix(authorization, "Bearer ")) == "" {
|
|
||||||
unauthorized(w, "Bearer", newRequestID())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
token := strings.TrimPrefix(authorization, "Bearer ")
|
|
||||||
user, err := s.user(r, token)
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
unauthorized(w, "Bearer", newRequestID())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
requestID := newRequestID()
|
|
||||||
w.Header().Set("X-Request-Id", requestID)
|
|
||||||
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), authenticatedUserKey{}, user.ID)))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func unauthorized(w http.ResponseWriter, scheme, requestID string) {
|
|
||||||
w.Header().Set("X-Request-Id", requestID)
|
|
||||||
if scheme == "Basic" {
|
|
||||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
|
||||||
} else {
|
|
||||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
|
||||||
}
|
|
||||||
writeError(w, 401, "unauthorized", "invalid credentials", requestID)
|
|
||||||
}
|
|
||||||
|
|
||||||
func sessionHandler(users *userStore, sessions *sessionStore) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
requestID := newRequestID()
|
|
||||||
w.Header().Set("X-Request-Id", requestID)
|
|
||||||
if r.Method != http.MethodPost {
|
|
||||||
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
username, password, ok := r.BasicAuth()
|
|
||||||
if !ok || !usernamePattern.MatchString(username) || utf8.RuneCountInString(password) < 12 || utf8.RuneCountInString(password) > 128 || r.ContentLength > 0 {
|
|
||||||
unauthorized(w, "Basic", requestID)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
user, valid, err := users.verifyPassword(r.Context(), username, password)
|
|
||||||
if err != nil {
|
|
||||||
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if !valid {
|
|
||||||
unauthorized(w, "Basic", requestID)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
token, expires, err := sessions.create(r, user.ID)
|
|
||||||
if err != nil {
|
|
||||||
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(201)
|
|
||||||
json.NewEncoder(w).Encode(struct {
|
|
||||||
Token string `json:"token"`
|
|
||||||
TokenType string `json:"token_type"`
|
|
||||||
ExpiresAt time.Time `json:"expires_at"`
|
|
||||||
User User `json:"user"`
|
|
||||||
}{token, "Bearer", expires, user})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func logoutHandler(sessions *sessionStore) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
requestID := newRequestID()
|
|
||||||
w.Header().Set("X-Request-Id", requestID)
|
|
||||||
if r.Method != http.MethodDelete {
|
|
||||||
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
|
||||||
if err := sessions.revoke(r, token); err != nil {
|
|
||||||
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.WriteHeader(204)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-80
@@ -1,80 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/rand"
|
|
||||||
"crypto/subtle"
|
|
||||||
"errors"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
"golang.org/x/crypto/scrypt"
|
|
||||||
)
|
|
||||||
|
|
||||||
type User struct {
|
|
||||||
ID string `json:"id"`
|
|
||||||
Username string `json:"username"`
|
|
||||||
DisplayName string `json:"display_name"`
|
|
||||||
CreatedAt time.Time `json:"created_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type userStore struct {
|
|
||||||
db *pgxpool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func newUserStore(db *pgxpool.Pool) *userStore {
|
|
||||||
return &userStore{db: db}
|
|
||||||
}
|
|
||||||
|
|
||||||
func derivePassword(password string, salt []byte) ([]byte, error) {
|
|
||||||
return scrypt.Key([]byte(password), salt, 32768, 8, 1, 32)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *userStore) create(ctx context.Context, username, displayName, password string) (User, error) {
|
|
||||||
salt := make([]byte, 32)
|
|
||||||
if _, err := rand.Read(salt); err != nil {
|
|
||||||
return User{}, err
|
|
||||||
}
|
|
||||||
hash, err := derivePassword(password, salt)
|
|
||||||
if err != nil {
|
|
||||||
return User{}, err
|
|
||||||
}
|
|
||||||
packedHash := append(salt, hash...)
|
|
||||||
user := User{
|
|
||||||
ID: uuid.New().String(),
|
|
||||||
Username: username,
|
|
||||||
DisplayName: displayName,
|
|
||||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = s.db.Exec(ctx, "INSERT INTO users(id,username,display_name,password_hash,created_at) VALUES($1,$2,$3,$4,$5)", user.ID, user.Username, user.DisplayName, packedHash, user.CreatedAt)
|
|
||||||
return user, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *userStore) getByID(ctx context.Context, id string) (User, error) {
|
|
||||||
var user User
|
|
||||||
err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at FROM users WHERE id=$1", id).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
|
||||||
return user, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *userStore) verifyPassword(ctx context.Context, username, password string) (User, bool, error) {
|
|
||||||
var user User
|
|
||||||
var packedHash []byte
|
|
||||||
err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at,password_hash FROM users WHERE username=$1", username).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &packedHash)
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return User{}, false, nil
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return User{}, false, err
|
|
||||||
}
|
|
||||||
if len(packedHash) != 64 {
|
|
||||||
return User{}, false, errors.New("invalid password hash format")
|
|
||||||
}
|
|
||||||
actual, err := derivePassword(password, packedHash[:32])
|
|
||||||
if err != nil {
|
|
||||||
return User{}, false, err
|
|
||||||
}
|
|
||||||
return user, subtle.ConstantTimeCompare(packedHash[32:], actual) == 1, nil
|
|
||||||
}
|
|
||||||
@@ -1,155 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"github.com/jackc/pgx/v5/pgconn"
|
|
||||||
"io"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
"unicode/utf8"
|
|
||||||
)
|
|
||||||
|
|
||||||
type createUserRequest struct {
|
|
||||||
Username string `json:"username"`
|
|
||||||
DisplayName string `json:"display_name"`
|
|
||||||
Password string `json:"password"`
|
|
||||||
}
|
|
||||||
|
|
||||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
|
||||||
|
|
||||||
func decodeJSONBody(r *http.Request, destination any) error {
|
|
||||||
decoder := json.NewDecoder(r.Body)
|
|
||||||
decoder.DisallowUnknownFields()
|
|
||||||
|
|
||||||
if err := decoder.Decode(destination); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
var extra any
|
|
||||||
if err := decoder.Decode(&extra); err != io.EOF {
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return fmt.Errorf("more than one JSON value")
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func createUserHandler(store *userStore) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
requestID := newRequestID()
|
|
||||||
w.Header().Set("X-Request-Id", requestID)
|
|
||||||
|
|
||||||
if r.Method != http.MethodPost {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusMethodNotAllowed,
|
|
||||||
"method_not_allowed",
|
|
||||||
"method not allowed",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusUnsupportedMediaType,
|
|
||||||
"unsupported_media_type",
|
|
||||||
"content type must be application/json",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var request createUserRequest
|
|
||||||
|
|
||||||
if err := decodeJSONBody(r, &request); err != nil {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"invalid JSON body",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if !usernamePattern.MatchString(request.Username) {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"username must contain 3-32 lowercase latin letters, digits or underscores",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.TrimSpace(request.DisplayName) == "" {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"display_name must not be blank",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if utf8.RuneCountInString(request.DisplayName) > 100 {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusBadRequest,
|
|
||||||
"invalid_request",
|
|
||||||
"display_name is too long",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(request.Password) == "" || utf8.RuneCountInString(request.Password) < 12 || utf8.RuneCountInString(request.Password) > 128 {
|
|
||||||
writeError(w, http.StatusBadRequest, "invalid_request", "password must contain 12-128 characters", requestID)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
user, err := store.create(
|
|
||||||
r.Context(),
|
|
||||||
request.Username,
|
|
||||||
request.DisplayName,
|
|
||||||
request.Password,
|
|
||||||
)
|
|
||||||
|
|
||||||
if uniqueViolation(err) {
|
|
||||||
writeError(
|
|
||||||
w,
|
|
||||||
http.StatusConflict,
|
|
||||||
"conflict",
|
|
||||||
"username is already taken",
|
|
||||||
requestID,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
var pgerr *pgconn.PgError
|
|
||||||
if errors.As(err, &pgerr) && pgerr.Code == "23514" {
|
|
||||||
writeError(w, 400, "invalid_request", "invalid user fields", requestID)
|
|
||||||
} else {
|
|
||||||
writeError(w, 503, "unavailable", "database unavailable", requestID)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(http.StatusCreated)
|
|
||||||
|
|
||||||
if err := json.NewEncoder(w).Encode(user); err != nil {
|
|
||||||
log.Printf("failed to encode user response: %v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user