forked from mtusi2026/mtusi2026lab2
Реализация на 4
This commit is contained in:
+49
-9
@@ -1,11 +1,51 @@
|
||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
||||
# Copy to .env and replace both password placeholders for a local synthetic stand.
|
||||
# Never commit .env. Existing .env files must be updated manually; see infra/README.md.
|
||||
HOST_PORT=8080
|
||||
|
||||
APP_ENABLED=true
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
APP_READ_TIMEOUT=5s
|
||||
APP_WRITE_TIMEOUT=10s
|
||||
APP_IDLE_TIMEOUT=60s
|
||||
APP_SHUTDOWN_TIMEOUT=8s
|
||||
|
||||
APPLICATION_LOG_LEVEL=info
|
||||
APPLICATION_ENVIRONMENT=dev
|
||||
APPLICATION_SHUTDOWN_TIMEOUT=8s
|
||||
APPLICATION_REQUEST_RATE_LIMIT=100
|
||||
APPLICATION_BURST_RATE_LIMIT=100
|
||||
APPLICATION_RATE_LIMIT_TTL=1m
|
||||
|
||||
# Compose fixes container addresses and ports to the service names below.
|
||||
# These ports are not published on the host.
|
||||
POSTGRES_HOST=postgres
|
||||
POSTGRES_PORT=5432
|
||||
POSTGRES_USER=messenger
|
||||
POSTGRES_PASSWORD=replace-with-local-postgres-password
|
||||
POSTGRES_DATABASE=messenger
|
||||
POSTGRES_VERSION_TABLE=versions
|
||||
# The Go runner is not implemented; postgres bootstraps a new volume instead.
|
||||
POSTGRES_RUN_MIGRATIONS=false
|
||||
POSTGRES_MAX_CONNECTIONS=10
|
||||
|
||||
REDIS_HOST=redis
|
||||
REDIS_PORT=6379
|
||||
REDIS_USERNAME=default
|
||||
REDIS_PASSWORD=replace-with-local-redis-password
|
||||
REDIS_DB=0
|
||||
|
||||
JWT_ACCESS_TOKEN_LIFETIME=15m
|
||||
JWT_REFRESH_TOKEN_LIFETIME=24h
|
||||
# Container paths. Compose mounts ./certs read-only at /run/certs.
|
||||
JWT_PUBLIC_KEY_PATH=/run/certs/public_key.pem
|
||||
JWT_PRIVATE_KEY_PATH=/run/certs/private_key.pem
|
||||
|
||||
# Local HTTP defaults. Use secure cookies when serving through HTTPS.
|
||||
COOKIES_ENABLED=false
|
||||
COOKIES_DOMAIN=localhost
|
||||
COOKIES_PATH=/
|
||||
COOKIES_SECURE=false
|
||||
COOKIES_SAME_SITE=lax
|
||||
# Viper accepts a whitespace-separated list of origins.
|
||||
COOKIES_ALLOWED_ORIGINS=http://localhost:8080
|
||||
|
||||
@@ -28,5 +28,6 @@ coverage/
|
||||
.DS_Store
|
||||
.idea/
|
||||
.vscode/
|
||||
certs/
|
||||
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
||||
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
||||
|
||||
@@ -4,13 +4,93 @@ services:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
image: mtusi-messenger:lab2
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
APP_ENABLED: "true"
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: "8080"
|
||||
APP_READ_TIMEOUT: ${APP_READ_TIMEOUT:-5s}
|
||||
APP_WRITE_TIMEOUT: ${APP_WRITE_TIMEOUT:-10s}
|
||||
APP_IDLE_TIMEOUT: ${APP_IDLE_TIMEOUT:-60s}
|
||||
APP_SHUTDOWN_TIMEOUT: ${APP_SHUTDOWN_TIMEOUT:-8s}
|
||||
APPLICATION_LOG_LEVEL: ${APPLICATION_LOG_LEVEL:-info}
|
||||
APPLICATION_ENVIRONMENT: ${APPLICATION_ENVIRONMENT:-dev}
|
||||
APPLICATION_SHUTDOWN_TIMEOUT: ${APPLICATION_SHUTDOWN_TIMEOUT:-8s}
|
||||
APPLICATION_REQUEST_RATE_LIMIT: ${APPLICATION_REQUEST_RATE_LIMIT:-100}
|
||||
APPLICATION_BURST_RATE_LIMIT: ${APPLICATION_BURST_RATE_LIMIT:-100}
|
||||
APPLICATION_RATE_LIMIT_TTL: ${APPLICATION_RATE_LIMIT_TTL:-1m}
|
||||
POSTGRES_HOST: postgres
|
||||
POSTGRES_PORT: "5432"
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
|
||||
POSTGRES_DATABASE: ${POSTGRES_DATABASE:-messenger}
|
||||
POSTGRES_VERSION_TABLE: ${POSTGRES_VERSION_TABLE:-versions}
|
||||
# Schema bootstrap is handled by postgres; the Go migration runner is not implemented.
|
||||
POSTGRES_RUN_MIGRATIONS: "false"
|
||||
POSTGRES_MAX_CONNECTIONS: ${POSTGRES_MAX_CONNECTIONS:-10}
|
||||
REDIS_HOST: redis
|
||||
REDIS_PORT: "6379"
|
||||
REDIS_USERNAME: default
|
||||
REDIS_PASSWORD: ${REDIS_PASSWORD:?Set REDIS_PASSWORD in .env}
|
||||
REDIS_DB: ${REDIS_DB:-0}
|
||||
JWT_ACCESS_TOKEN_LIFETIME: ${JWT_ACCESS_TOKEN_LIFETIME:-15m}
|
||||
JWT_REFRESH_TOKEN_LIFETIME: ${JWT_REFRESH_TOKEN_LIFETIME:-24h}
|
||||
JWT_PUBLIC_KEY_PATH: /run/certs/public_key.pem
|
||||
JWT_PRIVATE_KEY_PATH: /run/certs/private_key.pem
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ./certs
|
||||
target: /run/certs
|
||||
read_only: true
|
||||
bind:
|
||||
create_host_path: false
|
||||
ports:
|
||||
- "127.0.0.1:${HOST_PORT:-8080}:8080"
|
||||
stop_grace_period: 10s
|
||||
|
||||
postgres:
|
||||
image: postgres:17.11-alpine3.23
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
|
||||
POSTGRES_DB: ${POSTGRES_DATABASE:-messenger}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\""]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
start_period: 30s
|
||||
retries: 12
|
||||
stop_grace_period: 60s
|
||||
|
||||
redis:
|
||||
image: redis:8.2.11-alpine3.22
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
REDIS_PASSWORD: ${REDIS_PASSWORD:?Set REDIS_PASSWORD in .env}
|
||||
# Redis does not apply REDIS_PASSWORD by itself. Re-enter its entrypoint
|
||||
# with redis-server so it also drops privileges to the redis user.
|
||||
command:
|
||||
- sh
|
||||
- -c
|
||||
- exec docker-entrypoint.sh redis-server --appendonly yes --appendfsync everysec --requirepass "$$REDIS_PASSWORD"
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "REDISCLI_AUTH=\"$${REDIS_PASSWORD}\" redis-cli --no-auth-warning ping | grep -qx PONG"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
start_period: 5s
|
||||
retries: 12
|
||||
stop_grace_period: 30s
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
# Инфраструктура студента
|
||||
|
||||
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
|
||||
|
||||
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
|
||||
|
||||
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
|
||||
Executable
+21
@@ -0,0 +1,21 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
project_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$project_root"
|
||||
|
||||
if [ ! -d certs ]; then
|
||||
make key-gen
|
||||
fi
|
||||
|
||||
compose() {
|
||||
docker compose --env-file "${COMPOSE_ENV_FILE:-.env}" -f docker-compose.yml "$@"
|
||||
}
|
||||
|
||||
# Validate and build before stopping the API. Recreate containers to apply
|
||||
# current Compose settings, preserve named volumes, and wait for healthchecks.
|
||||
compose config --quiet
|
||||
compose build api
|
||||
compose stop api
|
||||
compose up -d --force-recreate --wait --wait-timeout 120 postgres redis
|
||||
compose up -d --no-build --pull never --force-recreate --wait --wait-timeout 60 api
|
||||
+51
-19
@@ -7,13 +7,26 @@ import (
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/adapter/controller/http"
|
||||
inmemory2 "gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/inmemory"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/adapter/repository/storage"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/config"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/encrypting"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/migrator"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres/txmanager"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/middleware"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/validator"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/auth"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/chat"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/user"
|
||||
)
|
||||
|
||||
func main() {
|
||||
time.Local = time.UTC
|
||||
if err := run(); err != nil {
|
||||
slog.Error("application stopped", "error", err)
|
||||
os.Exit(1)
|
||||
@@ -21,44 +34,63 @@ func main() {
|
||||
}
|
||||
|
||||
func run() error {
|
||||
cfg, err := config.LoadServer()
|
||||
cfg, err := config.New()
|
||||
if err != nil {
|
||||
return fmt.Errorf("load server config: %w", err)
|
||||
}
|
||||
|
||||
router := http.NewRouter()
|
||||
pgx, err := postgres.New(cfg.Postgres)
|
||||
if err != nil {
|
||||
return fmt.Errorf("init postgres: %w", err)
|
||||
}
|
||||
postgresMigrator := migrator.New(cfg)
|
||||
tm := txmanager.New(pgx)
|
||||
provider := jwtprovider.New(cfg)
|
||||
encryptor := encrypting.New()
|
||||
|
||||
userCache := inmemory2.NewUserCache()
|
||||
chatCache := inmemory2.NewChatCache(userCache)
|
||||
messageCache := inmemory2.NewMessageCache(chatCache)
|
||||
chatsRepo := storage.NewChatsRepo(pgx)
|
||||
messageRepo := storage.NewMessagesRepo(pgx)
|
||||
refreshTokensRepo := storage.NewRefreshTokensRepo(pgx)
|
||||
userRepo := storage.NewUsersRepo(pgx)
|
||||
|
||||
server := http.New(cfg, router)
|
||||
|
||||
baseHandler := http.NewBaseHandler(router)
|
||||
healthHandler := http.NewHealthHandler(baseHandler, server)
|
||||
chatHandler := http.NewChatHandler(baseHandler, userCache, chatCache, messageCache)
|
||||
userHandler := http.NewUserHandler(baseHandler, userCache)
|
||||
authSvc := auth.New(provider, tm, encryptor, userRepo, refreshTokensRepo)
|
||||
userSvc := user.New(encryptor, userRepo)
|
||||
chatSvc := chat.New(tm, chatsRepo, messageRepo)
|
||||
|
||||
httpRouter := router.New(
|
||||
middleware.NewAuthMiddleware(authSvc),
|
||||
middleware.RequestIDMiddleware(),
|
||||
middleware.LoggingMiddleware(),
|
||||
)
|
||||
server := http.New(cfg, httpRouter)
|
||||
requestValidator := validator.NewValidatorImpl()
|
||||
registerRoutes(
|
||||
healthHandler,
|
||||
chatHandler,
|
||||
userHandler,
|
||||
http.NewAuthHandler(httpRouter, authSvc),
|
||||
http.NewHealthHandler(httpRouter, server),
|
||||
http.NewChatHandler(httpRouter, provider, requestValidator, chatSvc),
|
||||
http.NewUserHandler(httpRouter, provider, requestValidator, userSvc),
|
||||
)
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
if err := server.Start(ctx); err != nil {
|
||||
if err = postgresMigrator.Start(ctx); err != nil {
|
||||
return fmt.Errorf("start postgres migrator: %w", err)
|
||||
}
|
||||
if err = server.Start(ctx); err != nil {
|
||||
return fmt.Errorf("start HTTP server: %w", err)
|
||||
}
|
||||
slog.Info("HTTP server started", "address", cfg.BindAddress())
|
||||
slog.Info("HTTP server started", "address", cfg.Server.BindAddress())
|
||||
|
||||
<-ctx.Done()
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.Server.ShutdownTimeout)
|
||||
defer cancel()
|
||||
if err := server.Stop(shutdownCtx); err != nil {
|
||||
if err = server.Stop(shutdownCtx); err != nil {
|
||||
return fmt.Errorf("stop HTTP server: %w", err)
|
||||
}
|
||||
if err = postgresMigrator.Close(shutdownCtx); err != nil {
|
||||
return fmt.Errorf("close postgres migrator: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
+25
-4
@@ -5,32 +5,53 @@ go 1.27.0
|
||||
require (
|
||||
github.com/go-chi/chi/v5 v5.5.0
|
||||
github.com/go-playground/validator/v10 v10.30.5
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgerrcode v0.0.0-20250907135507-afb5586c32a6
|
||||
github.com/jackc/pgx/v5 v5.11.0
|
||||
github.com/oapi-codegen/runtime v1.4.2
|
||||
github.com/redis/go-redis/v9 v9.23.0
|
||||
github.com/spf13/viper v1.21.0
|
||||
go.uber.org/multierr v1.11.0
|
||||
golang.org/x/crypto v0.57.0
|
||||
google.golang.org/grpc v1.85.0
|
||||
)
|
||||
|
||||
require (
|
||||
dario.cat/mergo v1.0.2 // indirect
|
||||
github.com/Masterminds/goutils v1.1.1 // indirect
|
||||
github.com/Masterminds/semver/v3 v3.5.0 // indirect
|
||||
github.com/Masterminds/sprig/v3 v3.3.0 // indirect
|
||||
github.com/Masterminds/squirrel v1.5.4 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
|
||||
github.com/huandu/xstrings v1.5.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/jackc/tern/v2 v2.4.3 // indirect
|
||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
|
||||
github.com/leodido/go-urn v1.5.0 // indirect
|
||||
github.com/mcosta74/pgx-slog v0.4.1 // indirect
|
||||
github.com/mitchellh/copystructure v1.2.0 // indirect
|
||||
github.com/mitchellh/reflectwalk v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.4.3-0.20260624044523-35f78d5908f1 // indirect
|
||||
github.com/redis/go-redis/v9 v9.23.0 // indirect
|
||||
github.com/sagikazarmark/locafero v0.11.0 // indirect
|
||||
github.com/shopspring/decimal v1.4.0 // indirect
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
|
||||
github.com/spf13/afero v1.15.0 // indirect
|
||||
github.com/spf13/cast v1.10.0 // indirect
|
||||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/vgarvardt/pgx-google-uuid/v5 v5.6.0 // indirect
|
||||
go.uber.org/atomic v1.12.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
golang.org/x/crypto v0.57.0 // indirect
|
||||
golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
)
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
|
||||
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
|
||||
github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=
|
||||
github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU=
|
||||
github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE=
|
||||
github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
|
||||
github.com/Masterminds/sprig/v3 v3.3.0 h1:mQh0Yrg1XPo6vjYXgtf5OtijNAKJRNcTdOOGZe3tPhs=
|
||||
github.com/Masterminds/sprig/v3 v3.3.0/go.mod h1:Zy1iXRYNqNLUolqCpL4uhk6SHUMAOSCzdgBfDb35Lz0=
|
||||
github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM=
|
||||
github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
@@ -24,14 +35,39 @@ github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63Y
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/huandu/xstrings v1.5.0 h1:2ag3IFq9ZDANvthTwTiqSSZLjDc+BedvHPAp5tJy2TI=
|
||||
github.com/huandu/xstrings v1.5.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
|
||||
github.com/jackc/pgerrcode v0.0.0-20250907135507-afb5586c32a6 h1:D/V0gu4zQ3cL2WKeVNVM4r2gLxGGf6McLwgXzRTo2RQ=
|
||||
github.com/jackc/pgerrcode v0.0.0-20250907135507-afb5586c32a6/go.mod h1:a/s9Lp5W7n/DD0VrVoyJ00FbP2ytTPDVOivvn2bMlds=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
|
||||
github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jackc/tern/v2 v2.4.3 h1:g293d3OZgW7OFEhsYXgEv0C21jea2boNr0VR4K5I7OY=
|
||||
github.com/jackc/tern/v2 v2.4.3/go.mod h1:rMpMuRYcff5wWLptoTSO1qcDxJ4OodysvK17i2SVBys=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw=
|
||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o=
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk=
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw=
|
||||
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
|
||||
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
|
||||
github.com/mcosta74/pgx-slog v0.4.1 h1:Rt25l/jE5tu1ioqPDrqY17Kv6REdsM0L9WCT+hFw1rw=
|
||||
github.com/mcosta74/pgx-slog v0.4.1/go.mod h1:BCpubkiENkWQ8MvZ4a9LJgWuBzC5UpWoJmQ1/SOlv+M=
|
||||
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
|
||||
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
|
||||
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
|
||||
github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
|
||||
github.com/oapi-codegen/runtime v1.4.2 h1:GMxFVYLzoYLua+/KvzgSphkyK1lLTReQI9Vf4hvATKE=
|
||||
github.com/oapi-codegen/runtime v1.4.2/go.mod h1:GwV7hC2hviaMzj+ITfHVRESK5J2W/GefVwIND/bMGvU=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
@@ -46,6 +82,8 @@ github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZV
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=
|
||||
github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=
|
||||
github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
|
||||
github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U=
|
||||
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
|
||||
@@ -56,25 +94,38 @@ github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
|
||||
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
|
||||
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||
github.com/vgarvardt/pgx-google-uuid/v5 v5.6.0 h1:EhPtK0mgrgaTMXpegE69hvoSOVC1Ahk8+QJ9B8b+OdU=
|
||||
github.com/vgarvardt/pgx-google-uuid/v5 v5.6.0/go.mod h1:5LtFrNEkgzxHvXPO9eOvcXsSn9/KeKYgx9kjeI2oXQI=
|
||||
go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
|
||||
go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw=
|
||||
google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/auth"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
router router.Router
|
||||
|
||||
auth auth.API
|
||||
}
|
||||
|
||||
func NewAuthHandler(r router.Router, api auth.API) Handler {
|
||||
return &AuthHandler{
|
||||
router: r,
|
||||
auth: api,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *AuthHandler) RegisterRoutes() {
|
||||
h.router.Public(http.MethodPost, "/api/v1/auth/sessions", h.Login)
|
||||
h.router.Private(http.MethodDelete, "/api/v1/auth/sessions/current", h.Logout)
|
||||
}
|
||||
|
||||
func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || username == "" || password == "" {
|
||||
w.Header().Set(
|
||||
"WWW-Authenticate",
|
||||
`Basic realm="messenger", charset="UTF-8"`,
|
||||
)
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeUnauthorized, "invalid credentials"))
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.auth.Login(ctx, dto.Login{
|
||||
Username: username,
|
||||
Password: password,
|
||||
})
|
||||
if err != nil {
|
||||
if apperr.HTTPStatusFromError(err) == http.StatusUnauthorized {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
}
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusCreated, contracts.Session{
|
||||
ExpiresAt: resp.ExpiresAt,
|
||||
Token: resp.Tokens.RefreshToken.Payload,
|
||||
TokenType: resp.TokenType,
|
||||
User: contracts.User{
|
||||
CreatedAt: resp.User.CreatedAt,
|
||||
DisplayName: resp.User.DisplayName,
|
||||
Id: resp.User.ID,
|
||||
Username: resp.User.Username,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
token, exists := framework.Token(r)
|
||||
if !exists {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeUnauthorized, "missing token in header"))
|
||||
return
|
||||
}
|
||||
|
||||
err := h.auth.Logout(ctx, dto.RefreshToken{
|
||||
Payload: token,
|
||||
})
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusNoContent, nil)
|
||||
}
|
||||
@@ -2,157 +2,250 @@ package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
inmemory2 "gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/inmemory"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/validator"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/chat"
|
||||
)
|
||||
|
||||
type ChatHandler struct {
|
||||
*BaseHandler
|
||||
users inmemory2.UserCache
|
||||
chats inmemory2.ChatCache
|
||||
messages inmemory2.MessageCache
|
||||
router router.Router
|
||||
provider jwtprovider.Provider
|
||||
validator *validator.ValidatorImpl
|
||||
|
||||
chat chat.API
|
||||
}
|
||||
|
||||
func NewChatHandler(base *BaseHandler, users inmemory2.UserCache, chats inmemory2.ChatCache, messages inmemory2.MessageCache) Handler {
|
||||
return &ChatHandler{BaseHandler: base, users: users, chats: chats, messages: messages}
|
||||
func NewChatHandler(r router.Router, provider jwtprovider.Provider, v *validator.ValidatorImpl, api chat.API) Handler {
|
||||
return &ChatHandler{
|
||||
router: r,
|
||||
provider: provider,
|
||||
validator: v,
|
||||
chat: api,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *ChatHandler) RegisterRoutes() {
|
||||
h.router.Post("/api/v1/chats", h.Create)
|
||||
h.router.Get("/api/v1/chats", h.Get)
|
||||
h.router.Get("/api/v1/chats/{chat_id}", h.GetByID)
|
||||
h.router.Post("/api/v1/chats/{chat_id}/messages", h.SendMessage)
|
||||
h.router.Get("/api/v1/chats/{chat_id}/messages", h.GetMessages)
|
||||
h.router.Private(http.MethodPost, "/api/v1/chats", h.Create)
|
||||
h.router.Private(http.MethodGet, "/api/v1/chats", h.Get)
|
||||
h.router.Private(http.MethodGet, "/api/v1/chats/{chat_id}", h.GetByID)
|
||||
h.router.Private(http.MethodPost, "/api/v1/chats/{chat_id}/messages", h.SendMessage)
|
||||
h.router.Private(http.MethodGet, "/api/v1/chats/{chat_id}/messages", h.GetMessages)
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
user, ok := h.authenticatedUser(w, r, h.users)
|
||||
if !ok {
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
var req contracts.CreateChat
|
||||
if !h.Decode(w, r, &req) || !h.Validate(w, r, &req) {
|
||||
if !framework.Decode(w, r, &req) || !framework.Validate(w, r, h.validator, &req) {
|
||||
return
|
||||
}
|
||||
chat, err := h.chats.Create(ctx, dto.CreateChat{
|
||||
CreatorID: user.ID,
|
||||
|
||||
if userData.UserID == uuid.Nil ||
|
||||
!validText(req.Title, 100) ||
|
||||
len(req.MemberIds) < 1 ||
|
||||
len(req.MemberIds) > 100 {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid chat fields"))
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.chat.CreateChat(ctx, dto.CreateChat{
|
||||
CreatorID: userData.UserID,
|
||||
Title: req.Title,
|
||||
MemberIDs: req.MemberIds,
|
||||
})
|
||||
if err != nil {
|
||||
h.JSONError(ctx, w, err)
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
h.JSONResponse(w, http.StatusCreated, contractChat(chat))
|
||||
|
||||
framework.JSONResponse(w, http.StatusCreated, contracts.Chat{
|
||||
Id: resp.ID,
|
||||
Title: resp.Title,
|
||||
MemberIds: resp.MemberIDs,
|
||||
CreatedAt: resp.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
user, ok := h.authenticatedUser(w, r, h.users)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, afterID, ok := h.pageParams(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
page, err := h.chats.ListForMember(ctx, user.ID, limit, afterID)
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
h.JSONError(ctx, w, err)
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
items := make([]contracts.Chat, 0, len(page.Items))
|
||||
for _, chat := range page.Items {
|
||||
items = append(items, contractChat(chat))
|
||||
|
||||
limit, afterID, ok := framework.PageParams(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
h.JSONResponse(w, http.StatusOK, contracts.ChatPage{Items: items, NextCursor: cursorString(page.NextCursorID)})
|
||||
|
||||
if userData.UserID == uuid.Nil {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid user id"))
|
||||
return
|
||||
}
|
||||
if afterID != nil && *afterID == uuid.Nil {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid cursor"))
|
||||
return
|
||||
}
|
||||
|
||||
page, err := h.chat.ListForMember(ctx, dto.ChatFilters{
|
||||
UserID: userData.UserID,
|
||||
Limit: limit,
|
||||
AfterID: afterID,
|
||||
})
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
items := make([]contracts.Chat, 0, len(page.Items))
|
||||
for _, item := range page.Items {
|
||||
items = append(items, contracts.Chat{
|
||||
CreatedAt: item.CreatedAt,
|
||||
Id: item.ID,
|
||||
MemberIds: item.MemberIDs,
|
||||
Title: item.Title,
|
||||
})
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.ChatPage{
|
||||
Items: items,
|
||||
NextCursor: cursorString(page.NextCursorID),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *ChatHandler) GetByID(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
user, ok := h.authenticatedUser(w, r, h.users)
|
||||
if !ok {
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
chatID, err := h.ParseIDFromPathParam(ctx, w, r, "chat_id")
|
||||
|
||||
chatID, err := framework.ParseIDFromPathParam(ctx, w, r, "chat_id")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
chat, err := h.chats.GetForMember(ctx, chatID, user.ID)
|
||||
|
||||
resp, err := h.chat.GetForMember(ctx, dto.ChatMember{
|
||||
UserID: userData.UserID,
|
||||
ChatID: chatID,
|
||||
})
|
||||
if err != nil {
|
||||
h.JSONError(ctx, w, err)
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
h.JSONResponse(w, http.StatusOK, contractChat(chat))
|
||||
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.Chat{
|
||||
CreatedAt: resp.CreatedAt,
|
||||
Id: resp.ID,
|
||||
MemberIds: resp.MemberIDs,
|
||||
Title: resp.Title,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *ChatHandler) SendMessage(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
user, ok := h.authenticatedUser(w, r, h.users)
|
||||
if !ok {
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
chatID, err := h.ParseIDFromPathParam(ctx, w, r, "chat_id")
|
||||
|
||||
chatID, err := framework.ParseIDFromPathParam(ctx, w, r, "chat_id")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if _, err := h.chats.GetForMember(ctx, chatID, user.ID); err != nil {
|
||||
h.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
var req contracts.CreateMessage
|
||||
if !h.Decode(w, r, &req) || !h.Validate(w, r, &req) {
|
||||
if !framework.Decode(w, r, &req) || !framework.Validate(w, r, h.validator, &req) {
|
||||
return
|
||||
}
|
||||
message, err := h.messages.Create(ctx, dto.CreateMessage{ChatID: chatID, SenderID: user.ID, Text: req.Text})
|
||||
|
||||
if !validText(req.Text, 4000) {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid message text"))
|
||||
return
|
||||
}
|
||||
|
||||
message, err := h.chat.CreateMessage(ctx, dto.CreateMessage{
|
||||
ChatID: chatID,
|
||||
SenderID: userData.UserID,
|
||||
Text: req.Text,
|
||||
})
|
||||
if err != nil {
|
||||
h.JSONError(ctx, w, err)
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
h.JSONResponse(w, http.StatusCreated, contractMessage(message))
|
||||
|
||||
framework.JSONResponse(w, http.StatusCreated, contracts.Message{
|
||||
Id: message.ID,
|
||||
ChatId: message.ChatID,
|
||||
SenderId: message.SenderID,
|
||||
Text: message.Text,
|
||||
CreatedAt: message.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *ChatHandler) GetMessages(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
user, ok := h.authenticatedUser(w, r, h.users)
|
||||
if !ok {
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
chatID, err := h.ParseIDFromPathParam(ctx, w, r, "chat_id")
|
||||
|
||||
chatID, err := framework.ParseIDFromPathParam(ctx, w, r, "chat_id")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if _, err := h.chats.GetForMember(ctx, chatID, user.ID); err != nil {
|
||||
h.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
limit, afterID, ok := h.pageParams(w, r)
|
||||
|
||||
limit, afterID, ok := framework.PageParams(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
page, err := h.messages.ListForChat(ctx, chatID, user.ID, limit, afterID)
|
||||
|
||||
page, err := h.chat.ListForChat(ctx, dto.MessageFilters{
|
||||
ChatID: chatID,
|
||||
UserID: userData.UserID,
|
||||
Limit: limit,
|
||||
AfterID: afterID,
|
||||
})
|
||||
if err != nil {
|
||||
h.JSONError(ctx, w, err)
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
items := make([]contracts.Message, 0, len(page.Items))
|
||||
for _, message := range page.Items {
|
||||
items = append(items, contractMessage(message))
|
||||
items = append(items, contracts.Message{
|
||||
Id: message.ID,
|
||||
ChatId: message.ChatID,
|
||||
SenderId: message.SenderID,
|
||||
Text: message.Text,
|
||||
CreatedAt: message.CreatedAt,
|
||||
})
|
||||
}
|
||||
h.JSONResponse(w, http.StatusOK, contracts.MessagePage{Items: items, NextCursor: cursorString(page.NextCursorID)})
|
||||
}
|
||||
|
||||
func contractChat(chat dto.Chat) contracts.Chat {
|
||||
return contracts.Chat{Id: chat.ID, Title: chat.Title, MemberIds: chat.MemberIDs, CreatedAt: chat.CreatedAt}
|
||||
}
|
||||
|
||||
func contractMessage(message dto.Message) contracts.Message {
|
||||
return contracts.Message{Id: message.ID, ChatId: message.ChatID, SenderId: message.SenderID, Text: message.Text, CreatedAt: message.CreatedAt}
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.MessagePage{Items: items, NextCursor: cursorString(page.NextCursorID)})
|
||||
}
|
||||
|
||||
func cursorString(id *uuid.UUID) *string {
|
||||
@@ -162,3 +255,7 @@ func cursorString(id *uuid.UUID) *string {
|
||||
value := id.String()
|
||||
return &value
|
||||
}
|
||||
|
||||
func validText(value string, maxLength int) bool {
|
||||
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && utf8.RuneCountInString(value) <= maxLength
|
||||
}
|
||||
|
||||
@@ -8,9 +8,8 @@ import (
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/config"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
|
||||
)
|
||||
|
||||
type Server interface {
|
||||
@@ -26,16 +25,16 @@ type server struct {
|
||||
ready atomic.Bool
|
||||
}
|
||||
|
||||
func New(cfg *config.Server, router chi.Router) Server {
|
||||
func New(cfg *config.Config, router router.Router) Server {
|
||||
s := server{
|
||||
server: http.Server{
|
||||
Addr: cfg.BindAddress(),
|
||||
Addr: cfg.Server.BindAddress(),
|
||||
Handler: router,
|
||||
ReadTimeout: cfg.ReadTimeout,
|
||||
WriteTimeout: cfg.WriteTimeout,
|
||||
IdleTimeout: cfg.IdleTimeout,
|
||||
ReadTimeout: cfg.Server.ReadTimeout,
|
||||
WriteTimeout: cfg.Server.WriteTimeout,
|
||||
IdleTimeout: cfg.Server.IdleTimeout,
|
||||
},
|
||||
cfg: cfg,
|
||||
cfg: cfg.Server,
|
||||
ready: atomic.Bool{},
|
||||
}
|
||||
|
||||
|
||||
@@ -1,220 +1,5 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
v10 "github.com/go-playground/validator/v10"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/inmemory"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/validator"
|
||||
)
|
||||
|
||||
const (
|
||||
HeaderContentType = "Content-Type"
|
||||
HeaderRequestID = "X-Request-Id"
|
||||
HeaderUserID = "X-User-Id"
|
||||
)
|
||||
|
||||
type Handler interface {
|
||||
RegisterRoutes()
|
||||
}
|
||||
|
||||
type BaseHandler struct {
|
||||
router chi.Router
|
||||
validator *validator.ValidatorImpl
|
||||
}
|
||||
|
||||
func NewBaseHandler(r chi.Router) *BaseHandler {
|
||||
return &BaseHandler{
|
||||
router: r,
|
||||
validator: validator.NewValidatorImpl(),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *BaseHandler) validate(ctx context.Context, value any) error {
|
||||
err := h.validator.ValidateCtx(ctx, value)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var fieldErrors v10.ValidationErrors
|
||||
if errors.As(err, &fieldErrors) {
|
||||
return apperr.Wrap(err, apperr.CodeInvalidRequest, "invalid request fields")
|
||||
}
|
||||
return apperr.Wrap(err, apperr.CodeInternalError, "validation failed")
|
||||
}
|
||||
|
||||
func (h *BaseHandler) Validate(w http.ResponseWriter, r *http.Request, value any) bool {
|
||||
if err := h.validate(r.Context(), value); err != nil {
|
||||
h.JSONError(r.Context(), w, err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *BaseHandler) JSONResponse(w http.ResponseWriter, status int, body any) {
|
||||
w.Header().Set(HeaderContentType, "application/json")
|
||||
w.WriteHeader(status)
|
||||
|
||||
if status == http.StatusNoContent {
|
||||
return
|
||||
}
|
||||
|
||||
if err := json.NewEncoder(w).Encode(body); err != nil {
|
||||
wrapped := apperr.Wrap(err, apperr.CodeInternal, "failed json encode")
|
||||
slog.Error("response", "error", wrapped)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *BaseHandler) JSONError(ctx context.Context, w http.ResponseWriter, err error) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
requestId, ok := ctx.Value(HeaderRequestID).(uuid.UUID)
|
||||
if !ok {
|
||||
requestId = uuid.New()
|
||||
}
|
||||
w.Header().Set(HeaderRequestID, requestId.String())
|
||||
|
||||
appErr, ok := apperr.As(err)
|
||||
if !ok {
|
||||
appErr = apperr.New(apperr.CodeInternalError, "internal server error")
|
||||
}
|
||||
slog.Error("response", "error", err, "status", appErr.Code().HTTPStatus(), "requestId", requestId.String())
|
||||
h.JSONResponse(w, appErr.Code().HTTPStatus(), contracts.Error{
|
||||
Error: struct {
|
||||
Code contracts.ErrorErrorCode `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestId string `json:"request_id"`
|
||||
}{
|
||||
Code: contracts.ErrorErrorCode(appErr.Code()),
|
||||
Message: apperr.PublicMessage(appErr),
|
||||
RequestId: requestId.String(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *BaseHandler) Decode(w http.ResponseWriter, r *http.Request, object any) bool {
|
||||
mediaType, params, err := mime.ParseMediaType(r.Header.Get(HeaderContentType))
|
||||
if err != nil || mediaType != "application/json" ||
|
||||
(params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) {
|
||||
h.JSONError(r.Context(), w, apperr.New(apperr.CodeUnsupportedMediaType, "expected application/json"))
|
||||
return false
|
||||
}
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(object); err != nil {
|
||||
h.JSONError(r.Context(), w, apperr.Wrap(err, apperr.CodeBadRequest, "failed decode"))
|
||||
return false
|
||||
}
|
||||
var trailing any
|
||||
if err := decoder.Decode(&trailing); err != io.EOF {
|
||||
h.JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "expected one JSON object"))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *BaseHandler) PathParam(r *http.Request, key string) string {
|
||||
return chi.URLParam(r, key)
|
||||
}
|
||||
|
||||
func (h *BaseHandler) QueryParam(r *http.Request, key string) string {
|
||||
return r.URL.Query().Get(key)
|
||||
}
|
||||
|
||||
func (h *BaseHandler) HeaderParam(r *http.Request, key string) string {
|
||||
return r.Header.Get(key)
|
||||
}
|
||||
|
||||
func (h *BaseHandler) ParseIDFromPathParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
|
||||
rawID := h.PathParam(r, key)
|
||||
id, err := uuid.Parse(rawID)
|
||||
if err != nil {
|
||||
h.JSONError(ctx, w, apperr.New(apperr.CodeValidation, fmt.Sprintf("provided invalid %s", key)))
|
||||
return uuid.Nil, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (h *BaseHandler) ParseIDFromQueryParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
|
||||
rawID := h.QueryParam(r, key)
|
||||
id, err := uuid.Parse(rawID)
|
||||
if err != nil {
|
||||
h.JSONError(ctx, w, apperr.New(apperr.CodeValidation, fmt.Sprintf("provided invalid %s", key)))
|
||||
return uuid.Nil, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (h *BaseHandler) ParseIDFromHeaderParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
|
||||
rawID := h.HeaderParam(r, key)
|
||||
id, err := uuid.Parse(rawID)
|
||||
if err != nil {
|
||||
h.JSONError(ctx, w, apperr.New(apperr.CodeUnauthorized, "missing or invalid user ID"))
|
||||
return uuid.Nil, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (h *BaseHandler) authenticatedUser(w http.ResponseWriter, r *http.Request, users inmemory.UserCache) (dto.User, bool) {
|
||||
id, err := h.ParseIDFromHeaderParam(r.Context(), w, r, HeaderUserID)
|
||||
if err != nil {
|
||||
return dto.User{}, false
|
||||
}
|
||||
user, err := users.GetByID(r.Context(), id)
|
||||
if err != nil {
|
||||
if appErr, ok := apperr.As(err); ok && appErr.Code() == apperr.CodeNotFound {
|
||||
h.JSONError(r.Context(), w, apperr.New(apperr.CodeUnauthorized, "unknown user ID"))
|
||||
} else {
|
||||
h.JSONError(r.Context(), w, err)
|
||||
}
|
||||
return dto.User{}, false
|
||||
}
|
||||
return user, true
|
||||
}
|
||||
|
||||
func (h *BaseHandler) pageParams(w http.ResponseWriter, r *http.Request) (*int, *uuid.UUID, bool) {
|
||||
query := r.URL.Query()
|
||||
var limit *int
|
||||
if values, exists := query["limit"]; exists {
|
||||
if len(values) != 1 {
|
||||
h.JSONError(r.Context(), w, apperr.New(apperr.CodeInvalidRequest, "invalid limit"))
|
||||
return nil, nil, false
|
||||
}
|
||||
value, err := strconv.Atoi(values[0])
|
||||
if err != nil || value < 1 || value > 100 {
|
||||
h.JSONError(r.Context(), w, apperr.New(apperr.CodeInvalidRequest, "invalid limit"))
|
||||
return nil, nil, false
|
||||
}
|
||||
limit = &value
|
||||
}
|
||||
var afterID *uuid.UUID
|
||||
if values, exists := query["cursor"]; exists {
|
||||
if len(values) != 1 {
|
||||
h.JSONError(r.Context(), w, apperr.New(apperr.CodeInvalidRequest, "invalid cursor"))
|
||||
return nil, nil, false
|
||||
}
|
||||
id, err := uuid.Parse(values[0])
|
||||
if err != nil || id == uuid.Nil {
|
||||
h.JSONError(r.Context(), w, apperr.New(apperr.CodeInvalidRequest, "invalid cursor"))
|
||||
return nil, nil, false
|
||||
}
|
||||
afterID = &id
|
||||
}
|
||||
return limit, afterID, true
|
||||
}
|
||||
|
||||
@@ -5,33 +5,35 @@ import (
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
|
||||
)
|
||||
|
||||
type HealthHandler struct {
|
||||
*BaseHandler
|
||||
router router.Router
|
||||
server Server
|
||||
}
|
||||
|
||||
func NewHealthHandler(base *BaseHandler, server Server) Handler {
|
||||
func NewHealthHandler(r router.Router, server Server) Handler {
|
||||
return &HealthHandler{
|
||||
BaseHandler: base,
|
||||
server: server,
|
||||
router: r,
|
||||
server: server,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *HealthHandler) RegisterRoutes() {
|
||||
h.router.Get("/health/ready", h.Ready)
|
||||
h.router.Get("/health/live", h.Live)
|
||||
h.router.Public(http.MethodGet, "/health/ready", h.Ready)
|
||||
h.router.Public(http.MethodGet, "/health/live", h.Live)
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Live(w http.ResponseWriter, _ *http.Request) {
|
||||
h.JSONResponse(w, http.StatusOK, contracts.Health{Status: contracts.Ok})
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.Health{Status: contracts.Ok})
|
||||
}
|
||||
|
||||
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.server.Ready() {
|
||||
h.JSONError(r.Context(), w, apperr.New(apperr.CodeUnavailable, "server is not ready"))
|
||||
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeUnavailable, "server is not ready"))
|
||||
return
|
||||
}
|
||||
h.JSONResponse(w, http.StatusOK, contracts.Health{Status: contracts.Ok})
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.Health{Status: contracts.Ok})
|
||||
}
|
||||
|
||||
@@ -1,50 +1 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func NewRouter() chi.Router {
|
||||
r := chi.NewRouter()
|
||||
r.Use(requestIdMiddleware, loggingMiddleware)
|
||||
return r
|
||||
}
|
||||
|
||||
func requestIdMiddleware(next http.Handler) http.Handler {
|
||||
fn := func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
requestID := uuid.New()
|
||||
w.Header().Set(HeaderRequestID, requestID.String())
|
||||
ctx = context.WithValue(ctx, HeaderRequestID, requestID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
}
|
||||
return http.HandlerFunc(fn)
|
||||
}
|
||||
|
||||
func loggingMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
started := time.Now()
|
||||
wrapped := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
next.ServeHTTP(wrapped, r)
|
||||
|
||||
status := wrapped.Status()
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
slog.InfoContext(r.Context(), "http request",
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", status,
|
||||
"duration", time.Since(started),
|
||||
"bytes", wrapped.BytesWritten(),
|
||||
"request_id", w.Header().Get(HeaderRequestID),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3,64 +3,87 @@ package http
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/inmemory"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/validator"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/user"
|
||||
)
|
||||
|
||||
type UserHandler struct {
|
||||
*BaseHandler
|
||||
router router.Router
|
||||
provider jwtprovider.Provider
|
||||
validator *validator.ValidatorImpl
|
||||
|
||||
users inmemory.UserCache
|
||||
user user.API
|
||||
}
|
||||
|
||||
func NewUserHandler(base *BaseHandler, users inmemory.UserCache) Handler {
|
||||
func NewUserHandler(r router.Router, provider jwtprovider.Provider, v *validator.ValidatorImpl, api user.API) Handler {
|
||||
return &UserHandler{
|
||||
BaseHandler: base,
|
||||
users: users,
|
||||
router: r,
|
||||
provider: provider,
|
||||
validator: v,
|
||||
user: api,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *UserHandler) RegisterRoutes() {
|
||||
h.router.Post("/api/v1/users", h.Create)
|
||||
h.router.Get("/api/v1/users/me", h.GetMe)
|
||||
h.router.Public(http.MethodPost, "/api/v1/users", h.Create)
|
||||
h.router.Private(http.MethodGet, "/api/v1/users/me", h.GetMe)
|
||||
}
|
||||
|
||||
func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
var req contracts.CreateUser
|
||||
if !h.Decode(w, r, &req) || !h.Validate(w, r, &req) {
|
||||
if !framework.Decode(w, r, &req) || !framework.Validate(w, r, h.validator, &req) {
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.users.Create(ctx, dto.CreateUser{
|
||||
toCreate := dto.CreateUser{
|
||||
Username: req.Username,
|
||||
DisplayName: req.DisplayName,
|
||||
})
|
||||
}
|
||||
|
||||
if req.Password != nil {
|
||||
toCreate.Password = *req.Password
|
||||
}
|
||||
|
||||
resp, err := h.user.Create(ctx, toCreate)
|
||||
if err != nil {
|
||||
h.JSONError(ctx, w, err)
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
h.JSONResponse(w, http.StatusCreated, contracts.User{
|
||||
CreatedAt: user.CreatedAt,
|
||||
DisplayName: user.DisplayName,
|
||||
Id: user.ID,
|
||||
Username: user.Username,
|
||||
framework.JSONResponse(w, http.StatusCreated, contracts.User{
|
||||
CreatedAt: resp.CreatedAt,
|
||||
DisplayName: resp.DisplayName,
|
||||
Id: resp.ID,
|
||||
Username: resp.Username,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *UserHandler) GetMe(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := h.authenticatedUser(w, r, h.users)
|
||||
if !ok {
|
||||
ctx := r.Context()
|
||||
|
||||
userData, err := framework.ParseToken(r, h.provider)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
h.JSONResponse(w, http.StatusOK, contracts.User{
|
||||
CreatedAt: user.CreatedAt,
|
||||
DisplayName: user.DisplayName,
|
||||
Id: user.ID,
|
||||
Username: user.Username,
|
||||
resp, err := h.user.GetByID(ctx, userData.UserID)
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
return
|
||||
}
|
||||
|
||||
framework.JSONResponse(w, http.StatusOK, contracts.User{
|
||||
CreatedAt: resp.CreatedAt,
|
||||
DisplayName: resp.DisplayName,
|
||||
Id: resp.ID,
|
||||
Username: resp.Username,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,149 +0,0 @@
|
||||
package inmemory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
)
|
||||
|
||||
const chatCacheName = "CHATS_CACHE"
|
||||
|
||||
type ChatCache interface {
|
||||
Create(ctx context.Context, input dto.CreateChat) (dto.Chat, error)
|
||||
GetForMember(ctx context.Context, chatID, userID uuid.UUID) (dto.Chat, error)
|
||||
ListForMember(ctx context.Context, userID uuid.UUID, limit *int, afterID *uuid.UUID) (dto.Page[dto.Chat], error)
|
||||
}
|
||||
|
||||
type chatCache struct {
|
||||
mu sync.RWMutex
|
||||
store *CopyAndWriteCache[uuid.UUID, dto.Chat]
|
||||
users UserCache
|
||||
}
|
||||
|
||||
func NewChatCache(users UserCache) ChatCache {
|
||||
if users == nil {
|
||||
panic("chat cache requires a user repository")
|
||||
}
|
||||
return &chatCache{
|
||||
store: NewCopyAndWriteCache[uuid.UUID, dto.Chat](chatCacheName),
|
||||
users: users,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *chatCache) Create(ctx context.Context, input dto.CreateChat) (dto.Chat, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.Chat{}, err
|
||||
}
|
||||
if strings.TrimSpace(input.Title) == "" || utf8.RuneCountInString(input.Title) > 100 ||
|
||||
len(input.MemberIDs) < 1 || len(input.MemberIDs) > 100 {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeInvalidRequest, "invalid chat fields")
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, len(input.MemberIDs))
|
||||
for _, memberID := range input.MemberIDs {
|
||||
if memberID == uuid.Nil {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeInvalidRequest, "invalid chat member")
|
||||
}
|
||||
if _, duplicate := seen[memberID]; duplicate {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeInvalidRequest, "duplicate chat member")
|
||||
}
|
||||
seen[memberID] = struct{}{}
|
||||
if _, err := c.users.GetByID(ctx, memberID); err != nil {
|
||||
if appErr, ok := apperr.As(err); ok && appErr.Code() == apperr.CodeNotFound {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeInvalidRequest, "unknown chat member")
|
||||
}
|
||||
return dto.Chat{}, err
|
||||
}
|
||||
}
|
||||
if _, included := seen[input.CreatorID]; !included {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeInvalidRequest, "creator must be a chat member")
|
||||
}
|
||||
|
||||
id, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
return dto.Chat{}, apperr.Wrap(err, apperr.CodeInternalError, "generate chat ID")
|
||||
}
|
||||
chat := dto.Chat{
|
||||
ID: id,
|
||||
Title: input.Title,
|
||||
MemberIDs: append([]uuid.UUID(nil), input.MemberIDs...),
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if !c.store.Store(chat.ID, chat) {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeInternalError, "store chat")
|
||||
}
|
||||
return cloneChat(chat), nil
|
||||
}
|
||||
|
||||
func (c *chatCache) GetForMember(ctx context.Context, chatID, userID uuid.UUID) (dto.Chat, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.Chat{}, err
|
||||
}
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
chat, ok := c.store.Get(chatID)
|
||||
if !ok || !slices.Contains(chat.MemberIDs, userID) {
|
||||
return dto.Chat{}, apperr.New(apperr.CodeNotFound, "chat not found")
|
||||
}
|
||||
return cloneChat(chat), nil
|
||||
}
|
||||
|
||||
func (c *chatCache) ListForMember(ctx context.Context, userID uuid.UUID, limit *int, afterID *uuid.UUID) (dto.Page[dto.Chat], error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.Page[dto.Chat]{}, err
|
||||
}
|
||||
pageSize, err := pageLimit(limit)
|
||||
if err != nil {
|
||||
return dto.Page[dto.Chat]{}, err
|
||||
}
|
||||
|
||||
c.mu.RLock()
|
||||
all := c.store.GetList()
|
||||
chats := make([]dto.Chat, 0, len(all))
|
||||
for _, chat := range all {
|
||||
if slices.Contains(chat.MemberIDs, userID) {
|
||||
chats = append(chats, cloneChat(chat))
|
||||
}
|
||||
}
|
||||
c.mu.RUnlock()
|
||||
|
||||
sort.Slice(chats, func(i, j int) bool {
|
||||
return lessKey(chats[i].CreatedAt, chats[i].ID, chats[j].CreatedAt, chats[j].ID)
|
||||
})
|
||||
start := 0
|
||||
if afterID != nil {
|
||||
start = -1
|
||||
for i, chat := range chats {
|
||||
if chat.ID == *afterID {
|
||||
start = i + 1
|
||||
break
|
||||
}
|
||||
}
|
||||
if start < 0 {
|
||||
return dto.Page[dto.Chat]{}, apperr.New(apperr.CodeInvalidRequest, "invalid cursor")
|
||||
}
|
||||
}
|
||||
end := min(start+pageSize, len(chats))
|
||||
page := dto.Page[dto.Chat]{Items: chats[start:end]}
|
||||
if end < len(chats) {
|
||||
id := chats[end-1].ID
|
||||
page.NextCursorID = &id
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func cloneChat(chat dto.Chat) dto.Chat {
|
||||
chat.MemberIDs = append([]uuid.UUID(nil), chat.MemberIDs...)
|
||||
return chat
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
package inmemory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
)
|
||||
|
||||
const MessageCacheName = "MESSAGE_CACHE"
|
||||
|
||||
type MessageCache interface {
|
||||
Create(ctx context.Context, input dto.CreateMessage) (dto.Message, error)
|
||||
ListForChat(ctx context.Context, chatID, userID uuid.UUID, limit *int, afterID *uuid.UUID) (dto.Page[dto.Message], error)
|
||||
}
|
||||
|
||||
type messageCache struct {
|
||||
mu sync.RWMutex
|
||||
store *CopyAndWriteCache[uuid.UUID, dto.Message]
|
||||
byChat map[uuid.UUID][]dto.Message
|
||||
chats ChatCache
|
||||
}
|
||||
|
||||
func NewMessageCache(chats ChatCache) MessageCache {
|
||||
if chats == nil {
|
||||
panic("message cache requires a chat repository")
|
||||
}
|
||||
return &messageCache{
|
||||
store: NewCopyAndWriteCache[uuid.UUID, dto.Message](MessageCacheName),
|
||||
byChat: make(map[uuid.UUID][]dto.Message),
|
||||
chats: chats,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *messageCache) Create(ctx context.Context, input dto.CreateMessage) (dto.Message, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.Message{}, err
|
||||
}
|
||||
if _, err := c.chats.GetForMember(ctx, input.ChatID, input.SenderID); err != nil {
|
||||
return dto.Message{}, err
|
||||
}
|
||||
if strings.TrimSpace(input.Text) == "" || utf8.RuneCountInString(input.Text) > 4000 {
|
||||
return dto.Message{}, apperr.New(apperr.CodeInvalidRequest, "invalid message text")
|
||||
}
|
||||
|
||||
id, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
return dto.Message{}, apperr.Wrap(err, apperr.CodeInternalError, "generate message ID")
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
message := dto.Message{
|
||||
ID: id,
|
||||
ChatID: input.ChatID,
|
||||
SenderID: input.SenderID,
|
||||
Text: input.Text,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
if !c.store.Store(message.ID, message) {
|
||||
return dto.Message{}, apperr.New(apperr.CodeInternalError, "store message")
|
||||
}
|
||||
messages := c.byChat[message.ChatID]
|
||||
index := sort.Search(len(messages), func(i int) bool {
|
||||
return !lessKey(messages[i].CreatedAt, messages[i].ID, message.CreatedAt, message.ID)
|
||||
})
|
||||
messages = append(messages, dto.Message{})
|
||||
copy(messages[index+1:], messages[index:])
|
||||
messages[index] = message
|
||||
c.byChat[message.ChatID] = messages
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (c *messageCache) ListForChat(ctx context.Context, chatID, userID uuid.UUID, limit *int, afterID *uuid.UUID) (dto.Page[dto.Message], error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.Page[dto.Message]{}, err
|
||||
}
|
||||
if _, err := c.chats.GetForMember(ctx, chatID, userID); err != nil {
|
||||
return dto.Page[dto.Message]{}, err
|
||||
}
|
||||
pageSize, err := pageLimit(limit)
|
||||
if err != nil {
|
||||
return dto.Page[dto.Message]{}, err
|
||||
}
|
||||
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
messages := c.byChat[chatID]
|
||||
start := 0
|
||||
if afterID != nil {
|
||||
cursor, ok := c.store.Get(*afterID)
|
||||
if !ok || cursor.ChatID != chatID {
|
||||
return dto.Page[dto.Message]{}, apperr.New(apperr.CodeInvalidRequest, "invalid cursor")
|
||||
}
|
||||
start = sort.Search(len(messages), func(i int) bool {
|
||||
return lessKey(cursor.CreatedAt, cursor.ID, messages[i].CreatedAt, messages[i].ID)
|
||||
})
|
||||
}
|
||||
end := min(start+pageSize, len(messages))
|
||||
items := make([]dto.Message, end-start)
|
||||
copy(items, messages[start:end])
|
||||
page := dto.Page[dto.Message]{Items: items}
|
||||
if end < len(messages) {
|
||||
id := messages[end-1].ID
|
||||
page.NextCursorID = &id
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package inmemory
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
)
|
||||
|
||||
func pageLimit(rawLimit *int) (int, error) {
|
||||
limit := 50
|
||||
if rawLimit != nil {
|
||||
limit = *rawLimit
|
||||
}
|
||||
if limit < 1 || limit > 100 {
|
||||
return 0, apperr.New(apperr.CodeInvalidRequest, "invalid limit")
|
||||
}
|
||||
return limit, nil
|
||||
}
|
||||
|
||||
func lessKey(leftTime time.Time, leftID uuid.UUID, rightTime time.Time, rightID uuid.UUID) bool {
|
||||
if !leftTime.Equal(rightTime) {
|
||||
return leftTime.Before(rightTime)
|
||||
}
|
||||
return bytes.Compare(leftID[:], rightID[:]) < 0
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
package inmemory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
)
|
||||
|
||||
const UserCacheName = "USERS_CACHE"
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
type UserCache interface {
|
||||
Create(ctx context.Context, input dto.CreateUser) (dto.User, error)
|
||||
GetByID(ctx context.Context, id uuid.UUID) (dto.User, error)
|
||||
GetByUsername(ctx context.Context, username string) (dto.User, error)
|
||||
}
|
||||
|
||||
type userCache struct {
|
||||
mu sync.RWMutex
|
||||
store *CopyAndWriteCache[uuid.UUID, dto.User]
|
||||
byUsername map[string]uuid.UUID
|
||||
}
|
||||
|
||||
func NewUserCache() UserCache {
|
||||
return &userCache{
|
||||
store: NewCopyAndWriteCache[uuid.UUID, dto.User](UserCacheName),
|
||||
byUsername: make(map[string]uuid.UUID),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *userCache) Create(ctx context.Context, input dto.CreateUser) (dto.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.User{}, err
|
||||
}
|
||||
if !usernamePattern.MatchString(input.Username) ||
|
||||
strings.TrimSpace(input.DisplayName) == "" ||
|
||||
utf8.RuneCountInString(input.DisplayName) > 100 {
|
||||
return dto.User{}, apperr.New(apperr.CodeInvalidRequest, "invalid user fields")
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if _, exists := c.byUsername[input.Username]; exists {
|
||||
return dto.User{}, apperr.New(apperr.CodeConflict, "username already exists")
|
||||
}
|
||||
|
||||
id, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
return dto.User{}, apperr.Wrap(err, apperr.CodeInternalError, "generate user ID")
|
||||
}
|
||||
user := dto.User{
|
||||
ID: id,
|
||||
Username: input.Username,
|
||||
DisplayName: input.DisplayName,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
if !c.store.Store(user.ID, user) {
|
||||
return dto.User{}, apperr.New(apperr.CodeInternalError, "store user")
|
||||
}
|
||||
c.byUsername[user.Username] = user.ID
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (c *userCache) GetByID(ctx context.Context, id uuid.UUID) (dto.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.User{}, err
|
||||
}
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
user, ok := c.store.Get(id)
|
||||
if !ok {
|
||||
return dto.User{}, apperr.New(apperr.CodeNotFound, "user not found")
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (c *userCache) GetByUsername(ctx context.Context, username string) (dto.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.User{}, err
|
||||
}
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
id, ok := c.byUsername[username]
|
||||
if !ok {
|
||||
return dto.User{}, apperr.New(apperr.CodeNotFound, "user not found")
|
||||
}
|
||||
user, ok := c.store.Get(id)
|
||||
if !ok {
|
||||
return dto.User{}, apperr.New(apperr.CodeInternalError, "user index is inconsistent")
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgerrcode"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
)
|
||||
|
||||
type ChatsRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewChatsRepo(pool *pgxpool.Pool) *ChatsRepo {
|
||||
return &ChatsRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *ChatsRepo) CreateTx(ctx context.Context, tx pgx.Tx, req dto.Chat) error {
|
||||
const insertChat = `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`
|
||||
if _, err := tx.Exec(ctx, insertChat, req.ID, req.Title, req.CreatedAt); err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to create chat")
|
||||
}
|
||||
const insertMembers = `INSERT INTO chat_members (chat_id, user_id)
|
||||
SELECT $1, user_id FROM unnest($2::uuid[]) AS members(user_id)`
|
||||
if _, err := tx.Exec(ctx, insertMembers, req.ID, req.MemberIDs); err != nil {
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok &&
|
||||
pgErr.Code == pgerrcode.ForeignKeyViolation && pgErr.ConstraintName == "chat_members_user_fk" {
|
||||
return apperr.Wrap(err, apperr.CodeBadRequest, "unknown chat member")
|
||||
}
|
||||
return apperr.WrapPostgres(err, "failed to create chat members")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *ChatsRepo) GetForMember(ctx context.Context, req dto.ChatMember) (*dto.Chat, error) {
|
||||
const query = `SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id)
|
||||
FROM chats c
|
||||
WHERE c.id = $1
|
||||
AND EXISTS (SELECT 1 FROM chat_members access WHERE access.chat_id = c.id AND access.user_id = $2)`
|
||||
return scanChat(r.pool.QueryRow(ctx, query, req.ChatID, req.UserID))
|
||||
}
|
||||
|
||||
func (r *ChatsRepo) ListForMember(ctx context.Context, userID uuid.UUID, page dto.PageQuery) ([]dto.Chat, error) {
|
||||
query := `WITH page AS MATERIALIZED (
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c JOIN chat_members access ON access.chat_id = c.id
|
||||
WHERE access.user_id = $1`
|
||||
args := []any{userID, page.Limit}
|
||||
if page.After != nil {
|
||||
query += ` AND (c.created_at, c.id) > ($3, $4)`
|
||||
args = append(args, page.After.CreatedAt, page.After.ID)
|
||||
}
|
||||
query += ` ORDER BY c.created_at, c.id LIMIT $2
|
||||
)
|
||||
SELECT p.id, p.title, p.created_at,
|
||||
ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = p.id ORDER BY m.user_id)
|
||||
FROM page p ORDER BY p.created_at, p.id`
|
||||
rows, err := r.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to list chats")
|
||||
}
|
||||
defer rows.Close()
|
||||
chats := make([]dto.Chat, 0)
|
||||
for rows.Next() {
|
||||
chat, err := scanChat(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
chats = append(chats, *chat)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to list chats")
|
||||
}
|
||||
return chats, nil
|
||||
}
|
||||
|
||||
func scanChat(row pgx.Row) (*dto.Chat, error) {
|
||||
var chat dto.Chat
|
||||
if err := row.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to get chat")
|
||||
}
|
||||
return &chat, nil
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgerrcode"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
)
|
||||
|
||||
type MessagesRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewMessagesRepo(pool *pgxpool.Pool) *MessagesRepo {
|
||||
return &MessagesRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *MessagesRepo) Create(ctx context.Context, req dto.Message) error {
|
||||
const query = `INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1, $2, $3, $4, $5)`
|
||||
if _, err := r.pool.Exec(ctx, query, req.ID, req.ChatID, req.SenderID, req.Text, req.CreatedAt); err != nil {
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok &&
|
||||
pgErr.Code == pgerrcode.ForeignKeyViolation && pgErr.ConstraintName == "messages_sender_member_fk" {
|
||||
return apperr.Wrap(err, apperr.CodeNotFound, "chat not found")
|
||||
}
|
||||
return apperr.WrapPostgres(err, "failed to create message")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MessagesRepo) GetByIDForChat(ctx context.Context, chatID, messageID uuid.UUID) (*dto.Message, error) {
|
||||
const query = `SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1 AND id = $2`
|
||||
return scanMessage(r.pool.QueryRow(ctx, query, chatID, messageID))
|
||||
}
|
||||
|
||||
func (r *MessagesRepo) ListForChat(ctx context.Context, chatID uuid.UUID, page dto.PageQuery) ([]dto.Message, error) {
|
||||
query := `SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1`
|
||||
args := []any{chatID, page.Limit}
|
||||
if page.After != nil {
|
||||
query += ` AND (created_at, id) > ($3, $4)`
|
||||
args = append(args, page.After.CreatedAt, page.After.ID)
|
||||
}
|
||||
query += ` ORDER BY created_at, id LIMIT $2`
|
||||
rows, err := r.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to list messages")
|
||||
}
|
||||
defer rows.Close()
|
||||
messages := make([]dto.Message, 0)
|
||||
for rows.Next() {
|
||||
message, err := scanMessage(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
messages = append(messages, *message)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to list messages")
|
||||
}
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
func scanMessage(row pgx.Row) (*dto.Message, error) {
|
||||
var message dto.Message
|
||||
if err := row.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to get message")
|
||||
}
|
||||
return &message, nil
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
|
||||
)
|
||||
|
||||
type RefreshTokensRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewRefreshTokensRepo(pool *pgxpool.Pool) *RefreshTokensRepo {
|
||||
return &RefreshTokensRepo{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) Create(ctx context.Context, req dto.StoredRefreshToken) error {
|
||||
return r.create(ctx, r.pool, req)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) CreateTx(ctx context.Context, tx pgx.Tx, req dto.StoredRefreshToken) error {
|
||||
return r.create(ctx, tx, req)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) GetByID(ctx context.Context, id uuid.UUID) (*dto.StoredRefreshToken, error) {
|
||||
return r.getByID(ctx, r.pool, id, false)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) GetByIDTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.StoredRefreshToken, error) {
|
||||
return r.getByID(ctx, tx, id, false)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) GetByIDForUpdate(ctx context.Context, id uuid.UUID) (*dto.StoredRefreshToken, error) {
|
||||
return r.getByID(ctx, r.pool, id, true)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) GetByIDForUpdateTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.StoredRefreshToken, error) {
|
||||
return r.getByID(ctx, tx, id, true)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) Revoke(ctx context.Context, req dto.RevokeRefreshToken) error {
|
||||
return r.revoke(ctx, r.pool, req)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) RevokeTx(ctx context.Context, tx pgx.Tx, req dto.RevokeRefreshToken) error {
|
||||
return r.revoke(ctx, tx, req)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) RevokeAllByUserID(ctx context.Context, req dto.RevokeRefreshTokensByUserID) error {
|
||||
return r.revokeAllByUserID(ctx, r.pool, req)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) RevokeAllByUserIDTx(ctx context.Context, tx pgx.Tx, req dto.RevokeRefreshTokensByUserID) error {
|
||||
return r.revokeAllByUserID(ctx, tx, req)
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) DeleteExpired(ctx context.Context) error {
|
||||
const query = `
|
||||
DELETE FROM refresh_tokens
|
||||
WHERE expires_at < $1`
|
||||
|
||||
_, err := r.pool.Exec(ctx, query, time.Now())
|
||||
if err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to delete expired refresh tokens")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) create(ctx context.Context, conn postgres.Conn, req dto.StoredRefreshToken) error {
|
||||
const query = `INSERT INTO refresh_tokens (id,
|
||||
user_id,
|
||||
token_hash,
|
||||
user_agent,
|
||||
ip_address,
|
||||
role,
|
||||
expires_at,
|
||||
created_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`
|
||||
|
||||
ct, err := conn.Exec(
|
||||
ctx,
|
||||
query,
|
||||
req.ID,
|
||||
req.UserID,
|
||||
req.TokenHash,
|
||||
req.UserAgent,
|
||||
req.IPAddress,
|
||||
req.Role,
|
||||
req.ExpiresAt,
|
||||
req.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to create refresh token")
|
||||
}
|
||||
|
||||
if ct.RowsAffected() == 0 {
|
||||
return apperr.New(apperr.CodeAlreadyExists, "refresh token already exists")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) getByID(ctx context.Context, conn postgres.Conn, id uuid.UUID, lock bool) (*dto.StoredRefreshToken, error) {
|
||||
const query = `SELECT id,
|
||||
user_id,
|
||||
token_hash,
|
||||
user_agent,
|
||||
ip_address,
|
||||
role,
|
||||
expires_at,
|
||||
revoked_at,
|
||||
created_at
|
||||
FROM refresh_tokens
|
||||
WHERE id = $1`
|
||||
const queryLock = `SELECT id,
|
||||
user_id,
|
||||
token_hash,
|
||||
user_agent,
|
||||
ip_address,
|
||||
role,
|
||||
expires_at,
|
||||
revoked_at,
|
||||
created_at
|
||||
FROM refresh_tokens
|
||||
WHERE id = $1 FOR UPDATE`
|
||||
|
||||
use := query
|
||||
if lock {
|
||||
use = queryLock
|
||||
}
|
||||
|
||||
var token dto.StoredRefreshToken
|
||||
err := conn.QueryRow(ctx, use, id).Scan(
|
||||
&token.ID,
|
||||
&token.UserID,
|
||||
&token.TokenHash,
|
||||
&token.UserAgent,
|
||||
&token.IPAddress,
|
||||
&token.Role,
|
||||
&token.ExpiresAt,
|
||||
&token.RevokedAt,
|
||||
&token.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to get refresh by id")
|
||||
}
|
||||
|
||||
return &token, nil
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) revoke(ctx context.Context, conn postgres.Conn, req dto.RevokeRefreshToken) error {
|
||||
const query = `
|
||||
UPDATE refresh_tokens
|
||||
SET revoked_at = $2
|
||||
WHERE id = $1
|
||||
AND revoked_at IS NULL`
|
||||
|
||||
ct, err := conn.Exec(ctx, query, req.ID, req.RevokedAt)
|
||||
if err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to revoke refresh token")
|
||||
}
|
||||
|
||||
if ct.RowsAffected() == 0 {
|
||||
return apperr.New(apperr.CodeNotFound, "refresh token not found")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RefreshTokensRepo) revokeAllByUserID(ctx context.Context, conn postgres.Conn, req dto.RevokeRefreshTokensByUserID) error {
|
||||
const query = `
|
||||
UPDATE refresh_tokens
|
||||
SET revoked_at = $2
|
||||
WHERE user_id = $1
|
||||
AND revoked_at IS NULL`
|
||||
|
||||
_, err := conn.Exec(ctx, query, req.UserID, req.RevokedAt)
|
||||
if err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to revoke refresh tokens")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgerrcode"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
|
||||
)
|
||||
|
||||
type UsersRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewUsersRepo(pool *pgxpool.Pool) *UsersRepo {
|
||||
return &UsersRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *UsersRepo) Create(ctx context.Context, req dto.CreateStoredUser) error {
|
||||
return r.create(ctx, r.pool, req)
|
||||
}
|
||||
|
||||
func (r *UsersRepo) CreateTx(ctx context.Context, tx pgx.Tx, req dto.CreateStoredUser) error {
|
||||
return r.create(ctx, tx, req)
|
||||
}
|
||||
|
||||
func (r *UsersRepo) GetByID(ctx context.Context, id uuid.UUID) (*dto.User, error) {
|
||||
return r.getByID(ctx, r.pool, id)
|
||||
}
|
||||
|
||||
func (r *UsersRepo) GetByIDTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.User, error) {
|
||||
return r.getByID(ctx, tx, id)
|
||||
}
|
||||
|
||||
func (r *UsersRepo) GetByUsername(ctx context.Context, username string) (*dto.User, error) {
|
||||
const query = `SELECT id, username, name, created_at FROM users WHERE username = $1`
|
||||
return scanUser(r.pool.QueryRow(ctx, query, username))
|
||||
}
|
||||
|
||||
func (r *UsersRepo) GetCredentialsByUsername(ctx context.Context, username string) (*dto.UserCredentials, error) {
|
||||
const query = `SELECT id, username, name, created_at, password_hash FROM users WHERE username = $1`
|
||||
|
||||
var credentials dto.UserCredentials
|
||||
err := r.pool.QueryRow(ctx, query, username).Scan(
|
||||
&credentials.User.ID,
|
||||
&credentials.User.Username,
|
||||
&credentials.User.DisplayName,
|
||||
&credentials.User.CreatedAt,
|
||||
&credentials.PasswordHash,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to get user credentials")
|
||||
}
|
||||
return &credentials, nil
|
||||
}
|
||||
|
||||
func (r *UsersRepo) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
const query = `DELETE FROM users WHERE id = $1`
|
||||
|
||||
ct, err := r.pool.Exec(ctx, query, id)
|
||||
if err != nil {
|
||||
return apperr.WrapPostgres(err, "failed to delete user")
|
||||
}
|
||||
if ct.RowsAffected() == 0 {
|
||||
return apperr.New(apperr.CodeNotFound, "user not found")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *UsersRepo) create(ctx context.Context, conn postgres.Conn, req dto.CreateStoredUser) error {
|
||||
const query = `INSERT INTO users (id, username, name, password_hash, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)`
|
||||
|
||||
_, err := conn.Exec(ctx, query, req.ID, req.Username, req.DisplayName, req.PasswordHash, req.CreatedAt, req.UpdatedAt)
|
||||
if err != nil {
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok &&
|
||||
pgErr.Code == pgerrcode.UniqueViolation && pgErr.ConstraintName == "users_username_unique" {
|
||||
return apperr.Wrap(err, apperr.CodeConflict, "username already exists")
|
||||
}
|
||||
return apperr.WrapPostgres(err, "failed to create user")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *UsersRepo) getByID(ctx context.Context, conn postgres.Conn, id uuid.UUID) (*dto.User, error) {
|
||||
const query = `SELECT id, username, name, created_at FROM users WHERE id = $1`
|
||||
return scanUser(conn.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
func scanUser(row pgx.Row) (*dto.User, error) {
|
||||
var user dto.User
|
||||
if err := row.Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to get user")
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
|
||||
"github.com/spf13/viper"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/environment"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/environment"
|
||||
)
|
||||
|
||||
type Application struct {
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
"go.uber.org/multierr"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/environment"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/environment"
|
||||
)
|
||||
|
||||
var defaultConfig = &Config{
|
||||
@@ -44,14 +43,6 @@ var defaultConfig = &Config{
|
||||
PublicKeyPath: "certs/private.pem",
|
||||
PrivateKeyPath: "certs/public.pem",
|
||||
},
|
||||
Cookies: &Cookies{
|
||||
Enabled: true,
|
||||
Domain: "",
|
||||
Path: "/",
|
||||
Secure: true,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
AllowedOrigins: []string{"http:localhost:8080"},
|
||||
},
|
||||
Application: &Application{
|
||||
LogLevel: "info",
|
||||
ShutdownTimeout: 10 * time.Second,
|
||||
@@ -65,7 +56,6 @@ type Config struct {
|
||||
Postgres *Postgres
|
||||
Redis *Redis
|
||||
JWT *JWT
|
||||
Cookies *Cookies
|
||||
Application *Application
|
||||
}
|
||||
|
||||
@@ -93,7 +83,6 @@ func (c *Config) Validate() error {
|
||||
c.Postgres.Validate(),
|
||||
c.JWT.Validate(),
|
||||
c.Redis.Validate(),
|
||||
c.Cookies.Validate(),
|
||||
c.Application.Validate(),
|
||||
)
|
||||
}
|
||||
@@ -104,7 +93,6 @@ func (c *Config) loadConfig(v *viper.Viper) error {
|
||||
c.Server.loadConfig(v),
|
||||
c.JWT.loadConfig(v),
|
||||
c.Redis.loadConfig(v),
|
||||
c.Cookies.loadConfig(v),
|
||||
c.Application.loadConfig(v),
|
||||
)
|
||||
}
|
||||
@@ -115,7 +103,6 @@ func (c *Config) copy() *Config {
|
||||
Postgres: c.Postgres.copy(),
|
||||
Redis: c.Redis.copy(),
|
||||
JWT: c.JWT.copy(),
|
||||
Cookies: c.Cookies.copy(),
|
||||
Application: c.Application.copy(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,33 +18,6 @@ type Server struct {
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
// LoadServer reads settings from environment variables and applies lab1 defaults.
|
||||
func LoadServer() (*Server, error) {
|
||||
v := viper.New()
|
||||
v.SetEnvPrefix("APP")
|
||||
v.AutomaticEnv()
|
||||
v.SetDefault("HOST", "0.0.0.0")
|
||||
v.SetDefault("PORT", 8080)
|
||||
v.SetDefault("READ_TIMEOUT", "5s")
|
||||
v.SetDefault("WRITE_TIMEOUT", "10s")
|
||||
v.SetDefault("IDLE_TIMEOUT", "60s")
|
||||
v.SetDefault("SHUTDOWN_TIMEOUT", "10s")
|
||||
v.SetDefault("ENABLED", true)
|
||||
|
||||
if err := v.BindEnv("HOST", "APP_HOST", "SERVER_HOST"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := v.BindEnv("PORT", "APP_PORT", "SERVER_PORT"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cfg := new(Server)
|
||||
if err := cfg.loadConfig(v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c *Server) Validate() error {
|
||||
if !c.Enabled {
|
||||
return nil
|
||||
|
||||
@@ -7,9 +7,7 @@ import (
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/authidentity"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/authprovider"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/role"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/role"
|
||||
)
|
||||
|
||||
// ---- Tokens ----
|
||||
@@ -92,53 +90,37 @@ type RevokeRefreshTokensByUserID struct {
|
||||
|
||||
// ---- Auth ----
|
||||
|
||||
type Session struct {
|
||||
ExpiresAt time.Time
|
||||
Token string
|
||||
TokenType string
|
||||
User User
|
||||
}
|
||||
|
||||
type Login struct {
|
||||
Email string
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
|
||||
type LoginResult struct {
|
||||
ExpiresAt time.Time
|
||||
TokenType string
|
||||
User User
|
||||
Tokens Tokens
|
||||
}
|
||||
|
||||
// UserCredentials is internal authentication data, never a public user response.
|
||||
type UserCredentials struct {
|
||||
User User
|
||||
PasswordHash string `json:"-"`
|
||||
}
|
||||
|
||||
type Logout struct {
|
||||
Token string
|
||||
}
|
||||
|
||||
type Register struct {
|
||||
Email string
|
||||
Password string
|
||||
RepeatPassword string
|
||||
}
|
||||
|
||||
// ---- Auth Identities ----
|
||||
|
||||
type AuthIdentity struct {
|
||||
ID uuid.UUID
|
||||
Role role.Role
|
||||
UserID uuid.UUID
|
||||
Provider authprovider.Type
|
||||
Identifier string
|
||||
PasswordHash *string
|
||||
Status authidentity.Status
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
type UpdateAuthIdentity struct {
|
||||
ID uuid.UUID
|
||||
Role *role.Role
|
||||
Provider *authprovider.Type
|
||||
Identifier *string
|
||||
PasswordHash *string
|
||||
Status *authidentity.Status
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type UpdateAuthIdentityPasswordHash struct {
|
||||
ID uuid.UUID
|
||||
PasswordHash string
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type UpdateAuthIdentityStatus struct {
|
||||
ID uuid.UUID
|
||||
Status authidentity.Status
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type GetAuthIdentityByRoleAndUserID struct {
|
||||
Role role.Role
|
||||
UserID uuid.UUID
|
||||
}
|
||||
|
||||
@@ -18,3 +18,14 @@ type CreateChat struct {
|
||||
Title string
|
||||
MemberIDs []uuid.UUID
|
||||
}
|
||||
|
||||
type ChatMember struct {
|
||||
UserID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
}
|
||||
|
||||
type ChatFilters struct {
|
||||
UserID uuid.UUID
|
||||
Limit *int
|
||||
AfterID *uuid.UUID
|
||||
}
|
||||
|
||||
@@ -19,3 +19,10 @@ type CreateMessage struct {
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
}
|
||||
|
||||
type MessageFilters struct {
|
||||
ChatID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
Limit *int
|
||||
AfterID *uuid.UUID
|
||||
}
|
||||
|
||||
@@ -1,9 +1,25 @@
|
||||
package dto
|
||||
|
||||
import "github.com/google/uuid"
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Page is a page of records with the ID to use for the next page.
|
||||
type Page[T any] struct {
|
||||
Items []T
|
||||
NextCursorID *uuid.UUID
|
||||
}
|
||||
|
||||
// PagePosition is a resolved database cursor, ordered by creation time and ID.
|
||||
type PagePosition struct {
|
||||
CreatedAt time.Time
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
// PageQuery is prepared by a service; Limit includes the lookahead row.
|
||||
type PageQuery struct {
|
||||
Limit int
|
||||
After *PagePosition
|
||||
}
|
||||
|
||||
@@ -16,4 +16,15 @@ type User struct {
|
||||
type CreateUser struct {
|
||||
Username string
|
||||
DisplayName string
|
||||
Password string
|
||||
}
|
||||
|
||||
// CreateStoredUser contains the prepared database record, never a plaintext password.
|
||||
type CreateStoredUser struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
PasswordHash string `json:"-"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
@@ -10,7 +10,8 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
DevUserScopes = "devUser.Scopes"
|
||||
BasicAuthScopes = "basicAuth.Scopes"
|
||||
BearerAuthScopes = "bearerAuth.Scopes"
|
||||
)
|
||||
|
||||
// Defines values for ErrorErrorCode.
|
||||
@@ -58,8 +59,9 @@ type CreateMessage struct {
|
||||
|
||||
// CreateUser defines model for CreateUser.
|
||||
type CreateUser struct {
|
||||
DisplayName string `json:"display_name"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password *string `json:"password,omitempty"`
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
// Error defines model for Error.
|
||||
@@ -97,6 +99,14 @@ type MessagePage struct {
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
// Session defines model for Session.
|
||||
type Session struct {
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
User User `json:"user"`
|
||||
}
|
||||
|
||||
// User defines model for User.
|
||||
type User struct {
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
package apperr
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/jackc/pgerrcode"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
grpcCodes "google.golang.org/grpc/codes"
|
||||
)
|
||||
|
||||
//go:generate stringer -type=Code -linecomment
|
||||
type Code uint16
|
||||
|
||||
const (
|
||||
// CodeBadRequest = {AppError: BAD_REQUEST, HTTP:400}
|
||||
CodeBadRequest Code = iota
|
||||
// CodePayloadTooLarge = {AppError: REQUEST_ENTITY_TOO_LARGE, HTTP:413}
|
||||
CodePayloadTooLarge
|
||||
// CodeValidation = {AppError: VALIDATION, HTTP:422}
|
||||
CodeValidation
|
||||
// CodeUnauthorized = {AppError: UNAUTHORIZED, HTTP:401}
|
||||
CodeUnauthorized
|
||||
// CodeForbidden = {AppError: FORBIDDEN, HTTP:403}
|
||||
CodeForbidden
|
||||
// CodeNotFound = {AppError: NOT_FOUND, HTTP:404}
|
||||
CodeNotFound
|
||||
// CodeAlreadyExists = {AppError: ALREADY_EXISTS, HTTP:409}
|
||||
CodeAlreadyExists
|
||||
// CodeConflict = {AppError: CONFLICT, HTTP:409}
|
||||
CodeConflict
|
||||
// CodeTooManyRequests = {AppError: TOO_MANY_REQUESTS, HTTP:429}
|
||||
CodeTooManyRequests
|
||||
// CodeTimeout = {AppError: TIMEOUT, HTTP:504}
|
||||
CodeTimeout
|
||||
// CodeInternal = {AppError: INTERNAL, HTTP:500}
|
||||
CodeInternal
|
||||
// CodeServiceUnavailable = {AppError: SERVICE_UNAVAILABLE, HTTP:503}
|
||||
CodeServiceUnavailable
|
||||
// CodeOK = {AppError: OK, HTTP:200}
|
||||
CodeOK
|
||||
// CodeLocked = {AppError: LOCKED, HTTP:423}
|
||||
CodeLocked
|
||||
// CodeUnsupportedMediaType = {AppError: UNSUPPORTED_MEDIA_TYPE, HTTP:415}
|
||||
CodeUnsupportedMediaType
|
||||
// CodeUnavailable = {AppError: SERVICE_UNAVAILABLE, HTTP: 503}
|
||||
CodeUnavailable
|
||||
)
|
||||
|
||||
func (c Code) HTTPStatus() int {
|
||||
if status, ok := httpStatusByCode[c]; ok {
|
||||
return status
|
||||
}
|
||||
return http.StatusInternalServerError
|
||||
}
|
||||
|
||||
func (c Code) GRPCCode() grpcCodes.Code {
|
||||
if code, ok := grpcCodeByCode[c]; ok {
|
||||
return code
|
||||
}
|
||||
return grpcCodes.Internal
|
||||
}
|
||||
|
||||
func (c Code) PostgresCodes() []string {
|
||||
codes := postgresCodesByCode[c]
|
||||
if len(codes) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
cp := make([]string, len(codes))
|
||||
copy(cp, codes)
|
||||
return cp
|
||||
}
|
||||
|
||||
func (c Code) PostgresCode() string {
|
||||
codes := c.PostgresCodes()
|
||||
if len(codes) == 0 {
|
||||
return ""
|
||||
}
|
||||
return codes[0]
|
||||
}
|
||||
|
||||
func CodeFromError(err error) Code {
|
||||
if err == nil {
|
||||
return CodeInternal
|
||||
}
|
||||
|
||||
var coded interface {
|
||||
Code() Code
|
||||
}
|
||||
if errors.As(err, &coded) {
|
||||
return coded.Code()
|
||||
}
|
||||
|
||||
if code, ok := codeFromRedisError(err, false, false); ok {
|
||||
return code
|
||||
}
|
||||
|
||||
return CodeFromPostgresError(err)
|
||||
}
|
||||
|
||||
func HTTPStatusFromError(err error) int {
|
||||
return CodeFromError(err).HTTPStatus()
|
||||
}
|
||||
|
||||
func GRPCCodeFromError(err error) grpcCodes.Code {
|
||||
return CodeFromError(err).GRPCCode()
|
||||
}
|
||||
|
||||
func CodeFromHTTPStatus(status int) Code {
|
||||
if code, ok := codeByHTTPStatus[status]; ok {
|
||||
return code
|
||||
}
|
||||
return CodeInternal
|
||||
}
|
||||
|
||||
func CodeFromGRPC(code grpcCodes.Code) Code {
|
||||
if appCode, ok := codeByGRPCCode[code]; ok {
|
||||
return appCode
|
||||
}
|
||||
return CodeInternal
|
||||
}
|
||||
|
||||
func CodeFromPostgres(pgCode string) Code {
|
||||
if code, ok := codeByPostgresCode[pgCode]; ok {
|
||||
return code
|
||||
}
|
||||
return CodeInternal
|
||||
}
|
||||
|
||||
func CodeFromPostgresError(err error) Code {
|
||||
if err == nil {
|
||||
return CodeInternal
|
||||
}
|
||||
|
||||
if code, ok := codeByPgxError[err]; ok {
|
||||
return code
|
||||
}
|
||||
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
|
||||
return CodeFromPostgres(pgErr.Code)
|
||||
}
|
||||
|
||||
return CodeInternal
|
||||
}
|
||||
|
||||
var (
|
||||
httpStatusByCode = map[Code]int{
|
||||
CodeBadRequest: http.StatusBadRequest,
|
||||
CodeUnauthorized: http.StatusUnauthorized,
|
||||
CodeForbidden: http.StatusForbidden,
|
||||
CodeNotFound: http.StatusNotFound,
|
||||
CodeAlreadyExists: http.StatusConflict,
|
||||
CodeConflict: http.StatusConflict,
|
||||
CodePayloadTooLarge: http.StatusRequestEntityTooLarge,
|
||||
CodeTooManyRequests: http.StatusTooManyRequests,
|
||||
CodeValidation: http.StatusUnprocessableEntity,
|
||||
CodeTimeout: http.StatusGatewayTimeout,
|
||||
CodeInternal: http.StatusInternalServerError,
|
||||
CodeServiceUnavailable: http.StatusServiceUnavailable,
|
||||
CodeUnsupportedMediaType: http.StatusUnsupportedMediaType,
|
||||
CodeUnavailable: http.StatusServiceUnavailable,
|
||||
CodeOK: http.StatusOK,
|
||||
CodeLocked: http.StatusLocked,
|
||||
}
|
||||
codeByHTTPStatus = map[int]Code{
|
||||
http.StatusBadRequest: CodeBadRequest,
|
||||
http.StatusUnauthorized: CodeUnauthorized,
|
||||
http.StatusForbidden: CodeForbidden,
|
||||
http.StatusNotFound: CodeNotFound,
|
||||
http.StatusConflict: CodeConflict,
|
||||
http.StatusRequestEntityTooLarge: CodePayloadTooLarge,
|
||||
http.StatusTooManyRequests: CodeTooManyRequests,
|
||||
http.StatusUnprocessableEntity: CodeValidation,
|
||||
http.StatusGatewayTimeout: CodeTimeout,
|
||||
http.StatusInternalServerError: CodeInternal,
|
||||
http.StatusServiceUnavailable: CodeServiceUnavailable,
|
||||
http.StatusOK: CodeOK,
|
||||
http.StatusLocked: CodeLocked,
|
||||
http.StatusUnsupportedMediaType: CodeUnavailable,
|
||||
}
|
||||
grpcCodeByCode = map[Code]grpcCodes.Code{
|
||||
CodeBadRequest: grpcCodes.InvalidArgument,
|
||||
CodePayloadTooLarge: grpcCodes.ResourceExhausted,
|
||||
CodeValidation: grpcCodes.InvalidArgument,
|
||||
CodeUnauthorized: grpcCodes.Unauthenticated,
|
||||
CodeForbidden: grpcCodes.PermissionDenied,
|
||||
CodeNotFound: grpcCodes.NotFound,
|
||||
CodeAlreadyExists: grpcCodes.AlreadyExists,
|
||||
CodeConflict: grpcCodes.Aborted,
|
||||
CodeTooManyRequests: grpcCodes.ResourceExhausted,
|
||||
CodeTimeout: grpcCodes.DeadlineExceeded,
|
||||
CodeInternal: grpcCodes.Internal,
|
||||
CodeServiceUnavailable: grpcCodes.Unavailable,
|
||||
CodeOK: grpcCodes.OK,
|
||||
CodeLocked: grpcCodes.FailedPrecondition,
|
||||
}
|
||||
codeByGRPCCode = map[grpcCodes.Code]Code{
|
||||
grpcCodes.InvalidArgument: CodeBadRequest,
|
||||
grpcCodes.ResourceExhausted: CodeTooManyRequests,
|
||||
grpcCodes.Unauthenticated: CodeUnauthorized,
|
||||
grpcCodes.PermissionDenied: CodeForbidden,
|
||||
grpcCodes.NotFound: CodeNotFound,
|
||||
grpcCodes.AlreadyExists: CodeAlreadyExists,
|
||||
grpcCodes.Aborted: CodeConflict,
|
||||
grpcCodes.FailedPrecondition: CodeLocked,
|
||||
grpcCodes.DeadlineExceeded: CodeTimeout,
|
||||
grpcCodes.Internal: CodeInternal,
|
||||
grpcCodes.Unimplemented: CodeInternal,
|
||||
grpcCodes.Unavailable: CodeServiceUnavailable,
|
||||
grpcCodes.OK: CodeOK,
|
||||
}
|
||||
postgresCodesByCode = map[Code][]string{
|
||||
CodeBadRequest: {
|
||||
pgerrcode.InvalidTextRepresentation,
|
||||
pgerrcode.InvalidParameterValue,
|
||||
},
|
||||
CodeValidation: {
|
||||
pgerrcode.NotNullViolation,
|
||||
pgerrcode.CheckViolation,
|
||||
pgerrcode.StringDataRightTruncationDataException,
|
||||
pgerrcode.NumericValueOutOfRange,
|
||||
},
|
||||
CodeNotFound: {
|
||||
pgerrcode.ForeignKeyViolation,
|
||||
},
|
||||
CodeAlreadyExists: {
|
||||
pgerrcode.UniqueViolation,
|
||||
},
|
||||
CodeConflict: {
|
||||
pgerrcode.ExclusionViolation,
|
||||
pgerrcode.SerializationFailure,
|
||||
pgerrcode.DeadlockDetected,
|
||||
},
|
||||
CodeLocked: {
|
||||
pgerrcode.LockNotAvailable,
|
||||
pgerrcode.ObjectInUse,
|
||||
},
|
||||
CodeTooManyRequests: {
|
||||
pgerrcode.TooManyConnections,
|
||||
},
|
||||
CodeTimeout: {
|
||||
pgerrcode.QueryCanceled,
|
||||
},
|
||||
CodeInternal: {
|
||||
pgerrcode.ConnectionException,
|
||||
pgerrcode.ConnectionFailure,
|
||||
pgerrcode.SQLClientUnableToEstablishSQLConnection,
|
||||
pgerrcode.SQLServerRejectedEstablishmentOfSQLConnection,
|
||||
pgerrcode.TransactionResolutionUnknown,
|
||||
},
|
||||
CodeServiceUnavailable: {
|
||||
pgerrcode.CannotConnectNow,
|
||||
},
|
||||
}
|
||||
codeByPostgresCode = buildCodeByPostgresCode(postgresCodesByCode)
|
||||
codeByPgxError = map[error]Code{
|
||||
pgx.ErrNoRows: CodeNotFound,
|
||||
pgx.ErrTxClosed: CodeInternal,
|
||||
pgx.ErrTxCommitRollback: CodeConflict,
|
||||
pgx.ErrTooManyRows: CodeInternal,
|
||||
}
|
||||
)
|
||||
|
||||
func buildCodeByPostgresCode(src map[Code][]string) map[string]Code {
|
||||
dst := make(map[string]Code, len(src))
|
||||
for code, pgCodes := range src {
|
||||
for _, pgCode := range pgCodes {
|
||||
dst[pgCode] = code
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// Code generated by "stringer -type=Code -linecomment"; DO NOT EDIT.
|
||||
|
||||
package apperr
|
||||
|
||||
import "strconv"
|
||||
|
||||
func _() {
|
||||
// An "invalid array index" compiler error signifies that the constant values have changed.
|
||||
// Re-run the stringer command to generate them again.
|
||||
var x [1]struct{}
|
||||
_ = x[CodeBadRequest-0]
|
||||
_ = x[CodePayloadTooLarge-1]
|
||||
_ = x[CodeValidation-2]
|
||||
_ = x[CodeUnauthorized-3]
|
||||
_ = x[CodeForbidden-4]
|
||||
_ = x[CodeNotFound-5]
|
||||
_ = x[CodeAlreadyExists-6]
|
||||
_ = x[CodeConflict-7]
|
||||
_ = x[CodeTooManyRequests-8]
|
||||
_ = x[CodeTimeout-9]
|
||||
_ = x[CodeInternal-10]
|
||||
_ = x[CodeServiceUnavailable-11]
|
||||
_ = x[CodeOK-12]
|
||||
_ = x[CodeLocked-13]
|
||||
}
|
||||
|
||||
const _Code_name = "CodeBadRequestCodePayloadTooLargeCodeValidationCodeUnauthorizedCodeForbiddenCodeNotFoundCodeAlreadyExistsCodeConflictCodeTooManyRequestsCodeTimeoutCodeInternalCodeServiceUnavailableCodeOKCodeLocked"
|
||||
|
||||
var _Code_index = [...]uint8{0, 14, 33, 47, 63, 76, 88, 105, 117, 136, 147, 159, 181, 187, 197}
|
||||
|
||||
func (i Code) String() string {
|
||||
idx := int(i) - 0
|
||||
if i < 0 || idx >= len(_Code_index)-1 {
|
||||
return "Code(" + strconv.FormatInt(int64(i), 10) + ")"
|
||||
}
|
||||
return _Code_name[_Code_index[idx]:_Code_index[idx+1]]
|
||||
}
|
||||
@@ -2,90 +2,96 @@ package apperr
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"fmt"
|
||||
|
||||
grpcCodes "google.golang.org/grpc/codes"
|
||||
)
|
||||
|
||||
// Code is the machine-readable error code used by the API contract.
|
||||
type Code string
|
||||
|
||||
const (
|
||||
CodeInvalidRequest Code = "invalid_request"
|
||||
CodeUnauthorized Code = "unauthorized"
|
||||
CodeNotFound Code = "not_found"
|
||||
CodeConflict Code = "conflict"
|
||||
CodePayloadTooLarge Code = "payload_too_large"
|
||||
CodeUnsupportedMediaType Code = "unsupported_media_type"
|
||||
CodeRateLimited Code = "rate_limited"
|
||||
CodeUnavailable Code = "unavailable"
|
||||
CodeInternalError Code = "internal_error"
|
||||
|
||||
CodeValidation Code = CodeInvalidRequest
|
||||
CodeBadRequest Code = CodeInvalidRequest
|
||||
CodeInternal Code = CodeInternalError
|
||||
)
|
||||
|
||||
func (c Code) HTTPStatus() int {
|
||||
switch c {
|
||||
case CodeInvalidRequest:
|
||||
return http.StatusBadRequest
|
||||
case CodeUnauthorized:
|
||||
return http.StatusUnauthorized
|
||||
case CodeNotFound:
|
||||
return http.StatusNotFound
|
||||
case CodeConflict:
|
||||
return http.StatusConflict
|
||||
case CodePayloadTooLarge:
|
||||
return http.StatusRequestEntityTooLarge
|
||||
case CodeUnsupportedMediaType:
|
||||
return http.StatusUnsupportedMediaType
|
||||
case CodeRateLimited:
|
||||
return http.StatusTooManyRequests
|
||||
case CodeUnavailable:
|
||||
return http.StatusServiceUnavailable
|
||||
default:
|
||||
return http.StatusInternalServerError
|
||||
}
|
||||
}
|
||||
|
||||
// AppError adds a public message and API code to an optional underlying error.
|
||||
type AppError struct {
|
||||
code Code
|
||||
message string
|
||||
cause error
|
||||
err error
|
||||
msg string
|
||||
code Code
|
||||
meta metadata
|
||||
}
|
||||
|
||||
func New(code Code, message string) *AppError {
|
||||
return &AppError{code: code, message: message}
|
||||
}
|
||||
|
||||
// Wrap returns nil for a nil cause.
|
||||
func Wrap(err error, code Code, message string) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
func New(code Code, msg string) error {
|
||||
return &AppError{
|
||||
msg: msg,
|
||||
code: code,
|
||||
meta: metadata{},
|
||||
}
|
||||
return &AppError{code: code, message: message, cause: err}
|
||||
}
|
||||
|
||||
func Wrap(err error, code Code, msg string) error {
|
||||
m := AppError{
|
||||
err: err,
|
||||
msg: msg,
|
||||
code: code,
|
||||
meta: metadata{},
|
||||
}
|
||||
return &m
|
||||
}
|
||||
|
||||
func WrapAppError(err error, msg string) error {
|
||||
m := AppError{
|
||||
err: err,
|
||||
msg: msg,
|
||||
code: CodeInternal,
|
||||
meta: metadata{},
|
||||
}
|
||||
|
||||
if mistake := As(err); mistake != nil {
|
||||
m.err = mistake
|
||||
m.code = mistake.code
|
||||
m.meta = mistake.meta
|
||||
}
|
||||
|
||||
return &m
|
||||
}
|
||||
|
||||
func As(err error) *AppError {
|
||||
if mistakeErr, ok := errors.AsType[*AppError](err); ok {
|
||||
return mistakeErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func CodeIs(err error, code Code) bool {
|
||||
if appErr := As(err); appErr != nil && appErr.Code() == code {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (e *AppError) Error() string {
|
||||
if e == nil {
|
||||
return "<nil>"
|
||||
return ""
|
||||
}
|
||||
if e.cause != nil {
|
||||
return e.message + ": " + e.cause.Error()
|
||||
|
||||
if e.err == nil {
|
||||
if e.msg != "" {
|
||||
return e.msg
|
||||
}
|
||||
return e.code.String()
|
||||
}
|
||||
return e.message
|
||||
|
||||
if e.msg == "" {
|
||||
return e.err.Error()
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s: %s", e.msg, e.err.Error())
|
||||
}
|
||||
|
||||
func (e *AppError) Unwrap() error {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return e.cause
|
||||
return e.err
|
||||
}
|
||||
|
||||
func (e *AppError) Code() Code {
|
||||
if e == nil {
|
||||
return CodeInternalError
|
||||
return CodeInternal
|
||||
}
|
||||
return e.code
|
||||
}
|
||||
@@ -94,29 +100,24 @@ func (e *AppError) Message() string {
|
||||
if e == nil {
|
||||
return ""
|
||||
}
|
||||
return e.message
|
||||
return e.msg
|
||||
}
|
||||
|
||||
// As finds an AppError even when it is wrapped with fmt.Errorf("...: %w", err).
|
||||
func As(err error) (*AppError, bool) {
|
||||
var appErr *AppError
|
||||
if !errors.As(err, &appErr) || appErr == nil {
|
||||
return nil, false
|
||||
func (e *AppError) Cause() error {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return appErr, true
|
||||
return e.err
|
||||
}
|
||||
|
||||
// Root is retained for existing HTTP handler call sites.
|
||||
func Root(err error) *AppError {
|
||||
appErr, _ := As(err)
|
||||
return appErr
|
||||
func (e *AppError) Metadata() Metadata {
|
||||
return e.meta
|
||||
}
|
||||
|
||||
// PublicMessage never exposes an unknown error or the cause of a server error.
|
||||
func PublicMessage(err error) string {
|
||||
appErr, ok := As(err)
|
||||
if !ok || appErr.Code().HTTPStatus() >= http.StatusInternalServerError {
|
||||
return "internal server error"
|
||||
}
|
||||
return appErr.Message()
|
||||
func (e *AppError) HTTPStatus() int {
|
||||
return e.Code().HTTPStatus()
|
||||
}
|
||||
|
||||
func (e *AppError) GRPCCode() grpcCodes.Code {
|
||||
return e.Code().GRPCCode()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package apperr
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var _ Metadata = (*metadata)(nil)
|
||||
|
||||
type Metadata interface {
|
||||
Get(key metakey) string
|
||||
Clone() map[metakey]string
|
||||
CloneToAnyMap() map[string]any
|
||||
String() string
|
||||
}
|
||||
|
||||
type metadata map[metakey]string
|
||||
|
||||
func (m metadata) Get(key metakey) string {
|
||||
return m[key]
|
||||
}
|
||||
|
||||
func (m metadata) Clone() map[metakey]string {
|
||||
return maps.Clone(m)
|
||||
}
|
||||
|
||||
func (m metadata) CloneToAnyMap() map[string]any {
|
||||
newM := make(map[string]any, len(m))
|
||||
for k, v := range m {
|
||||
newM[k.String()] = v
|
||||
}
|
||||
return newM
|
||||
}
|
||||
|
||||
func (m metadata) String() string {
|
||||
var b strings.Builder
|
||||
for k, v := range m {
|
||||
b.WriteString(fmt.Sprintf("%s: %s, ", k, v))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package apperr
|
||||
|
||||
type metakey uint16
|
||||
|
||||
const (
|
||||
PgErrorCode metakey = iota
|
||||
RedisErrorCode
|
||||
)
|
||||
|
||||
func (m metakey) String() string {
|
||||
switch m {
|
||||
case PgErrorCode:
|
||||
return "pg_err_code"
|
||||
case RedisErrorCode:
|
||||
return "redis_err_code"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package apperr
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
func WrapPostgres(err error, msg string) error {
|
||||
m := AppError{
|
||||
err: err,
|
||||
msg: msg,
|
||||
code: CodeInternal,
|
||||
meta: metadata{},
|
||||
}
|
||||
|
||||
m.handlePostgres()
|
||||
|
||||
return &m
|
||||
}
|
||||
|
||||
func (e *AppError) handlePostgres() {
|
||||
if e.err == nil {
|
||||
e.code = CodeOK
|
||||
return
|
||||
}
|
||||
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](e.err); ok {
|
||||
e.meta[PgErrorCode] = pgErr.Code
|
||||
e.code = CodeFromPostgres(pgErr.Code)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case errors.Is(e.err, pgx.ErrNoRows):
|
||||
e.msg = fmt.Sprintf("not found: %s", e.msg)
|
||||
e.code = CodeNotFound
|
||||
return
|
||||
case errors.Is(e.err, pgx.ErrTooManyRows):
|
||||
e.msg = fmt.Sprintf("got too many rows: %s", e.msg)
|
||||
e.code = CodeInternal
|
||||
return
|
||||
case errors.Is(e.err, pgx.ErrTxClosed):
|
||||
e.msg = fmt.Sprintf("transaction is closed: %s", e.msg)
|
||||
e.code = CodeInternal
|
||||
return
|
||||
case errors.Is(e.err, pgx.ErrTxCommitRollback):
|
||||
e.msg = fmt.Sprintf("transaction commit resulted in rollback: %s", e.msg)
|
||||
e.code = CodeInternal
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (e *AppError) PgCode() string {
|
||||
if e == nil {
|
||||
return ""
|
||||
}
|
||||
if e.meta == nil {
|
||||
return ""
|
||||
}
|
||||
return e.meta.Get(PgErrorCode)
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package apperr
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func WrapRedis(err error, msg string) error {
|
||||
m := AppError{
|
||||
err: err,
|
||||
msg: msg,
|
||||
meta: metadata{},
|
||||
}
|
||||
|
||||
m.handleRedis()
|
||||
|
||||
return &m
|
||||
}
|
||||
|
||||
func CodeFromRedisError(err error) Code {
|
||||
code, ok := codeFromRedisError(err, true, true)
|
||||
if !ok {
|
||||
return CodeInternal
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
func (e *AppError) handleRedis() {
|
||||
if e.err == nil {
|
||||
e.code = CodeOK
|
||||
return
|
||||
}
|
||||
|
||||
if code := redisErrorCode(e.err); code != "" {
|
||||
e.meta[RedisErrorCode] = code
|
||||
}
|
||||
|
||||
if errors.Is(e.err, redis.Nil) {
|
||||
e.msg = fmt.Sprintf("not found: %s", e.msg)
|
||||
}
|
||||
|
||||
e.code = CodeFromRedisError(e.err)
|
||||
}
|
||||
|
||||
func (e *AppError) RedisCode() string {
|
||||
if e == nil {
|
||||
return ""
|
||||
}
|
||||
if e.meta == nil {
|
||||
return ""
|
||||
}
|
||||
return e.meta.Get(RedisErrorCode)
|
||||
}
|
||||
|
||||
func codeFromRedisError(err error, includeTransport bool, includeProtocolString bool) (Code, bool) {
|
||||
if err == nil {
|
||||
return CodeInternal, false
|
||||
}
|
||||
|
||||
switch {
|
||||
case errors.Is(err, redis.Nil):
|
||||
return CodeNotFound, true
|
||||
case errors.Is(err, redis.TxFailedErr):
|
||||
return CodeConflict, true
|
||||
case errors.Is(err, redis.ErrCrossSlot):
|
||||
return CodeBadRequest, true
|
||||
case errors.Is(err, redis.ErrPoolTimeout):
|
||||
return CodeTimeout, true
|
||||
case errors.Is(err, redis.ErrPoolExhausted):
|
||||
return CodeTooManyRequests, true
|
||||
case errors.Is(err, redis.ErrClosed):
|
||||
return CodeServiceUnavailable, true
|
||||
}
|
||||
|
||||
if includeTransport {
|
||||
if errors.Is(err, context.Canceled) ||
|
||||
errors.Is(err, context.DeadlineExceeded) {
|
||||
return CodeTimeout, true
|
||||
}
|
||||
|
||||
if netErr, ok := errors.AsType[net.Error](err); ok {
|
||||
if netErr.Timeout() {
|
||||
return CodeTimeout, true
|
||||
}
|
||||
return CodeServiceUnavailable, true
|
||||
}
|
||||
}
|
||||
|
||||
hasRedisError := isRedisError(err)
|
||||
if !hasRedisError && !includeProtocolString {
|
||||
return CodeInternal, false
|
||||
}
|
||||
|
||||
switch {
|
||||
case redis.IsExecAbortError(err):
|
||||
return CodeConflict, true
|
||||
case redis.IsMaxClientsError(err):
|
||||
return CodeTooManyRequests, true
|
||||
case redis.IsLoadingError(err),
|
||||
redis.IsReadOnlyError(err),
|
||||
redis.IsClusterDownError(err),
|
||||
redis.IsTryAgainError(err),
|
||||
redis.IsMasterDownError(err),
|
||||
redis.IsNoReplicasError(err),
|
||||
redis.IsOOMError(err):
|
||||
return CodeServiceUnavailable, true
|
||||
case redis.IsAuthError(err),
|
||||
redis.IsPermissionError(err):
|
||||
return CodeInternal, true
|
||||
}
|
||||
|
||||
if _, ok := redis.IsMovedError(err); ok {
|
||||
return CodeServiceUnavailable, true
|
||||
}
|
||||
if _, ok := redis.IsAskError(err); ok {
|
||||
return CodeServiceUnavailable, true
|
||||
}
|
||||
|
||||
if hasRedisError {
|
||||
return CodeInternal, true
|
||||
}
|
||||
|
||||
return CodeInternal, false
|
||||
}
|
||||
|
||||
func isRedisError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
var redisErr redis.Error
|
||||
return errors.As(err, &redisErr)
|
||||
}
|
||||
|
||||
func redisErrorCode(err error) string {
|
||||
switch {
|
||||
case err == nil:
|
||||
return ""
|
||||
case errors.Is(err, redis.Nil):
|
||||
return "nil"
|
||||
case errors.Is(err, redis.TxFailedErr):
|
||||
return "tx_failed"
|
||||
case errors.Is(err, redis.ErrCrossSlot):
|
||||
return "CROSSSLOT"
|
||||
case errors.Is(err, redis.ErrPoolTimeout):
|
||||
return "pool_timeout"
|
||||
case errors.Is(err, redis.ErrPoolExhausted):
|
||||
return "pool_exhausted"
|
||||
case errors.Is(err, redis.ErrClosed):
|
||||
return "closed"
|
||||
}
|
||||
|
||||
var redisErr redis.Error
|
||||
if !errors.As(err, &redisErr) {
|
||||
return ""
|
||||
}
|
||||
|
||||
msg := strings.TrimSpace(redisErr.Error())
|
||||
msg = strings.TrimPrefix(msg, "ERR ")
|
||||
parts := strings.Fields(msg)
|
||||
if len(parts) == 0 {
|
||||
return ""
|
||||
}
|
||||
return parts[0]
|
||||
}
|
||||
+5
-4
@@ -1,4 +1,4 @@
|
||||
package provider
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/role"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/role"
|
||||
)
|
||||
|
||||
var _ Claims = (*jwtClaims)(nil)
|
||||
@@ -110,14 +110,15 @@ func (p *provider) parseClaimsFromProtectedJWT(token *dto.Token) (*jwtClaims, er
|
||||
token.Payload,
|
||||
claims,
|
||||
p.readKeyFunc,
|
||||
jwt.WithValidMethods([]string{jwt.SigningMethodRS256.Alg()}),
|
||||
jwt.WithExpirationRequired(),
|
||||
jwt.WithIssuedAt(),
|
||||
)
|
||||
if err != nil {
|
||||
slog.Error("failed to parse token with claims", "error", err)
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
|
||||
// todo ADD VALIDATION
|
||||
|
||||
if !parsed.Valid {
|
||||
slog.Error("failed to parse token: provided invalid token", "valid", parsed.Valid)
|
||||
return nil, ErrInvalidToken
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package provider
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package provider
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"errors"
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
package provider
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/role"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/role"
|
||||
)
|
||||
|
||||
type Provider interface {
|
||||
+8
-8
@@ -1,4 +1,4 @@
|
||||
package provider
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -18,13 +18,13 @@ type manager struct {
|
||||
|
||||
func NewCookieManager(cfg *config.Config, provider Provider) Cookie {
|
||||
m := &manager{
|
||||
enabled: cfg.Cookies.Enabled,
|
||||
cookieFabric: newCookieBuilder(
|
||||
cfg.Cookies.Domain,
|
||||
cfg.Cookies.Path,
|
||||
cfg.Cookies.Secure,
|
||||
cfg.Cookies.SameSite,
|
||||
),
|
||||
//enabled: cfg.Cookies.Enabled,
|
||||
//cookieFabric: newCookieBuilder(
|
||||
// cfg.Cookies.Domain,
|
||||
// cfg.Cookies.Path,
|
||||
// cfg.Cookies.Secure,
|
||||
// cfg.Cookies.SameSite,
|
||||
//),
|
||||
prv: provider,
|
||||
}
|
||||
|
||||
+6
-8
@@ -1,4 +1,4 @@
|
||||
package provider
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"crypto/rsa"
|
||||
@@ -11,8 +11,8 @@ import (
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/config"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/environment"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/role"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/environment"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/role"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -76,7 +76,7 @@ func (p *provider) ParseVerified(t *dto.Token) (*dto.UserDataInToken, error) {
|
||||
if t == nil {
|
||||
return nil, ErrTokenIsMissing
|
||||
}
|
||||
claims, err := p.parseFunc(t)
|
||||
claims, err := p.parseClaimsFromProtectedJWT(t)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse token: %w", err)
|
||||
}
|
||||
@@ -173,10 +173,8 @@ func (p *provider) ValidateUserDataInToken(u *dto.UserDataInToken) error {
|
||||
}
|
||||
|
||||
func (p *provider) readKeyFunc(token *jwt.Token) (interface{}, error) {
|
||||
switch token.Method.(type) {
|
||||
case *jwt.SigningMethodRSA:
|
||||
return p.publicKey, nil
|
||||
default:
|
||||
if token.Method != jwt.SigningMethodRS256 {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return p.publicKey, nil
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package provider
|
||||
package jwtprovider
|
||||
|
||||
import (
|
||||
"crypto/rsa"
|
||||
@@ -1,79 +0,0 @@
|
||||
package authidentity
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"git.dev.mamont-optics.ru/mamont-optics/backend/application/internal/pkg/types"
|
||||
)
|
||||
|
||||
type Status string
|
||||
|
||||
const (
|
||||
StatusUndefined Status = "UNDEFINED"
|
||||
StatusPending Status = "PENDING"
|
||||
StatusActive Status = "ACTIVE"
|
||||
StatusBlocked Status = "BLOCKED"
|
||||
)
|
||||
|
||||
var allowedStatuses = map[Status]struct{}{
|
||||
StatusUndefined: {},
|
||||
StatusPending: {},
|
||||
StatusActive: {},
|
||||
StatusBlocked: {},
|
||||
}
|
||||
|
||||
func ParseStatus(status string) Status {
|
||||
s := Status(strings.ToUpper(status))
|
||||
if !s.IsValid() {
|
||||
return StatusUndefined
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func ParseAndValidateStatus(status string) (Status, error) {
|
||||
parsed := ParseStatus(status)
|
||||
if _, ok := allowedStatuses[parsed]; ok {
|
||||
return parsed, nil
|
||||
}
|
||||
return StatusUndefined, types.ErrUnsupportedAuthIdentityStatus
|
||||
}
|
||||
|
||||
func (t Status) String() string {
|
||||
return string(t)
|
||||
}
|
||||
|
||||
func (t Status) Validate() error {
|
||||
if _, ok := allowedStatuses[t]; ok {
|
||||
return nil
|
||||
}
|
||||
return types.ErrUnsupportedAuthIdentityStatus
|
||||
}
|
||||
|
||||
func (t Status) IsValid() bool {
|
||||
_, ok := allowedStatuses[t]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (t Status) MarshalJSON() ([]byte, error) {
|
||||
if err := t.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(t.String())
|
||||
}
|
||||
|
||||
func (t *Status) UnmarshalJSON(data []byte) error {
|
||||
if t == nil {
|
||||
return types.ErrUnmarshalAuthIdentityStatusIntoNilPointer
|
||||
}
|
||||
var value string
|
||||
if err := json.Unmarshal(data, &value); err != nil {
|
||||
return err
|
||||
}
|
||||
parsed := ParseStatus(value)
|
||||
if err := parsed.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
*t = parsed
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package encrypting
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argon2idMemory = 64 * 1024 // KiB
|
||||
argon2idTime = 3
|
||||
argon2idThreads = 4
|
||||
argon2idSaltLen = 16
|
||||
argon2idKeyLen = 32
|
||||
// Only this bounded profile is accepted; stored parameters cannot request arbitrary resources.
|
||||
argon2idPrefix = "$argon2id$v=19$m=65536,t=3,p=4$"
|
||||
)
|
||||
|
||||
func (e *encryptor) EncryptSecretUsingArgon2id(ctx context.Context, secret string) (string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
var salt [argon2idSaltLen]byte
|
||||
if _, err := rand.Read(salt[:]); err != nil {
|
||||
return "", fmt.Errorf("%w: %w", ErrFailedToEncryptPassword, err)
|
||||
}
|
||||
key := argon2.IDKey([]byte(secret), salt[:], argon2idTime, argon2idMemory, argon2idThreads, argon2idKeyLen)
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return argon2idPrefix + base64.RawStdEncoding.EncodeToString(salt[:]) + "$" + base64.RawStdEncoding.EncodeToString(key), nil
|
||||
}
|
||||
|
||||
func (e *encryptor) CompareHashAndSecretUsingArgon2id(ctx context.Context, hash, secret string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
encoding := base64.RawStdEncoding.Strict()
|
||||
if len(hash) != len(argon2idPrefix)+encoding.EncodedLen(argon2idSaltLen)+1+encoding.EncodedLen(argon2idKeyLen) {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
payload, ok := strings.CutPrefix(hash, argon2idPrefix)
|
||||
if !ok {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
saltText, keyText, ok := strings.Cut(payload, "$")
|
||||
if !ok {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
salt, err := encoding.DecodeString(saltText)
|
||||
if err != nil || len(salt) != argon2idSaltLen {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
storedKey, err := encoding.DecodeString(keyText)
|
||||
if err != nil || len(storedKey) != argon2idKeyLen {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
key := argon2.IDKey([]byte(secret), salt, argon2idTime, argon2idMemory, argon2idThreads, argon2idKeyLen)
|
||||
if err = ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if subtle.ConstantTimeCompare(storedKey, key) != 1 {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package encrypting
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type encryptor struct {
|
||||
cost int
|
||||
generateFromPasswordFunc func([]byte, int) ([]byte, error)
|
||||
compareHashAndPasswordFunc func([]byte, []byte) error
|
||||
}
|
||||
|
||||
func New() Encryptor {
|
||||
return &encryptor{
|
||||
cost: bcrypt.DefaultCost,
|
||||
generateFromPasswordFunc: bcrypt.GenerateFromPassword,
|
||||
compareHashAndPasswordFunc: bcrypt.CompareHashAndPassword,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *encryptor) EncryptSecret(_ context.Context, secret string) (string, error) {
|
||||
res, err := e.generateFromPasswordFunc([]byte(secret), e.cost)
|
||||
if err != nil {
|
||||
return "", ErrFailedToEncryptPassword
|
||||
}
|
||||
return string(res), nil
|
||||
}
|
||||
|
||||
func (e *encryptor) EncryptSecretUsingSum256(_ context.Context, secret string) (string, error) {
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
res, err := e.generateFromPasswordFunc([]byte(hex.EncodeToString(sum[:])), e.cost)
|
||||
if err != nil {
|
||||
return "", ErrFailedToEncryptPassword
|
||||
}
|
||||
return string(res), nil
|
||||
}
|
||||
|
||||
func (e *encryptor) CompareHashAndSecret(_ context.Context, hash, password string) error {
|
||||
err := e.compareHashAndPasswordFunc([]byte(hash), []byte(password))
|
||||
if err != nil {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *encryptor) CompareHashAndSecretUsingSum256(_ context.Context, hash, password string) error {
|
||||
sum := sha256.Sum256([]byte(password))
|
||||
err := e.compareHashAndPasswordFunc([]byte(hash), []byte(hex.EncodeToString(sum[:])))
|
||||
if err != nil {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package encrypting
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrFailedToEncryptPassword = errors.New("failed to encrypt password")
|
||||
ErrFailedToComparePasswords = errors.New("failed to compare passwords")
|
||||
)
|
||||
@@ -0,0 +1,12 @@
|
||||
package encrypting
|
||||
|
||||
import "context"
|
||||
|
||||
type Encryptor interface {
|
||||
EncryptSecretUsingArgon2id(ctx context.Context, secret string) (string, error)
|
||||
CompareHashAndSecretUsingArgon2id(ctx context.Context, hash, secret string) error
|
||||
EncryptSecret(ctx context.Context, secret string) (string, error)
|
||||
EncryptSecretUsingSum256(_ context.Context, secret string) (string, error)
|
||||
CompareHashAndSecret(ctx context.Context, hash, secret string) error
|
||||
CompareHashAndSecretUsingSum256(ctx context.Context, hash, secret string) error
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package migrator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/tern/v2/migrate"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/config"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/migrations"
|
||||
)
|
||||
|
||||
type Migrator interface {
|
||||
MigrateUp(ctx context.Context) error
|
||||
MigrateDown(ctx context.Context) error
|
||||
MigrateTo(ctx context.Context, version int32) error
|
||||
GetVersion(ctx context.Context) (int32, error)
|
||||
Configure(ctx context.Context) error
|
||||
Close(ctx context.Context) error
|
||||
Start(ctx context.Context) error
|
||||
Stop(ctx context.Context) error
|
||||
}
|
||||
|
||||
type migrator struct {
|
||||
cfg *config.Config
|
||||
conn *pgx.Conn
|
||||
migrator *migrate.Migrator
|
||||
migrations fs.FS
|
||||
configured bool
|
||||
closed bool
|
||||
}
|
||||
|
||||
func New(cfg *config.Config) Migrator {
|
||||
return &migrator{
|
||||
cfg: cfg,
|
||||
conn: nil,
|
||||
migrator: nil,
|
||||
migrations: migrations.Migrations,
|
||||
configured: false,
|
||||
closed: false,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *migrator) MigrateUp(ctx context.Context) error {
|
||||
if !m.configured {
|
||||
return apperr.New(apperr.CodeInternal, "migrator was not configured")
|
||||
}
|
||||
return m.migrator.Migrate(ctx)
|
||||
}
|
||||
|
||||
func (m *migrator) MigrateDown(ctx context.Context) error {
|
||||
if !m.configured {
|
||||
return apperr.New(apperr.CodeInternal, "migrator was not configured")
|
||||
}
|
||||
return m.migrator.MigrateTo(ctx, 0)
|
||||
}
|
||||
|
||||
func (m *migrator) MigrateTo(ctx context.Context, version int32) error {
|
||||
if !m.configured {
|
||||
return apperr.New(apperr.CodeInternal, "migrator was not configured")
|
||||
}
|
||||
return m.migrator.MigrateTo(ctx, version)
|
||||
}
|
||||
|
||||
func (m *migrator) GetVersion(ctx context.Context) (int32, error) {
|
||||
if !m.configured {
|
||||
return -1, apperr.New(apperr.CodeInternal, "migrator was not configured")
|
||||
}
|
||||
return m.migrator.GetCurrentVersion(ctx)
|
||||
}
|
||||
|
||||
func (m *migrator) Configure(ctx context.Context) error {
|
||||
if err := m.initConn(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.initMigrator(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.loadMigrations(); err != nil {
|
||||
return err
|
||||
}
|
||||
m.configured = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *migrator) Close(ctx context.Context) error {
|
||||
return m.closeConn(ctx)
|
||||
}
|
||||
|
||||
func (m *migrator) Start(ctx context.Context) error {
|
||||
if !m.cfg.Postgres.GetRunMigrations() {
|
||||
slog.Info("flag run migrations is disabled: skipping migrating")
|
||||
return nil
|
||||
}
|
||||
|
||||
err := m.Configure(ctx)
|
||||
if err != nil {
|
||||
slog.Error("failed to configure migrator", "error", err)
|
||||
return err
|
||||
}
|
||||
err = m.MigrateUp(ctx)
|
||||
if err != nil {
|
||||
slog.Error("failed to migrate database up", "error", err)
|
||||
return err
|
||||
}
|
||||
|
||||
if err = m.Close(ctx); err != nil {
|
||||
slog.Error("failed close connection to database", "error", err)
|
||||
return err
|
||||
}
|
||||
|
||||
m.closed = true
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *migrator) Stop(ctx context.Context) error {
|
||||
if !m.cfg.Postgres.GetRunMigrations() {
|
||||
return nil
|
||||
}
|
||||
|
||||
if !m.closed {
|
||||
err := m.conn.Close(ctx)
|
||||
if err != nil {
|
||||
slog.Error("failed close connection to database", "error", err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *migrator) loadMigrations() (err error) {
|
||||
err = m.migrator.LoadMigrations(m.migrations)
|
||||
if err != nil {
|
||||
slog.Error("failed to load migrations", "error", err)
|
||||
return apperr.New(apperr.CodeInternal, "failed to load migrations")
|
||||
}
|
||||
slog.Info("successfully loaded migrations", "error", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *migrator) initConn(ctx context.Context) (err error) {
|
||||
m.conn, err = pgx.Connect(ctx, m.cfg.Postgres.GetURI())
|
||||
if err != nil {
|
||||
slog.Error("failed to create connection to database", "error", err)
|
||||
return apperr.New(apperr.CodeInternal, "failed to create connection to database")
|
||||
}
|
||||
slog.Info("connected to database", "db", m.cfg.Postgres.Database)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *migrator) initMigrator(ctx context.Context) (err error) {
|
||||
m.migrator, err = migrate.NewMigrator(ctx, m.conn, m.cfg.Postgres.GetVersionTableName())
|
||||
if err != nil {
|
||||
slog.Error("failed to initialize migrator", "error", err)
|
||||
return apperr.New(apperr.CodeInternal, "failed to initialize migrator")
|
||||
}
|
||||
slog.Info("successfully initialized migrator")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *migrator) closeConn(ctx context.Context) error {
|
||||
return m.conn.Close(ctx)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
pgxUUID "github.com/vgarvardt/pgx-google-uuid/v5"
|
||||
)
|
||||
|
||||
type AfterConnect func(ctx context.Context, conn *pgx.Conn) error
|
||||
|
||||
func AddUUIDSupport(_ context.Context, conn *pgx.Conn) error {
|
||||
pgxUUID.Register(conn.TypeMap())
|
||||
return nil
|
||||
}
|
||||
func WithEnumTypeSupport(enumName string) AfterConnect {
|
||||
return func(ctx context.Context, conn *pgx.Conn) error {
|
||||
dt, err := conn.LoadType(ctx, enumName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
conn.TypeMap().RegisterType(dt)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package postgres
|
||||
|
||||
type MigrationConfig interface {
|
||||
GetURI() string
|
||||
GetVersionTableName() string
|
||||
GetRunMigrations() bool
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
var (
|
||||
errCreatingPool = errors.New("failed to create postgres pool")
|
||||
errParseConfig = errors.New("failed to parse postgres config")
|
||||
)
|
||||
@@ -0,0 +1,15 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
type Conn interface {
|
||||
SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults
|
||||
Exec(ctx context.Context, sql string, arguments ...any) (commandTag pgconn.CommandTag, err error)
|
||||
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
|
||||
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/jackc/pgx/v5/tracelog"
|
||||
|
||||
pgxslog "github.com/mcosta74/pgx-slog"
|
||||
)
|
||||
|
||||
type ConfigWithLog interface {
|
||||
GetLogLevel() string
|
||||
}
|
||||
|
||||
type ConfigWithMaxConn interface {
|
||||
GetMaxConnections() int32
|
||||
}
|
||||
|
||||
func getLevelFromConfig(cfg MigrationConfig) tracelog.LogLevel {
|
||||
if logCfg, ok := cfg.(ConfigWithLog); ok {
|
||||
lvl, _ := tracelog.LogLevelFromString(logCfg.GetLogLevel())
|
||||
return lvl
|
||||
}
|
||||
return tracelog.LogLevelError
|
||||
}
|
||||
|
||||
func addMaxConnectionsToCfg(cfg any, poolCfg *pgxpool.Config) {
|
||||
if connCfg, ok := cfg.(ConfigWithMaxConn); ok {
|
||||
poolCfg.MaxConns = connCfg.GetMaxConnections()
|
||||
}
|
||||
}
|
||||
|
||||
func New(cfg MigrationConfig, afterConnect ...AfterConnect) (*pgxpool.Pool, error) {
|
||||
lvl := getLevelFromConfig(cfg)
|
||||
|
||||
if len(afterConnect) == 0 {
|
||||
afterConnect = []AfterConnect{AddUUIDSupport}
|
||||
}
|
||||
|
||||
poolConfig, err := pgxpool.ParseConfig(cfg.GetURI())
|
||||
if err != nil {
|
||||
slog.Error("failed to parse postgres config", "error", err)
|
||||
return nil, errParseConfig
|
||||
}
|
||||
|
||||
addMaxConnectionsToCfg(cfg, poolConfig)
|
||||
|
||||
poolConfig.ConnConfig.Tracer = &tracelog.TraceLog{
|
||||
Logger: pgxslog.NewLogger(slog.Default()),
|
||||
LogLevel: lvl,
|
||||
Config: &tracelog.TraceLogConfig{
|
||||
TimeKey: "ts",
|
||||
},
|
||||
}
|
||||
|
||||
poolConfig.AfterConnect = load(afterConnect...)
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(context.Background(), poolConfig)
|
||||
if err != nil {
|
||||
slog.Error("failed to create postgres pool", "error", err)
|
||||
return nil, errCreatingPool
|
||||
}
|
||||
|
||||
slog.Info("successfully connected to postgres pool")
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
func load(afterConnects ...AfterConnect) func(ctx context.Context, conn *pgx.Conn) error {
|
||||
return func(ctx context.Context, conn *pgx.Conn) error {
|
||||
for _, afterConnect := range afterConnects {
|
||||
if err := afterConnect(ctx, conn); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package txmanager
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type TransactionManager struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool) *TransactionManager {
|
||||
return &TransactionManager{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
func (tm *TransactionManager) RunInTransaction(ctx context.Context, opts *pgx.TxOptions, fn func(tx pgx.Tx) error) (err error) {
|
||||
var tx pgx.Tx
|
||||
|
||||
if opts != nil {
|
||||
tx, err = tm.pool.BeginTx(ctx, *opts)
|
||||
} else {
|
||||
tx, err = tm.pool.Begin(ctx)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to begin transaction: %w", err)
|
||||
}
|
||||
|
||||
var committed bool
|
||||
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
err = fmt.Errorf("panic in transaction: %v", p)
|
||||
}
|
||||
if !committed {
|
||||
rollbackErr := tx.Rollback(ctx)
|
||||
if rollbackErr != nil && !errors.Is(rollbackErr, pgx.ErrTxClosed) {
|
||||
slog.Error("failed to rollback transaction", "error", rollbackErr)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
if err = fn(tx); err != nil {
|
||||
return fmt.Errorf("failed to execute transaction: %w", err)
|
||||
}
|
||||
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("failed to commit transaction: %w", err)
|
||||
}
|
||||
|
||||
committed = true
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
package framework
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
v10 "github.com/go-playground/validator/v10"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/headers"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/validator"
|
||||
)
|
||||
|
||||
func validate(ctx context.Context, v *validator.ValidatorImpl, value any) error {
|
||||
err := v.ValidateCtx(ctx, value)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var fieldErrors v10.ValidationErrors
|
||||
if errors.As(err, &fieldErrors) {
|
||||
return apperr.Wrap(err, apperr.CodeValidation, "invalid request fields")
|
||||
}
|
||||
return apperr.Wrap(err, apperr.CodeInternal, "validation failed")
|
||||
}
|
||||
|
||||
func Validate(w http.ResponseWriter, r *http.Request, v *validator.ValidatorImpl, value any) bool {
|
||||
if err := validate(r.Context(), v, value); err != nil {
|
||||
JSONError(r.Context(), w, err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func JSONResponse(w http.ResponseWriter, status int, body any) {
|
||||
w.Header().Set(headers.HeaderContentType, "application/json")
|
||||
w.WriteHeader(status)
|
||||
|
||||
if status == http.StatusNoContent {
|
||||
return
|
||||
}
|
||||
|
||||
if err := json.NewEncoder(w).Encode(body); err != nil {
|
||||
wrapped := apperr.Wrap(err, apperr.CodeInternal, "failed json encode")
|
||||
slog.Error("response", "error", wrapped)
|
||||
}
|
||||
}
|
||||
|
||||
func JSONError(ctx context.Context, w http.ResponseWriter, err error) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
requestId, ok := ctx.Value(headers.HeaderRequestID).(uuid.UUID)
|
||||
if !ok {
|
||||
requestId = uuid.New()
|
||||
}
|
||||
w.Header().Set(headers.HeaderRequestID, requestId.String())
|
||||
|
||||
appErr := apperr.As(err)
|
||||
if appErr == nil {
|
||||
appErr = apperr.As(apperr.New(apperr.CodeInternal, "internal server error"))
|
||||
}
|
||||
if appErr.Code().HTTPStatus() == http.StatusUnauthorized && w.Header().Get("WWW-Authenticate") == "" {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
}
|
||||
|
||||
slog.Error("response", "error", err, "status", appErr.Code().HTTPStatus(), "requestId", requestId.String())
|
||||
|
||||
var code contracts.ErrorErrorCode
|
||||
switch appErr.Code() {
|
||||
case apperr.CodeBadRequest, apperr.CodeValidation:
|
||||
code = contracts.InvalidRequest
|
||||
case apperr.CodeUnauthorized:
|
||||
code = contracts.Unauthorized
|
||||
case apperr.CodeNotFound:
|
||||
code = contracts.NotFound
|
||||
case apperr.CodeAlreadyExists, apperr.CodeConflict:
|
||||
code = contracts.Conflict
|
||||
case apperr.CodePayloadTooLarge:
|
||||
code = contracts.PayloadTooLarge
|
||||
case apperr.CodeTooManyRequests:
|
||||
code = contracts.RateLimited
|
||||
case apperr.CodeServiceUnavailable, apperr.CodeUnavailable:
|
||||
code = contracts.Unavailable
|
||||
case apperr.CodeUnsupportedMediaType:
|
||||
code = contracts.UnsupportedMediaType
|
||||
default:
|
||||
code = contracts.InternalError
|
||||
}
|
||||
JSONResponse(w, appErr.Code().HTTPStatus(), contracts.Error{
|
||||
Error: struct {
|
||||
Code contracts.ErrorErrorCode `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestId string `json:"request_id"`
|
||||
}{
|
||||
Code: code,
|
||||
Message: appErr.Message(),
|
||||
RequestId: requestId.String(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func Decode(w http.ResponseWriter, r *http.Request, object any) bool {
|
||||
mediaType, params, err := mime.ParseMediaType(r.Header.Get(headers.HeaderContentType))
|
||||
if err != nil || mediaType != "application/json" ||
|
||||
(params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) {
|
||||
JSONError(r.Context(), w, apperr.New(apperr.CodeUnsupportedMediaType, "expected application/json"))
|
||||
return false
|
||||
}
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(object); err != nil {
|
||||
JSONError(r.Context(), w, apperr.Wrap(err, apperr.CodeBadRequest, "failed decode"))
|
||||
return false
|
||||
}
|
||||
var trailing any
|
||||
if err := decoder.Decode(&trailing); err != io.EOF {
|
||||
JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "expected one JSON object"))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func PathParam(r *http.Request, key string) string {
|
||||
return chi.URLParam(r, key)
|
||||
}
|
||||
|
||||
func QueryParam(r *http.Request, key string) string {
|
||||
return r.URL.Query().Get(key)
|
||||
}
|
||||
|
||||
func HeaderParam(r *http.Request, key string) string {
|
||||
return r.Header.Get(key)
|
||||
}
|
||||
|
||||
func ParseIDFromPathParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
|
||||
rawID := PathParam(r, key)
|
||||
id, err := uuid.Parse(rawID)
|
||||
if err != nil {
|
||||
JSONError(ctx, w, apperr.New(apperr.CodeValidation, fmt.Sprintf("provided invalid %s", key)))
|
||||
return uuid.Nil, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func ParseIDFromQueryParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
|
||||
rawID := QueryParam(r, key)
|
||||
id, err := uuid.Parse(rawID)
|
||||
if err != nil {
|
||||
JSONError(ctx, w, apperr.New(apperr.CodeValidation, fmt.Sprintf("provided invalid %s", key)))
|
||||
return uuid.Nil, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func ParseIDFromHeaderParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
|
||||
rawID := HeaderParam(r, key)
|
||||
id, err := uuid.Parse(rawID)
|
||||
if err != nil {
|
||||
JSONError(ctx, w, apperr.New(apperr.CodeUnauthorized, "missing or invalid user ID"))
|
||||
return uuid.Nil, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func Header(r *http.Request, header string) (string, bool) {
|
||||
return r.Header.Get(header), r.Header.Get(header) != ""
|
||||
}
|
||||
|
||||
func Token(r *http.Request) (string, bool) {
|
||||
foundHeader := r.Header.Get(headers.HeaderAuthorization)
|
||||
if foundHeader == "" {
|
||||
return "", false
|
||||
}
|
||||
|
||||
token, found := strings.CutPrefix(foundHeader, "Bearer ")
|
||||
if !found {
|
||||
return "", false
|
||||
}
|
||||
|
||||
return token, true
|
||||
}
|
||||
|
||||
func ParseToken(r *http.Request, provider jwtprovider.Provider) (*dto.UserDataInToken, error) {
|
||||
foundHeader := r.Header.Get(headers.HeaderAuthorization)
|
||||
if foundHeader == "" {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "missing authorization header")
|
||||
}
|
||||
|
||||
token, found := strings.CutPrefix(foundHeader, "Bearer ")
|
||||
if !found {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "invalid authorization header")
|
||||
}
|
||||
|
||||
userData, err := provider.ParseVerified(&dto.Token{Payload: token})
|
||||
if err != nil {
|
||||
return nil, apperr.Wrap(err, apperr.CodeUnauthorized, "invalid token")
|
||||
}
|
||||
|
||||
return userData, nil
|
||||
}
|
||||
|
||||
func PageParams(w http.ResponseWriter, r *http.Request) (*int, *uuid.UUID, bool) {
|
||||
query := r.URL.Query()
|
||||
var limit *int
|
||||
if values, exists := query["limit"]; exists {
|
||||
if len(values) != 1 {
|
||||
JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid limit"))
|
||||
return nil, nil, false
|
||||
}
|
||||
value, err := strconv.Atoi(values[0])
|
||||
if err != nil || value < 1 || value > 100 {
|
||||
JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid limit"))
|
||||
return nil, nil, false
|
||||
}
|
||||
limit = &value
|
||||
}
|
||||
var afterID *uuid.UUID
|
||||
if values, exists := query["cursor"]; exists {
|
||||
if len(values) != 1 {
|
||||
JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid cursor"))
|
||||
return nil, nil, false
|
||||
}
|
||||
id, err := uuid.Parse(values[0])
|
||||
if err != nil || id == uuid.Nil {
|
||||
JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid cursor"))
|
||||
return nil, nil, false
|
||||
}
|
||||
afterID = &id
|
||||
}
|
||||
return limit, afterID, true
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package headers
|
||||
|
||||
const (
|
||||
HeaderContentType = "Content-Type"
|
||||
HeaderRequestID = "X-Request-Id"
|
||||
HeaderUserID = "X-User-Id"
|
||||
HeaderAuthorization = "Authorization"
|
||||
)
|
||||
@@ -0,0 +1,74 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/role"
|
||||
)
|
||||
|
||||
var _ AuthMiddleware = (*authMiddleware)(nil)
|
||||
|
||||
type AuthMiddleware interface {
|
||||
WithPrivateAccess(next http.Handler) http.Handler
|
||||
WithAdminAccess(next http.Handler) http.Handler
|
||||
}
|
||||
|
||||
type SessionVerifier interface {
|
||||
VerifySession(ctx context.Context, token dto.Token) (*dto.UserDataInToken, error)
|
||||
}
|
||||
|
||||
type authMiddleware struct {
|
||||
verifier SessionVerifier
|
||||
}
|
||||
|
||||
func NewAuthMiddleware(verifier SessionVerifier) AuthMiddleware {
|
||||
return &authMiddleware{verifier: verifier}
|
||||
}
|
||||
|
||||
func (a *authMiddleware) WithPrivateAccess(next http.Handler) http.Handler {
|
||||
return a.privateAccessCheckCallback(next)
|
||||
}
|
||||
|
||||
func (a *authMiddleware) WithAdminAccess(next http.Handler) http.Handler {
|
||||
return a.operatorAccessCheckCallback(role.Admin, next)
|
||||
}
|
||||
|
||||
func (a *authMiddleware) privateAccessCheckCallback(next http.Handler) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if _, err := a.verifySession(r); err != nil {
|
||||
framework.JSONError(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *authMiddleware) operatorAccessCheckCallback(expectedRole role.Role, next http.Handler) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
u, err := a.verifySession(r)
|
||||
if err != nil {
|
||||
framework.JSONError(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
|
||||
if u.Role != role.Admin && u.Role != expectedRole {
|
||||
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeForbidden, "insufficient permissions"))
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *authMiddleware) verifySession(r *http.Request) (*dto.UserDataInToken, error) {
|
||||
token, found := framework.Token(r)
|
||||
if !found || token == "" {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "missing or invalid bearer token")
|
||||
}
|
||||
return a.verifier.VerifySession(r.Context(), dto.Token{Payload: token})
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/headers"
|
||||
)
|
||||
|
||||
func LoggingMiddleware() Middleware {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
started := time.Now()
|
||||
wrapped := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
next.ServeHTTP(wrapped, r)
|
||||
|
||||
status := wrapped.Status()
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
slog.InfoContext(r.Context(), "http request",
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", status,
|
||||
"duration", time.Since(started),
|
||||
"bytes", wrapped.BytesWritten(),
|
||||
"request_id", w.Header().Get(headers.HeaderRequestID),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
type Middleware = func(http.Handler) http.Handler
|
||||
@@ -0,0 +1,22 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/headers"
|
||||
)
|
||||
|
||||
func RequestIDMiddleware() Middleware {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
requestID := uuid.New()
|
||||
w.Header().Set(headers.HeaderRequestID, requestID.String())
|
||||
ctx = context.WithValue(ctx, headers.HeaderRequestID, requestID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/middleware"
|
||||
)
|
||||
|
||||
type Router interface {
|
||||
Private(method, pattern string, handler http.HandlerFunc, mw ...func(http.Handler) http.Handler)
|
||||
Public(method, pattern string, handler http.HandlerFunc, mw ...func(http.Handler) http.Handler)
|
||||
Admin(method, pattern string, handler http.HandlerFunc, mw ...func(http.Handler) http.Handler)
|
||||
ServeHTTP(w http.ResponseWriter, r *http.Request)
|
||||
With(mw ...func(http.Handler) http.Handler) Router
|
||||
Use(mw ...func(http.Handler) http.Handler) Router
|
||||
Handle(pattern string, handler http.Handler)
|
||||
Get(pattern string, handler http.HandlerFunc)
|
||||
Head(pattern string, handler http.HandlerFunc)
|
||||
Options(pattern string, handler http.HandlerFunc)
|
||||
Post(pattern string, handler http.HandlerFunc)
|
||||
Put(pattern string, handler http.HandlerFunc)
|
||||
Patch(pattern string, handler http.HandlerFunc)
|
||||
Delete(pattern string, handler http.HandlerFunc)
|
||||
Connect(pattern string, handler http.HandlerFunc)
|
||||
Trace(pattern string, handler http.HandlerFunc)
|
||||
}
|
||||
|
||||
type router struct {
|
||||
r chi.Router
|
||||
jwtMw middleware.AuthMiddleware
|
||||
}
|
||||
|
||||
func New(jwtMw middleware.AuthMiddleware, mw ...middleware.Middleware) Router {
|
||||
r := chi.NewRouter()
|
||||
r.Use(mw...)
|
||||
return &router{
|
||||
r: r,
|
||||
jwtMw: jwtMw,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *router) Group(pattern string) Router {
|
||||
sub := &router{
|
||||
r: chi.NewRouter(),
|
||||
jwtMw: c.jwtMw,
|
||||
}
|
||||
c.r.Mount(pattern, sub.r)
|
||||
return sub
|
||||
}
|
||||
|
||||
func (c *router) Public(method, pattern string, handler http.HandlerFunc, mw ...func(http.Handler) http.Handler) {
|
||||
next := c.applyMiddlewares(handler, mw...)
|
||||
c.r.MethodFunc(method, pattern, next.ServeHTTP)
|
||||
}
|
||||
|
||||
func (c *router) Private(method, pattern string, handler http.HandlerFunc, mw ...func(http.Handler) http.Handler) {
|
||||
next := c.applyMiddlewares(handler, mw...)
|
||||
c.r.MethodFunc(method, pattern, (c.jwtMw.WithPrivateAccess(next)).ServeHTTP)
|
||||
}
|
||||
|
||||
func (c *router) Admin(method, pattern string, handler http.HandlerFunc, mw ...func(http.Handler) http.Handler) {
|
||||
next := c.applyMiddlewares(handler, mw...)
|
||||
c.r.MethodFunc(method, pattern, (c.jwtMw.WithAdminAccess(next)).ServeHTTP)
|
||||
}
|
||||
|
||||
func (c *router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
c.r.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
func (c *router) With(mw ...func(http.Handler) http.Handler) Router {
|
||||
sub := &router{
|
||||
r: c.r.With(mw...),
|
||||
jwtMw: c.jwtMw,
|
||||
}
|
||||
return sub
|
||||
}
|
||||
|
||||
func (c *router) Use(mw ...func(http.Handler) http.Handler) Router {
|
||||
c.r.Use(mw...)
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *router) Handle(pattern string, handler http.Handler) {
|
||||
c.r.Handle(pattern, handler)
|
||||
}
|
||||
|
||||
func (c *router) Get(pattern string, handler http.HandlerFunc) {
|
||||
c.r.Get(pattern, handler)
|
||||
}
|
||||
|
||||
func (c *router) Head(pattern string, handler http.HandlerFunc) {
|
||||
c.r.Head(pattern, handler)
|
||||
}
|
||||
|
||||
func (c *router) Options(pattern string, handler http.HandlerFunc) {
|
||||
c.r.Options(pattern, handler)
|
||||
}
|
||||
|
||||
func (c *router) Post(pattern string, handler http.HandlerFunc) {
|
||||
c.r.Post(pattern, handler)
|
||||
}
|
||||
|
||||
func (c *router) Put(pattern string, handler http.HandlerFunc) {
|
||||
c.r.Put(pattern, handler)
|
||||
}
|
||||
|
||||
func (c *router) Patch(pattern string, handler http.HandlerFunc) {
|
||||
c.r.Patch(pattern, handler)
|
||||
}
|
||||
|
||||
func (c *router) Delete(pattern string, handler http.HandlerFunc) {
|
||||
c.r.Delete(pattern, handler)
|
||||
}
|
||||
|
||||
func (c *router) Connect(pattern string, handler http.HandlerFunc) {
|
||||
c.r.Connect(pattern, handler)
|
||||
}
|
||||
|
||||
func (c *router) Trace(pattern string, handler http.HandlerFunc) {
|
||||
c.r.Trace(pattern, handler)
|
||||
}
|
||||
|
||||
func (c *router) applyMiddlewares(handler http.HandlerFunc, mw ...func(http.Handler) http.Handler) http.Handler {
|
||||
next := http.Handler(handler)
|
||||
for _, mwFunc := range mw {
|
||||
next = mwFunc(next)
|
||||
}
|
||||
return next
|
||||
}
|
||||
+1
-1
@@ -4,7 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"git.dev.mamont-optics.ru/mamont-optics/backend/application/internal/pkg/types"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types"
|
||||
)
|
||||
|
||||
type Type string
|
||||
+1
-1
@@ -4,7 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"git.dev.mamont-optics.ru/mamont-optics/backend/application/internal/pkg/types"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types"
|
||||
)
|
||||
|
||||
type ApplicationEnvironment string
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"git.dev.mamont-optics.ru/mamont-optics/backend/application/internal/pkg/types"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types"
|
||||
)
|
||||
|
||||
type Role string
|
||||
@@ -0,0 +1,15 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
)
|
||||
|
||||
type API interface {
|
||||
Login(ctx context.Context, req dto.Login) (*dto.LoginResult, error)
|
||||
VerifyAccessToken(ctx context.Context, req dto.Token) (*dto.UserDataInToken, error)
|
||||
VerifySession(ctx context.Context, token dto.Token) (*dto.UserDataInToken, error)
|
||||
RefreshTokens(ctx context.Context, req dto.RefreshToken) (*dto.Tokens, error)
|
||||
Logout(ctx context.Context, req dto.RefreshToken) error
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
)
|
||||
|
||||
type userRepo interface {
|
||||
GetCredentialsByUsername(ctx context.Context, username string) (*dto.UserCredentials, error)
|
||||
}
|
||||
|
||||
type refreshTokensRepo interface {
|
||||
GetByID(ctx context.Context, id uuid.UUID) (*dto.StoredRefreshToken, error)
|
||||
GetByIDForUpdateTx(ctx context.Context, tx pgx.Tx, id uuid.UUID) (*dto.StoredRefreshToken, error)
|
||||
CreateTx(ctx context.Context, tx pgx.Tx, req dto.StoredRefreshToken) error
|
||||
RevokeTx(ctx context.Context, tx pgx.Tx, req dto.RevokeRefreshToken) error
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/encrypting"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres/txmanager"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/types/role"
|
||||
)
|
||||
|
||||
var _ API = (*Auth)(nil)
|
||||
|
||||
type Auth struct {
|
||||
jwt jwtprovider.Provider
|
||||
tm *txmanager.TransactionManager
|
||||
encryptor encrypting.Encryptor
|
||||
|
||||
usersRepo userRepo
|
||||
refreshTokensRepo refreshTokensRepo
|
||||
}
|
||||
|
||||
func New(
|
||||
jwt jwtprovider.Provider,
|
||||
tm *txmanager.TransactionManager,
|
||||
encryptor encrypting.Encryptor,
|
||||
usersRepo userRepo,
|
||||
refreshTokensRepo refreshTokensRepo,
|
||||
) *Auth {
|
||||
return &Auth{
|
||||
jwt: jwt,
|
||||
tm: tm,
|
||||
encryptor: encryptor,
|
||||
usersRepo: usersRepo,
|
||||
refreshTokensRepo: refreshTokensRepo,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Auth) Login(ctx context.Context, req dto.Login) (*dto.LoginResult, error) {
|
||||
if req.Username == "" || req.Password == "" {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "invalid credentials")
|
||||
}
|
||||
|
||||
credentials, err := a.usersRepo.GetCredentialsByUsername(ctx, req.Username)
|
||||
if err != nil {
|
||||
if apperr.CodeFromError(err) == apperr.CodeNotFound {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "invalid credentials")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if err = a.encryptor.CompareHashAndSecretUsingArgon2id(ctx, credentials.PasswordHash, req.Password); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "invalid credentials")
|
||||
}
|
||||
|
||||
var (
|
||||
tokens *dto.Tokens
|
||||
data *dto.UserDataInToken
|
||||
)
|
||||
err = a.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
|
||||
tokens, err = a.jwt.CreateRefreshAndAccessTokensForUser(credentials.User.ID, role.User)
|
||||
if err != nil {
|
||||
return apperr.Wrap(err, apperr.CodeInternal, "failed to generate tokens")
|
||||
}
|
||||
data, err = a.verifyToken(tokens.RefreshToken.Token(), false)
|
||||
if err != nil {
|
||||
return apperr.Wrap(err, apperr.CodeInternal, "failed to validate generated refresh token")
|
||||
}
|
||||
var hash string
|
||||
hash, err = a.encryptor.EncryptSecretUsingSum256(ctx, tokens.RefreshToken.Payload)
|
||||
if err != nil {
|
||||
return apperr.Wrap(err, apperr.CodeInternal, "failed to hash refresh token")
|
||||
}
|
||||
stored := dto.StoredRefreshToken{
|
||||
ID: data.TokenID,
|
||||
UserID: data.UserID,
|
||||
TokenHash: hash,
|
||||
Role: data.Role,
|
||||
ExpiresAt: data.ExpiresAt,
|
||||
CreatedAt: data.IssuedAt,
|
||||
}
|
||||
if err = a.refreshTokensRepo.CreateTx(ctx, tx, stored); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &dto.LoginResult{
|
||||
ExpiresAt: data.ExpiresAt,
|
||||
TokenType: "Bearer",
|
||||
User: credentials.User,
|
||||
Tokens: *tokens,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *Auth) VerifyAccessToken(ctx context.Context, req dto.Token) (*dto.UserDataInToken, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return a.verifyToken(&req, true)
|
||||
}
|
||||
|
||||
func (a *Auth) VerifySession(ctx context.Context, token dto.Token) (*dto.UserDataInToken, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data, err := a.verifyTokenClaims(&token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if data.IsAccess {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "invalid session token")
|
||||
}
|
||||
|
||||
stored, err := a.refreshTokensRepo.GetByID(ctx, data.TokenID)
|
||||
if err != nil {
|
||||
if apperr.CodeFromError(err) == apperr.CodeNotFound {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "invalid session")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if err = a.validateStoredSession(ctx, token, data, stored); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (a *Auth) Logout(ctx context.Context, req dto.RefreshToken) error {
|
||||
data, err := a.verifyToken(req.Token(), false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return a.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
|
||||
stored, err := a.activeRefreshTokenTx(ctx, tx, req, data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return a.refreshTokensRepo.RevokeTx(ctx, tx, dto.RevokeRefreshToken{
|
||||
ID: stored.ID,
|
||||
RevokedAt: time.Now(),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func (a *Auth) RefreshTokens(ctx context.Context, req dto.RefreshToken) (*dto.Tokens, error) {
|
||||
data, err := a.verifyToken(req.Token(), false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var tokens *dto.Tokens
|
||||
err = a.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
|
||||
stored, err := a.activeRefreshTokenTx(ctx, tx, req, data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = a.refreshTokensRepo.RevokeTx(ctx, tx, dto.RevokeRefreshToken{
|
||||
ID: stored.ID,
|
||||
RevokedAt: time.Now(),
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
tokens, err = a.createTokensTx(ctx, tx, stored.UserID, stored)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tokens, nil
|
||||
}
|
||||
|
||||
func (a *Auth) verifyToken(token *dto.Token, isAccess bool) (*dto.UserDataInToken, error) {
|
||||
data, err := a.verifyTokenClaims(token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if data.IsAccess != isAccess || data.Role != role.User {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "invalid token")
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (a *Auth) verifyTokenClaims(token *dto.Token) (*dto.UserDataInToken, error) {
|
||||
data, err := a.jwt.ParseVerified(token)
|
||||
if err != nil {
|
||||
return nil, apperr.Wrap(err, apperr.CodeUnauthorized, "invalid token")
|
||||
}
|
||||
if err = data.Validate(); err != nil {
|
||||
return nil, apperr.Wrap(err, apperr.CodeUnauthorized, "invalid token claims")
|
||||
}
|
||||
now := time.Now()
|
||||
if data.IssuedAt.After(now) || !data.ExpiresAt.After(now) {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "invalid token")
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (a *Auth) activeRefreshTokenTx(ctx context.Context, tx pgx.Tx, token dto.RefreshToken, data *dto.UserDataInToken) (*dto.StoredRefreshToken, error) {
|
||||
stored, err := a.refreshTokensRepo.GetByIDForUpdateTx(ctx, tx, data.TokenID)
|
||||
if err != nil {
|
||||
if apperr.CodeFromError(err) == apperr.CodeNotFound {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "invalid refresh token")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Recheck expiry after acquiring the row lock: a concurrent rotation may have held it.
|
||||
if err = a.validateStoredSession(ctx, dto.Token(token), data, stored); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return stored, nil
|
||||
}
|
||||
|
||||
func (a *Auth) validateStoredSession(ctx context.Context, token dto.Token, data *dto.UserDataInToken, stored *dto.StoredRefreshToken) error {
|
||||
now := time.Now()
|
||||
if stored.RevokedAt != nil || !stored.ExpiresAt.After(now) || !data.ExpiresAt.After(now) ||
|
||||
stored.UserID != data.UserID || stored.Role != data.Role {
|
||||
return apperr.New(apperr.CodeUnauthorized, "invalid session")
|
||||
}
|
||||
if err := a.encryptor.CompareHashAndSecretUsingSum256(ctx, stored.TokenHash, token.Payload); err != nil {
|
||||
return apperr.New(apperr.CodeUnauthorized, "invalid session")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Auth) createTokensTx(ctx context.Context, tx pgx.Tx, userID uuid.UUID, previous *dto.StoredRefreshToken) (*dto.Tokens, error) {
|
||||
tokens, err := a.jwt.CreateRefreshAndAccessTokensForUser(userID, role.User)
|
||||
if err != nil {
|
||||
return nil, apperr.Wrap(err, apperr.CodeInternal, "failed to generate tokens")
|
||||
}
|
||||
data, err := a.verifyToken(tokens.RefreshToken.Token(), false)
|
||||
if err != nil {
|
||||
return nil, apperr.Wrap(err, apperr.CodeInternal, "failed to validate generated refresh token")
|
||||
}
|
||||
hash, err := a.encryptor.EncryptSecretUsingSum256(ctx, tokens.RefreshToken.Payload)
|
||||
if err != nil {
|
||||
return nil, apperr.Wrap(err, apperr.CodeInternal, "failed to hash refresh token")
|
||||
}
|
||||
stored := dto.StoredRefreshToken{
|
||||
ID: data.TokenID,
|
||||
UserID: data.UserID,
|
||||
TokenHash: hash,
|
||||
Role: data.Role,
|
||||
ExpiresAt: data.ExpiresAt,
|
||||
CreatedAt: data.IssuedAt,
|
||||
}
|
||||
if previous != nil {
|
||||
stored.UserAgent = previous.UserAgent
|
||||
stored.IPAddress = previous.IPAddress
|
||||
}
|
||||
if err = a.refreshTokensRepo.CreateTx(ctx, tx, stored); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tokens, nil
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
)
|
||||
|
||||
type API interface {
|
||||
CreateChat(ctx context.Context, req dto.CreateChat) (*dto.Chat, error)
|
||||
GetForMember(ctx context.Context, req dto.ChatMember) (*dto.Chat, error)
|
||||
ListForMember(ctx context.Context, req dto.ChatFilters) (*dto.Page[dto.Chat], error)
|
||||
CreateMessage(ctx context.Context, req dto.CreateMessage) (*dto.Message, error)
|
||||
ListForChat(ctx context.Context, req dto.MessageFilters) (*dto.Page[dto.Message], error)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
)
|
||||
|
||||
type chatsRepo interface {
|
||||
CreateTx(ctx context.Context, tx pgx.Tx, req dto.Chat) error
|
||||
GetForMember(ctx context.Context, req dto.ChatMember) (*dto.Chat, error)
|
||||
ListForMember(ctx context.Context, userID uuid.UUID, page dto.PageQuery) ([]dto.Chat, error)
|
||||
}
|
||||
|
||||
type messagesRepo interface {
|
||||
Create(ctx context.Context, req dto.Message) error
|
||||
GetByIDForChat(ctx context.Context, chatID, messageID uuid.UUID) (*dto.Message, error)
|
||||
ListForChat(ctx context.Context, chatID uuid.UUID, page dto.PageQuery) ([]dto.Message, error)
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres/txmanager"
|
||||
)
|
||||
|
||||
var _ API = (*Chat)(nil)
|
||||
|
||||
type Chat struct {
|
||||
tm *txmanager.TransactionManager
|
||||
chatsRepo chatsRepo
|
||||
messagesRepo messagesRepo
|
||||
}
|
||||
|
||||
func New(tm *txmanager.TransactionManager, chatsRepo chatsRepo, messagesRepo messagesRepo) *Chat {
|
||||
return &Chat{tm: tm, chatsRepo: chatsRepo, messagesRepo: messagesRepo}
|
||||
}
|
||||
|
||||
func (c *Chat) CreateChat(ctx context.Context, req dto.CreateChat) (*dto.Chat, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, len(req.MemberIDs))
|
||||
for _, id := range req.MemberIDs {
|
||||
if id == uuid.Nil {
|
||||
return nil, apperr.New(apperr.CodeBadRequest, "invalid chat member")
|
||||
}
|
||||
if _, exists := seen[id]; exists {
|
||||
return nil, apperr.New(apperr.CodeBadRequest, "duplicate chat member")
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
|
||||
if _, included := seen[req.CreatorID]; !included {
|
||||
return nil, apperr.New(apperr.CodeBadRequest, "creator must be a chat member")
|
||||
}
|
||||
|
||||
members := slices.Clone(req.MemberIDs)
|
||||
slices.SortFunc(members, func(a, b uuid.UUID) int {
|
||||
return bytes.Compare(a[:], b[:])
|
||||
})
|
||||
chat := dto.Chat{
|
||||
ID: uuid.New(),
|
||||
Title: req.Title,
|
||||
MemberIDs: members,
|
||||
CreatedAt: time.Now().Truncate(time.Microsecond),
|
||||
}
|
||||
|
||||
if err := c.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
|
||||
return c.chatsRepo.CreateTx(ctx, tx, chat)
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &chat, nil
|
||||
}
|
||||
|
||||
func (c *Chat) GetForMember(ctx context.Context, req dto.ChatMember) (*dto.Chat, error) {
|
||||
chat, err := c.chatsRepo.GetForMember(ctx, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (c *Chat) ListForMember(ctx context.Context, req dto.ChatFilters) (*dto.Page[dto.Chat], error) {
|
||||
limit, err := pageLimit(req.Limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
query := dto.PageQuery{Limit: limit + 1}
|
||||
if req.AfterID != nil {
|
||||
cursor, err := c.GetForMember(ctx, dto.ChatMember{UserID: req.UserID, ChatID: *req.AfterID})
|
||||
if err != nil {
|
||||
return nil, cursorError(err)
|
||||
}
|
||||
query.After = &dto.PagePosition{CreatedAt: cursor.CreatedAt, ID: cursor.ID}
|
||||
}
|
||||
|
||||
items, err := c.chatsRepo.ListForMember(ctx, req.UserID, query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return makePage(items, limit, func(chat dto.Chat) uuid.UUID { return chat.ID }), nil
|
||||
}
|
||||
|
||||
func (c *Chat) CreateMessage(ctx context.Context, req dto.CreateMessage) (*dto.Message, error) {
|
||||
if _, err := c.GetForMember(ctx, dto.ChatMember{UserID: req.SenderID, ChatID: req.ChatID}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
message := dto.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: req.ChatID,
|
||||
SenderID: req.SenderID,
|
||||
Text: req.Text,
|
||||
CreatedAt: time.Now().Truncate(time.Microsecond),
|
||||
}
|
||||
if err := c.messagesRepo.Create(ctx, message); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &message, nil
|
||||
}
|
||||
|
||||
func (c *Chat) ListForChat(ctx context.Context, req dto.MessageFilters) (*dto.Page[dto.Message], error) {
|
||||
if _, err := c.GetForMember(ctx, dto.ChatMember{UserID: req.UserID, ChatID: req.ChatID}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
limit, err := pageLimit(req.Limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
query := dto.PageQuery{Limit: limit + 1}
|
||||
if req.AfterID != nil {
|
||||
cursor, err := c.messagesRepo.GetByIDForChat(ctx, req.ChatID, *req.AfterID)
|
||||
if err != nil {
|
||||
return nil, cursorError(err)
|
||||
}
|
||||
query.After = &dto.PagePosition{CreatedAt: cursor.CreatedAt, ID: cursor.ID}
|
||||
}
|
||||
|
||||
items, err := c.messagesRepo.ListForChat(ctx, req.ChatID, query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return makePage(items, limit, func(message dto.Message) uuid.UUID { return message.ID }), nil
|
||||
}
|
||||
|
||||
func pageLimit(limit *int) (int, error) {
|
||||
size := 50
|
||||
if limit != nil {
|
||||
size = *limit
|
||||
}
|
||||
if size < 1 || size > 100 {
|
||||
return 0, apperr.New(apperr.CodeBadRequest, "invalid limit")
|
||||
}
|
||||
return size, nil
|
||||
}
|
||||
|
||||
func cursorError(err error) error {
|
||||
if apperr.CodeFromError(err) == apperr.CodeNotFound {
|
||||
return apperr.New(apperr.CodeBadRequest, "invalid cursor")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func makePage[T any](items []T, limit int, id func(T) uuid.UUID) *dto.Page[T] {
|
||||
if items == nil {
|
||||
items = make([]T, 0)
|
||||
}
|
||||
page := dto.Page[T]{Items: items}
|
||||
if len(items) > limit {
|
||||
page.Items = items[:limit]
|
||||
cursor := id(page.Items[limit-1])
|
||||
page.NextCursorID = &cursor
|
||||
}
|
||||
return &page
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
)
|
||||
|
||||
type API interface {
|
||||
Create(ctx context.Context, req dto.CreateUser) (dto.User, error)
|
||||
GetByID(ctx context.Context, id uuid.UUID) (dto.User, error)
|
||||
GetByUsername(ctx context.Context, username string) (dto.User, error)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
)
|
||||
|
||||
type userRepo interface {
|
||||
Create(ctx context.Context, req dto.CreateStoredUser) error
|
||||
GetByID(ctx context.Context, id uuid.UUID) (*dto.User, error)
|
||||
GetByUsername(ctx context.Context, username string) (*dto.User, error)
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/encrypting"
|
||||
)
|
||||
|
||||
var (
|
||||
_ API = (*User)(nil)
|
||||
usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
)
|
||||
|
||||
type User struct {
|
||||
encryptor encrypting.Encryptor
|
||||
usersRepo userRepo
|
||||
}
|
||||
|
||||
func New(encryptor encrypting.Encryptor, usersRepo userRepo) *User {
|
||||
return &User{encryptor: encryptor, usersRepo: usersRepo}
|
||||
}
|
||||
|
||||
func (u *User) Create(ctx context.Context, req dto.CreateUser) (dto.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.User{}, err
|
||||
}
|
||||
if !usernamePattern.MatchString(req.Username) || !utf8.ValidString(req.DisplayName) ||
|
||||
strings.TrimSpace(req.DisplayName) == "" || utf8.RuneCountInString(req.DisplayName) > 100 {
|
||||
return dto.User{}, apperr.New(apperr.CodeBadRequest, "invalid user fields")
|
||||
}
|
||||
passwordLen := utf8.RuneCountInString(req.Password)
|
||||
if !utf8.ValidString(req.Password) || strings.TrimSpace(req.Password) == "" || passwordLen < 12 || passwordLen > 128 {
|
||||
return dto.User{}, apperr.New(apperr.CodeBadRequest, "invalid password")
|
||||
}
|
||||
|
||||
id, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
return dto.User{}, apperr.Wrap(err, apperr.CodeInternal, "failed to generate user id")
|
||||
}
|
||||
hash, err := u.encryptor.EncryptSecretUsingArgon2id(ctx, req.Password)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return dto.User{}, ctx.Err()
|
||||
}
|
||||
return dto.User{}, apperr.Wrap(err, apperr.CodeInternal, "failed to hash password")
|
||||
}
|
||||
|
||||
now := time.Now().Truncate(time.Microsecond)
|
||||
user := dto.User{ID: id, Username: req.Username, DisplayName: req.DisplayName, CreatedAt: now}
|
||||
if err = u.usersRepo.Create(ctx, dto.CreateStoredUser{
|
||||
ID: user.ID,
|
||||
Username: user.Username,
|
||||
DisplayName: user.DisplayName,
|
||||
PasswordHash: hash,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}); err != nil {
|
||||
return dto.User{}, err
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (u *User) GetByID(ctx context.Context, id uuid.UUID) (dto.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.User{}, err
|
||||
}
|
||||
if id == uuid.Nil {
|
||||
return dto.User{}, apperr.New(apperr.CodeBadRequest, "invalid user id")
|
||||
}
|
||||
user, err := u.usersRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return dto.User{}, err
|
||||
}
|
||||
return *user, nil
|
||||
}
|
||||
|
||||
func (u *User) GetByUsername(ctx context.Context, username string) (dto.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return dto.User{}, err
|
||||
}
|
||||
if !usernamePattern.MatchString(username) {
|
||||
return dto.User{}, apperr.New(apperr.CodeBadRequest, "invalid username")
|
||||
}
|
||||
user, err := u.usersRepo.GetByUsername(ctx, username)
|
||||
if err != nil {
|
||||
return dto.User{}, err
|
||||
}
|
||||
return *user, nil
|
||||
}
|
||||
@@ -1,14 +1,18 @@
|
||||
CREATE TABLE IF NOT EXISTS users
|
||||
(
|
||||
id UUID PRIMARY KEY,
|
||||
name VARCHAR(64),
|
||||
surname VARCHAR(64),
|
||||
patronymic VARCHAR(64),
|
||||
birthdate DATE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
id UUID PRIMARY KEY,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
username VARCHAR(32) NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
|
||||
CONSTRAINT users_username_unique UNIQUE (username),
|
||||
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
CONSTRAINT users_name_not_blank CHECK (name !~ '^[[:space:]]*$'),
|
||||
CONSTRAINT users_password_hash_not_empty CHECK (password_hash <> '')
|
||||
);
|
||||
|
||||
---- create above / drop below ----
|
||||
|
||||
DROP TABLE IF EXISTS users;
|
||||
DROP TABLE IF EXISTS users;
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
CREATE TABLE IF NOT EXISTS auth_identities
|
||||
(
|
||||
id UUID PRIMARY KEY,
|
||||
role VARCHAR(12) NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
provider TEXT NOT NULL,
|
||||
identifier TEXT NOT NULL,
|
||||
password_hash TEXT,
|
||||
status VARCHAR(24) NOT NULL DEFAULT 'PENDING',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
|
||||
CONSTRAINT fk_auth_identities_users FOREIGN KEY (user_id) REFERENCES users (id),
|
||||
UNIQUE (provider, identifier)
|
||||
);
|
||||
---- create above / drop below ----
|
||||
DROP TABLE IF EXISTS auth_identities;
|
||||
@@ -0,0 +1,14 @@
|
||||
CREATE TABLE IF NOT EXISTS chats
|
||||
(
|
||||
id UUID PRIMARY KEY,
|
||||
title VARCHAR(100) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
|
||||
CONSTRAINT chats_title_not_blank CHECK (title !~ '^[[:space:]]*$')
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_chats_created_at_id ON chats (created_at, id);
|
||||
|
||||
---- create above / drop below ----
|
||||
|
||||
DROP TABLE IF EXISTS chats;
|
||||
@@ -0,0 +1,15 @@
|
||||
CREATE TABLE IF NOT EXISTS chat_members
|
||||
(
|
||||
chat_id UUID NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
|
||||
PRIMARY KEY (chat_id, user_id),
|
||||
CONSTRAINT chat_members_chat_fk FOREIGN KEY (chat_id) REFERENCES chats (id) ON DELETE NO ACTION,
|
||||
CONSTRAINT chat_members_user_fk FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE NO ACTION
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_chat_members_user_id_chat_id ON chat_members (user_id, chat_id);
|
||||
|
||||
---- create above / drop below ----
|
||||
|
||||
DROP TABLE IF EXISTS chat_members;
|
||||
@@ -0,0 +1,18 @@
|
||||
CREATE TABLE IF NOT EXISTS messages
|
||||
(
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL,
|
||||
sender_id UUID NOT NULL,
|
||||
text VARCHAR(4000) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
|
||||
CONSTRAINT messages_text_not_blank CHECK (text !~ '^[[:space:]]*$'),
|
||||
CONSTRAINT messages_sender_member_fk FOREIGN KEY (chat_id, sender_id)
|
||||
REFERENCES chat_members (chat_id, user_id) ON DELETE NO ACTION
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_chat_id_created_at_id ON messages (chat_id, created_at, id);
|
||||
|
||||
---- create above / drop below ----
|
||||
|
||||
DROP TABLE IF EXISTS messages;
|
||||
@@ -0,0 +1,8 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"embed"
|
||||
)
|
||||
|
||||
//go:embed *.sql
|
||||
var Migrations embed.FS
|
||||
@@ -30,7 +30,7 @@ func newAPI(t *testing.T) *apiClient {
|
||||
chats := inmemory2.NewChatCache(users)
|
||||
messages := inmemory2.NewMessageCache(chats)
|
||||
base := controller.NewBaseHandler(router)
|
||||
controller.NewUserHandler(base, users).RegisterRoutes()
|
||||
controller.NewAuthHandler(base, users).RegisterRoutes()
|
||||
controller.NewChatHandler(base, users, chats, messages).RegisterRoutes()
|
||||
|
||||
return &apiClient{handler: router}
|
||||
|
||||
Reference in New Issue
Block a user