forked from mtusi2026/mtusi2026lab2
реализован уровень 3
This commit is contained in:
@@ -0,0 +1,264 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
HTTPHost string
|
||||
HTTPPort string
|
||||
|
||||
SessionTTL time.Duration
|
||||
|
||||
DatabaseURL string
|
||||
DatabaseMaxConns int32
|
||||
DatabaseMinConns int32
|
||||
DatabaseMaxConnLifetime time.Duration
|
||||
DatabaseMaxConnIdleTime time.Duration
|
||||
DatabaseHealthCheckPeriod time.Duration
|
||||
DatabaseConnectTimeout time.Duration
|
||||
DatabaseQueryTimeout time.Duration
|
||||
|
||||
ReadinessTimeout time.Duration
|
||||
ShutdownTimeout time.Duration
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
sessionTTL, err := secondsDurationFromEnv(
|
||||
"SESSION_TTL_SECONDS",
|
||||
3600,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseURL, err := requiredValueOrFile(
|
||||
"DATABASE_URL",
|
||||
"DATABASE_URL_FILE",
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseMaxConns, err := int32FromEnv("DB_MAX_CONNS", 10, 1)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseMinConns, err := int32FromEnv("DB_MIN_CONNS", 2, 0)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseMaxConnLifetime, err := durationFromEnv(
|
||||
"DB_MAX_CONN_LIFETIME",
|
||||
30*time.Minute,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseMaxConnIdleTime, err := durationFromEnv(
|
||||
"DB_MAX_CONN_IDLE_TIME",
|
||||
5*time.Minute,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseHealthCheckPeriod, err := durationFromEnv(
|
||||
"DB_HEALTH_CHECK_PERIOD",
|
||||
30*time.Second,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseConnectTimeout, err := durationFromEnv(
|
||||
"DB_CONNECT_TIMEOUT",
|
||||
5*time.Second,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseQueryTimeout, err := durationFromEnv(
|
||||
"DB_QUERY_TIMEOUT",
|
||||
3*time.Second,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
readinessTimeout, err := durationFromEnv(
|
||||
"READINESS_TIMEOUT",
|
||||
2*time.Second,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
shutdownTimeout, err := durationFromEnv(
|
||||
"SHUTDOWN_TIMEOUT",
|
||||
10*time.Second,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
if databaseMinConns > databaseMaxConns {
|
||||
return Config{}, errors.New(
|
||||
"DB_MIN_CONNS must not be greater than DB_MAX_CONNS",
|
||||
)
|
||||
}
|
||||
|
||||
return Config{
|
||||
HTTPHost: envOrDefault("APP_HOST", "0.0.0.0"),
|
||||
HTTPPort: envOrDefault("APP_PORT", "8080"),
|
||||
SessionTTL: sessionTTL,
|
||||
|
||||
DatabaseURL: databaseURL,
|
||||
DatabaseMaxConns: databaseMaxConns,
|
||||
DatabaseMinConns: databaseMinConns,
|
||||
DatabaseMaxConnLifetime: databaseMaxConnLifetime,
|
||||
DatabaseMaxConnIdleTime: databaseMaxConnIdleTime,
|
||||
DatabaseHealthCheckPeriod: databaseHealthCheckPeriod,
|
||||
DatabaseConnectTimeout: databaseConnectTimeout,
|
||||
DatabaseQueryTimeout: databaseQueryTimeout,
|
||||
|
||||
ReadinessTimeout: readinessTimeout,
|
||||
ShutdownTimeout: shutdownTimeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c Config) HTTPAddress() string {
|
||||
return net.JoinHostPort(c.HTTPHost, c.HTTPPort)
|
||||
}
|
||||
|
||||
func requiredValueOrFile(valueEnv, fileEnv string) (string, error) {
|
||||
value, valueExists := os.LookupEnv(valueEnv)
|
||||
filePath, fileExists := os.LookupEnv(fileEnv)
|
||||
|
||||
if valueExists && fileExists {
|
||||
return "", fmt.Errorf(
|
||||
"%s and %s must not be set at the same time",
|
||||
valueEnv,
|
||||
fileEnv,
|
||||
)
|
||||
}
|
||||
|
||||
if valueExists {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("%s must not be empty", valueEnv)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
if fileExists {
|
||||
filePath = strings.TrimSpace(filePath)
|
||||
if filePath == "" {
|
||||
return "", fmt.Errorf("%s must not be empty", fileEnv)
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(filePath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read %s: %w", fileEnv, err)
|
||||
}
|
||||
|
||||
value = strings.TrimSpace(string(data))
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("file from %s must not be empty", fileEnv)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("%s or %s must be set", valueEnv, fileEnv)
|
||||
}
|
||||
|
||||
func envOrDefault(name, fallback string) string {
|
||||
value := strings.TrimSpace(os.Getenv(name))
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
func int32FromEnv(name string, fallback, minimum int32) (int32, error) {
|
||||
raw := strings.TrimSpace(os.Getenv(name))
|
||||
if raw == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
|
||||
value, err := strconv.ParseInt(raw, 10, 32)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("%s must be an integer: %w", name, err)
|
||||
}
|
||||
|
||||
if value < int64(minimum) {
|
||||
return 0, fmt.Errorf("%s must be at least %d", name, minimum)
|
||||
}
|
||||
|
||||
return int32(value), nil
|
||||
}
|
||||
|
||||
func durationFromEnv(name string, fallback time.Duration) (time.Duration, error) {
|
||||
raw := strings.TrimSpace(os.Getenv(name))
|
||||
if raw == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
|
||||
value, err := time.ParseDuration(raw)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf(
|
||||
"%s must be a Go duration such as 3s or 5m: %w",
|
||||
name,
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
if value <= 0 {
|
||||
return 0, fmt.Errorf("%s must be positive", name)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func secondsDurationFromEnv(
|
||||
name string,
|
||||
fallbackSeconds int64,
|
||||
) (time.Duration, error) {
|
||||
raw := strings.TrimSpace(os.Getenv(name))
|
||||
if raw == "" {
|
||||
raw = strconv.FormatInt(fallbackSeconds, 10)
|
||||
}
|
||||
|
||||
seconds, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf(
|
||||
"%s must be an integer number of seconds: %w",
|
||||
name,
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
if seconds <= 0 {
|
||||
return 0, fmt.Errorf("%s must be positive", name)
|
||||
}
|
||||
|
||||
duration, err := time.ParseDuration(raw + "s")
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("%s is too large: %w", name, err)
|
||||
}
|
||||
|
||||
return duration, nil
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab2/internal/config"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func Open(
|
||||
ctx context.Context,
|
||||
cfg config.Config,
|
||||
) (*pgxpool.Pool, error) {
|
||||
poolConfig, err := pgxpool.ParseConfig(cfg.DatabaseURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse PostgreSQL configuration: %w", err)
|
||||
}
|
||||
|
||||
poolConfig.MaxConns = cfg.DatabaseMaxConns
|
||||
poolConfig.MinConns = cfg.DatabaseMinConns
|
||||
poolConfig.MaxConnLifetime = cfg.DatabaseMaxConnLifetime
|
||||
poolConfig.MaxConnIdleTime = cfg.DatabaseMaxConnIdleTime
|
||||
poolConfig.HealthCheckPeriod = cfg.DatabaseHealthCheckPeriod
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create PostgreSQL pool: %w", err)
|
||||
}
|
||||
|
||||
// NewWithConfig создаёт структуру пула, но не гарантирует,
|
||||
// что PostgreSQL уже доступен. Ping обеспечивает fail-fast.
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping PostgreSQL: %w", err)
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
+46
-13
@@ -23,6 +23,13 @@ type User struct {
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
User User `json:"user"`
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
@@ -71,6 +78,10 @@ func ValidateChatInput(title string, memberIDs []string, callerID string) error
|
||||
return fmt.Errorf("member_ids cannot be empty")
|
||||
}
|
||||
|
||||
if len(memberIDs) > 100 {
|
||||
return fmt.Errorf("member_ids must contain at most 100 users")
|
||||
}
|
||||
|
||||
hasCaller := false
|
||||
seen := make(map[string]bool)
|
||||
|
||||
@@ -78,6 +89,7 @@ func ValidateChatInput(title string, memberIDs []string, callerID string) error
|
||||
if _, err := uuid.Parse(id); err != nil {
|
||||
return fmt.Errorf("invalid member uuid: %s", id)
|
||||
}
|
||||
|
||||
if seen[id] {
|
||||
return fmt.Errorf("duplicate member_id: %s", id)
|
||||
}
|
||||
@@ -112,38 +124,59 @@ type CursorData struct {
|
||||
ChatID string
|
||||
}
|
||||
|
||||
// EncodeCursor превращает время, message_id и chat_id в непрозрачную base64 строку
|
||||
const messageCursorVersion = "v1"
|
||||
|
||||
func EncodeCursor(createdAt time.Time, messageID, chatID string) string {
|
||||
raw := fmt.Sprintf("%s|%s|%s", createdAt.Format(time.RFC3339Nano), messageID, chatID)
|
||||
return base64.StdEncoding.EncodeToString([]byte(raw))
|
||||
raw := fmt.Sprintf(
|
||||
"%s|%s|%s|%s",
|
||||
messageCursorVersion,
|
||||
createdAt.UTC().Format(time.RFC3339Nano),
|
||||
messageID,
|
||||
chatID,
|
||||
)
|
||||
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
// DecodeCursor декодирует строку курсора и проверяет, что он принадлежит именно этому чату
|
||||
func DecodeCursor(cursorStr string, expectedChatID string) (*CursorData, error) {
|
||||
bytes, err := base64.StdEncoding.DecodeString(cursorStr)
|
||||
func DecodeCursor(
|
||||
cursorStr string,
|
||||
expectedChatID string,
|
||||
) (*CursorData, error) {
|
||||
raw, err := base64.RawURLEncoding.DecodeString(cursorStr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid base64 cursor")
|
||||
}
|
||||
|
||||
parts := strings.Split(string(bytes), "|")
|
||||
if len(parts) != 3 {
|
||||
parts := strings.Split(string(raw), "|")
|
||||
if len(parts) != 4 {
|
||||
return nil, fmt.Errorf("malformed cursor")
|
||||
}
|
||||
|
||||
t, err := time.Parse(time.RFC3339Nano, parts[0])
|
||||
if parts[0] != messageCursorVersion {
|
||||
return nil, fmt.Errorf("unsupported cursor version")
|
||||
}
|
||||
|
||||
createdAt, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid cursor timestamp")
|
||||
}
|
||||
|
||||
chatID := parts[2]
|
||||
//защита из контракта: курсор от другого чата должен давать 400
|
||||
messageID := parts[2]
|
||||
chatID := parts[3]
|
||||
|
||||
if _, err := uuid.Parse(messageID); err != nil {
|
||||
return nil, fmt.Errorf("invalid cursor message_id")
|
||||
}
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
return nil, fmt.Errorf("invalid cursor chat_id")
|
||||
}
|
||||
if chatID != expectedChatID {
|
||||
return nil, fmt.Errorf("cursor belongs to another chat")
|
||||
}
|
||||
|
||||
return &CursorData{
|
||||
CreatedAt: t,
|
||||
MessageID: parts[1],
|
||||
CreatedAt: createdAt.UTC(),
|
||||
MessageID: messageID,
|
||||
ChatID: chatID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonMemory uint32 = 19 * 1024
|
||||
argonIterations uint32 = 2
|
||||
argonParallelism uint8 = 1
|
||||
argonSaltLength = 16
|
||||
argonKeyLength uint32 = 32
|
||||
|
||||
minPasswordLength = 12
|
||||
maxPasswordLength = 128
|
||||
)
|
||||
|
||||
var ErrInvalidPasswordHash = errors.New("invalid password hash")
|
||||
|
||||
func ValidatePassword(password string) error {
|
||||
if !utf8.ValidString(password) {
|
||||
return errors.New("password must be valid UTF-8")
|
||||
}
|
||||
|
||||
length := utf8.RuneCountInString(password)
|
||||
if length < minPasswordLength || length > maxPasswordLength {
|
||||
return fmt.Errorf(
|
||||
"password length must be between %d and %d code points",
|
||||
minPasswordLength,
|
||||
maxPasswordLength,
|
||||
)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
if err := ValidatePassword(password); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
salt := make([]byte, argonSaltLength)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate password salt: %w", err)
|
||||
}
|
||||
|
||||
hash := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
argonIterations,
|
||||
argonMemory,
|
||||
argonParallelism,
|
||||
argonKeyLength,
|
||||
)
|
||||
|
||||
encodedSalt := base64.RawStdEncoding.EncodeToString(salt)
|
||||
encodedHash := base64.RawStdEncoding.EncodeToString(hash)
|
||||
|
||||
encoded := fmt.Sprintf(
|
||||
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version,
|
||||
argonMemory,
|
||||
argonIterations,
|
||||
argonParallelism,
|
||||
encodedSalt,
|
||||
encodedHash,
|
||||
)
|
||||
|
||||
return encoded, nil
|
||||
}
|
||||
|
||||
func VerifyPassword(
|
||||
password string,
|
||||
encodedHash string,
|
||||
) (bool, error) {
|
||||
parameters, salt, expectedHash, err := decodePasswordHash(encodedHash)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
actualHash := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
parameters.iterations,
|
||||
parameters.memory,
|
||||
parameters.parallelism,
|
||||
uint32(len(expectedHash)),
|
||||
)
|
||||
|
||||
matches := subtle.ConstantTimeCompare(
|
||||
actualHash,
|
||||
expectedHash,
|
||||
) == 1
|
||||
|
||||
return matches, nil
|
||||
}
|
||||
|
||||
type argonParameters struct {
|
||||
memory uint32
|
||||
iterations uint32
|
||||
parallelism uint8
|
||||
}
|
||||
|
||||
func decodePasswordHash(
|
||||
encodedHash string,
|
||||
) (argonParameters, []byte, []byte, error) {
|
||||
parts := strings.Split(encodedHash, "$")
|
||||
if len(parts) != 6 ||
|
||||
parts[0] != "" ||
|
||||
parts[1] != "argon2id" {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
if version != argon2.Version {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
var parameters argonParameters
|
||||
if _, err := fmt.Sscanf(
|
||||
parts[3],
|
||||
"m=%d,t=%d,p=%d",
|
||||
¶meters.memory,
|
||||
¶meters.iterations,
|
||||
¶meters.parallelism,
|
||||
); err != nil {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
// Ограничения не позволяют повреждённой строке из БД запросить
|
||||
// гигантский объём памяти или процессорного времени.
|
||||
if parameters.memory < 8*1024 ||
|
||||
parameters.memory > 256*1024 ||
|
||||
parameters.iterations < 1 ||
|
||||
parameters.iterations > 10 ||
|
||||
parameters.parallelism < 1 ||
|
||||
parameters.parallelism > 8 {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil || len(salt) < 16 || len(salt) > 64 {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
hash, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil || len(hash) < 16 || len(hash) > 64 {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
return parameters, salt, hash, nil
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPasswordHashAndVerify(t *testing.T) {
|
||||
password := "Correct-password-123"
|
||||
|
||||
encodedHash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatalf("HashPassword returned error: %v", err)
|
||||
}
|
||||
|
||||
if strings.Contains(encodedHash, password) {
|
||||
t.Fatal("encoded hash contains plaintext password")
|
||||
}
|
||||
|
||||
matches, err := VerifyPassword(password, encodedHash)
|
||||
if err != nil {
|
||||
t.Fatalf("VerifyPassword returned error: %v", err)
|
||||
}
|
||||
if !matches {
|
||||
t.Fatal("correct password did not match")
|
||||
}
|
||||
|
||||
matches, err = VerifyPassword("Wrong-password-123", encodedHash)
|
||||
if err != nil {
|
||||
t.Fatalf("VerifyPassword returned error: %v", err)
|
||||
}
|
||||
if matches {
|
||||
t.Fatal("wrong password matched")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordHashesUseDifferentSalts(t *testing.T) {
|
||||
password := "Correct-password-123"
|
||||
|
||||
firstHash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatalf("first HashPassword returned error: %v", err)
|
||||
}
|
||||
|
||||
secondHash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatalf("second HashPassword returned error: %v", err)
|
||||
}
|
||||
|
||||
if firstHash == secondHash {
|
||||
t.Fatal("equal passwords produced equal encoded hashes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordValidation(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
password string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "minimum length",
|
||||
password: "123456789012",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "unicode",
|
||||
password: "пароль-проверка-123",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "colon is allowed",
|
||||
password: "password:with:colon",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "too short",
|
||||
password: "short",
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
err := ValidatePassword(testCase.password)
|
||||
|
||||
if testCase.wantErr && err == nil {
|
||||
t.Fatal("expected validation error")
|
||||
}
|
||||
if !testCase.wantErr && err != nil {
|
||||
t.Fatalf("unexpected validation error: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMalformedPasswordHash(t *testing.T) {
|
||||
_, err := VerifyPassword(
|
||||
"Correct-password-123",
|
||||
"not-an-argon2-hash",
|
||||
)
|
||||
if err == nil {
|
||||
t.Fatal("expected malformed hash error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
const sessionTokenBytes = 32
|
||||
|
||||
func GenerateSessionToken() (string, []byte, error) {
|
||||
randomBytes := make([]byte, sessionTokenBytes)
|
||||
|
||||
if _, err := rand.Read(randomBytes); err != nil {
|
||||
return "", nil, fmt.Errorf("generate session token: %w", err)
|
||||
}
|
||||
|
||||
token := base64.RawURLEncoding.EncodeToString(randomBytes)
|
||||
tokenHash := HashSessionToken(token)
|
||||
|
||||
return token, tokenHash, nil
|
||||
}
|
||||
|
||||
func HashSessionToken(token string) []byte {
|
||||
digest := sha256.Sum256([]byte(token))
|
||||
|
||||
hash := make([]byte, len(digest))
|
||||
copy(hash, digest[:])
|
||||
|
||||
return hash
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGenerateSessionToken(t *testing.T) {
|
||||
firstToken, firstHash, err := GenerateSessionToken()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateSessionToken returned error: %v", err)
|
||||
}
|
||||
|
||||
secondToken, secondHash, err := GenerateSessionToken()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateSessionToken returned error: %v", err)
|
||||
}
|
||||
|
||||
if firstToken == secondToken {
|
||||
t.Fatal("generated session tokens are equal")
|
||||
}
|
||||
|
||||
if bytes.Equal(firstHash, secondHash) {
|
||||
t.Fatal("generated session token hashes are equal")
|
||||
}
|
||||
|
||||
if len(firstHash) != 32 {
|
||||
t.Fatalf("expected 32-byte token hash, got %d", len(firstHash))
|
||||
}
|
||||
|
||||
recalculatedHash := HashSessionToken(firstToken)
|
||||
if !bytes.Equal(firstHash, recalculatedHash) {
|
||||
t.Fatal("token hash is not reproducible")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package store
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrInvalidCursor = errors.New("invalid cursor")
|
||||
)
|
||||
@@ -11,12 +11,6 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = fmt.Errorf("not found")
|
||||
ErrConflict = fmt.Errorf("conflict")
|
||||
ErrInvalidCursor = fmt.Errorf("invalid cursor")
|
||||
)
|
||||
|
||||
type MemoryStore struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
@@ -81,7 +75,11 @@ func (s *MemoryStore) CreateChat(title string, memberIDs []string) (domain.Chat,
|
||||
//все участники рил существуют
|
||||
for _, memberID := range memberIDs {
|
||||
if _, exists := s.usersByID[memberID]; !exists {
|
||||
return domain.Chat{}, fmt.Errorf("member not found: %s", memberID)
|
||||
return domain.Chat{}, fmt.Errorf(
|
||||
"%w: member %s",
|
||||
ErrNotFound,
|
||||
memberID,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,9 +284,13 @@ func (s *MemoryStore) GetMessages(
|
||||
if cursorStr != "" {
|
||||
decodedCursor, err := domain.DecodeCursor(cursorStr, chatID)
|
||||
if err != nil {
|
||||
return domain.MessagePage{},
|
||||
fmt.Errorf("invalid cursor: %w", err)
|
||||
return domain.MessagePage{}, fmt.Errorf(
|
||||
"%w: %v",
|
||||
ErrInvalidCursor,
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
cursorData = decodedCursor
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
)
|
||||
|
||||
type memorySession struct {
|
||||
userID string
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
type MemoryRepository struct {
|
||||
legacy *MemoryStore
|
||||
|
||||
mu sync.RWMutex
|
||||
passwordByUserID map[string]string
|
||||
userIDByUsername map[string]string
|
||||
sessionsByHashKey map[[32]byte]memorySession
|
||||
}
|
||||
|
||||
func NewMemoryRepository(legacy *MemoryStore) *MemoryRepository {
|
||||
return &MemoryRepository{
|
||||
legacy: legacy,
|
||||
passwordByUserID: make(map[string]string),
|
||||
userIDByUsername: make(map[string]string),
|
||||
sessionsByHashKey: make(map[[32]byte]memorySession),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) CreateUser(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
displayName string,
|
||||
passwordHash string,
|
||||
) (domain.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
|
||||
user, err := r.legacy.CreateUser(username, displayName)
|
||||
if err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
r.passwordByUserID[user.ID] = passwordHash
|
||||
r.userIDByUsername[user.Username] = user.ID
|
||||
r.mu.Unlock()
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetUserByID(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
) (domain.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
|
||||
return r.legacy.GetUserByID(userID)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetUserByUsername(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
) (domain.User, string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.User{}, "", err
|
||||
}
|
||||
|
||||
r.mu.RLock()
|
||||
userID, exists := r.userIDByUsername[username]
|
||||
passwordHash := r.passwordByUserID[userID]
|
||||
r.mu.RUnlock()
|
||||
|
||||
if !exists {
|
||||
return domain.User{}, "", ErrNotFound
|
||||
}
|
||||
|
||||
user, err := r.legacy.GetUserByID(userID)
|
||||
if err != nil {
|
||||
return domain.User{}, "", err
|
||||
}
|
||||
|
||||
return user, passwordHash, nil
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) CreateChat(
|
||||
ctx context.Context,
|
||||
title string,
|
||||
memberIDs []string,
|
||||
) (domain.Chat, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
|
||||
return r.legacy.CreateChat(title, memberIDs)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetChatByID(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
) (domain.Chat, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
|
||||
return r.legacy.GetChatByID(chatID, callerID)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetChatsForUser(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
limit int,
|
||||
cursor string,
|
||||
) (domain.ChatPage, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.ChatPage{}, err
|
||||
}
|
||||
|
||||
return r.legacy.GetChatsForUser(userID, limit, cursor)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) CreateMessage(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
senderID string,
|
||||
text string,
|
||||
) (domain.Message, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
|
||||
return r.legacy.CreateMessage(chatID, senderID, text)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetMessages(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
limit int,
|
||||
cursor string,
|
||||
) (domain.MessagePage, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.MessagePage{}, err
|
||||
}
|
||||
|
||||
return r.legacy.GetMessages(
|
||||
chatID,
|
||||
callerID,
|
||||
limit,
|
||||
cursor,
|
||||
)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) CreateSession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
userID string,
|
||||
expiresAt time.Time,
|
||||
) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
key, err := memoryTokenHashKey(tokenHash)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
r.sessionsByHashKey[key] = memorySession{
|
||||
userID: userID,
|
||||
expiresAt: expiresAt,
|
||||
}
|
||||
r.mu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetUserBySession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) (domain.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
|
||||
key, err := memoryTokenHashKey(tokenHash)
|
||||
if err != nil {
|
||||
return domain.User{}, ErrNotFound
|
||||
}
|
||||
|
||||
r.mu.RLock()
|
||||
session, exists := r.sessionsByHashKey[key]
|
||||
r.mu.RUnlock()
|
||||
|
||||
if !exists || !session.expiresAt.After(time.Now().UTC()) {
|
||||
return domain.User{}, ErrNotFound
|
||||
}
|
||||
|
||||
return r.legacy.GetUserByID(session.userID)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) DeleteSession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
key, err := memoryTokenHashKey(tokenHash)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
delete(r.sessionsByHashKey, key)
|
||||
r.mu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func memoryTokenHashKey(tokenHash []byte) ([32]byte, error) {
|
||||
var key [32]byte
|
||||
|
||||
if len(tokenHash) != len(key) {
|
||||
return key, fmt.Errorf(
|
||||
"session token hash must contain %d bytes",
|
||||
len(key),
|
||||
)
|
||||
}
|
||||
|
||||
copy(key[:], tokenHash)
|
||||
|
||||
return key, nil
|
||||
}
|
||||
|
||||
var _ Repository = (*MemoryRepository)(nil)
|
||||
@@ -0,0 +1,40 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type PostgreSQLStore struct {
|
||||
pool *pgxpool.Pool
|
||||
queryTimeout time.Duration
|
||||
}
|
||||
|
||||
func NewPostgreSQLStore(
|
||||
pool *pgxpool.Pool,
|
||||
queryTimeout time.Duration,
|
||||
) *PostgreSQLStore {
|
||||
return &PostgreSQLStore{
|
||||
pool: pool,
|
||||
queryTimeout: queryTimeout,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) Ping(ctx context.Context) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
return s.pool.Ping(queryContext)
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) Close() {
|
||||
s.pool.Close()
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) withTimeout(
|
||||
ctx context.Context,
|
||||
) (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(ctx, s.queryTimeout)
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) CreateChat(
|
||||
ctx context.Context,
|
||||
title string,
|
||||
memberIDs []string,
|
||||
) (domain.Chat, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
transaction, err := s.pool.Begin(queryContext)
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf(
|
||||
"begin create chat transaction: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = transaction.Rollback(queryContext)
|
||||
}()
|
||||
|
||||
// Проверяем участников внутри той же транзакции, в которой
|
||||
// создаются чат и строки членства.
|
||||
for _, memberID := range memberIDs {
|
||||
var exists bool
|
||||
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM users
|
||||
WHERE id = $1
|
||||
)
|
||||
`,
|
||||
memberID,
|
||||
).Scan(&exists)
|
||||
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf(
|
||||
"check chat member %s: %w",
|
||||
memberID,
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
if !exists {
|
||||
return domain.Chat{}, fmt.Errorf(
|
||||
"%w: member %s",
|
||||
ErrNotFound,
|
||||
memberID,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
chat := domain.Chat{
|
||||
ID: uuid.NewString(),
|
||||
Title: title,
|
||||
MemberIDs: append([]string(nil), memberIDs...),
|
||||
}
|
||||
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO chats (
|
||||
id,
|
||||
title
|
||||
)
|
||||
VALUES ($1, $2)
|
||||
RETURNING created_at
|
||||
`,
|
||||
chat.ID,
|
||||
chat.Title,
|
||||
).Scan(&chat.CreatedAt)
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf("insert chat: %w", err)
|
||||
}
|
||||
|
||||
for position, memberID := range memberIDs {
|
||||
_, err = transaction.Exec(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO chat_members (
|
||||
chat_id,
|
||||
user_id,
|
||||
position
|
||||
)
|
||||
VALUES ($1, $2, $3)
|
||||
`,
|
||||
chat.ID,
|
||||
memberID,
|
||||
position,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf(
|
||||
"insert chat member %s: %w",
|
||||
memberID,
|
||||
err,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if err = transaction.Commit(queryContext); err != nil {
|
||||
return domain.Chat{}, fmt.Errorf(
|
||||
"commit create chat transaction: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetChatByID(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
) (domain.Chat, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var chat domain.Chat
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
chat.id::text,
|
||||
chat.title,
|
||||
chat.created_at,
|
||||
array_agg(
|
||||
member.user_id::text
|
||||
ORDER BY member.position
|
||||
)
|
||||
FROM chats AS chat
|
||||
JOIN chat_members AS caller
|
||||
ON caller.chat_id = chat.id
|
||||
AND caller.user_id = $2
|
||||
JOIN chat_members AS member
|
||||
ON member.chat_id = chat.id
|
||||
WHERE chat.id = $1
|
||||
GROUP BY
|
||||
chat.id,
|
||||
chat.title,
|
||||
chat.created_at
|
||||
`,
|
||||
chatID,
|
||||
callerID,
|
||||
).Scan(
|
||||
&chat.ID,
|
||||
&chat.Title,
|
||||
&chat.CreatedAt,
|
||||
&chat.MemberIDs,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Chat{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf("select chat by id: %w", err)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetChatsForUser(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
limit int,
|
||||
cursorString string,
|
||||
) (domain.ChatPage, error) {
|
||||
var cursor *domain.ChatCursorData
|
||||
|
||||
if cursorString != "" {
|
||||
decodedCursor, err := domain.DecodeChatCursor(
|
||||
cursorString,
|
||||
userID,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.ChatPage{}, fmt.Errorf(
|
||||
"%w: %v",
|
||||
ErrInvalidCursor,
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
cursor = decodedCursor
|
||||
}
|
||||
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
|
||||
if cursor == nil {
|
||||
rows, err = s.pool.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
chat.id::text,
|
||||
chat.title,
|
||||
chat.created_at,
|
||||
array_agg(
|
||||
member.user_id::text
|
||||
ORDER BY member.position
|
||||
)
|
||||
FROM chat_members AS own_membership
|
||||
JOIN chats AS chat
|
||||
ON chat.id = own_membership.chat_id
|
||||
JOIN chat_members AS member
|
||||
ON member.chat_id = chat.id
|
||||
WHERE own_membership.user_id = $1
|
||||
GROUP BY
|
||||
chat.id,
|
||||
chat.title,
|
||||
chat.created_at
|
||||
ORDER BY
|
||||
chat.created_at,
|
||||
chat.id
|
||||
LIMIT $2
|
||||
`,
|
||||
userID,
|
||||
limit+1,
|
||||
)
|
||||
} else {
|
||||
rows, err = s.pool.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
chat.id::text,
|
||||
chat.title,
|
||||
chat.created_at,
|
||||
array_agg(
|
||||
member.user_id::text
|
||||
ORDER BY member.position
|
||||
)
|
||||
FROM chat_members AS own_membership
|
||||
JOIN chats AS chat
|
||||
ON chat.id = own_membership.chat_id
|
||||
JOIN chat_members AS member
|
||||
ON member.chat_id = chat.id
|
||||
WHERE own_membership.user_id = $1
|
||||
AND (chat.created_at, chat.id) > ($2, $3)
|
||||
GROUP BY
|
||||
chat.id,
|
||||
chat.title,
|
||||
chat.created_at
|
||||
ORDER BY
|
||||
chat.created_at,
|
||||
chat.id
|
||||
LIMIT $4
|
||||
`,
|
||||
userID,
|
||||
cursor.CreatedAt,
|
||||
cursor.ChatID,
|
||||
limit+1,
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return domain.ChatPage{}, fmt.Errorf(
|
||||
"query chats for user: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
page := domain.ChatPage{
|
||||
Items: make([]domain.Chat, 0, limit),
|
||||
}
|
||||
|
||||
for rows.Next() {
|
||||
var chat domain.Chat
|
||||
|
||||
if err := rows.Scan(
|
||||
&chat.ID,
|
||||
&chat.Title,
|
||||
&chat.CreatedAt,
|
||||
&chat.MemberIDs,
|
||||
); err != nil {
|
||||
return domain.ChatPage{}, fmt.Errorf(
|
||||
"scan chat page: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
page.Items = append(page.Items, chat)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return domain.ChatPage{}, fmt.Errorf(
|
||||
"iterate chat page: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
if len(page.Items) > limit {
|
||||
page.Items = page.Items[:limit]
|
||||
|
||||
lastChat := page.Items[len(page.Items)-1]
|
||||
nextCursor := domain.EncodeChatCursor(
|
||||
lastChat.CreatedAt,
|
||||
lastChat.ID,
|
||||
userID,
|
||||
)
|
||||
page.NextCursor = &nextCursor
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) CreateMessage(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
senderID string,
|
||||
text string,
|
||||
) (domain.Message, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
message := domain.Message{
|
||||
ID: uuid.NewString(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
}
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO messages (
|
||||
id,
|
||||
chat_id,
|
||||
sender_id,
|
||||
text
|
||||
)
|
||||
SELECT
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4
|
||||
FROM chat_members
|
||||
WHERE chat_id = $2
|
||||
AND user_id = $3
|
||||
RETURNING created_at
|
||||
`,
|
||||
message.ID,
|
||||
message.ChatID,
|
||||
message.SenderID,
|
||||
message.Text,
|
||||
).Scan(&message.CreatedAt)
|
||||
|
||||
if err == nil {
|
||||
return message, nil
|
||||
}
|
||||
|
||||
// INSERT ... SELECT возвращает zero rows, если отправитель
|
||||
// не является участником указанного чата.
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Message{}, ErrNotFound
|
||||
}
|
||||
|
||||
return domain.Message{}, fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetMessages(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
limit int,
|
||||
cursorString string,
|
||||
) (domain.MessagePage, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var isMember bool
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = $1
|
||||
AND user_id = $2
|
||||
)
|
||||
`,
|
||||
chatID,
|
||||
callerID,
|
||||
).Scan(&isMember)
|
||||
if err != nil {
|
||||
return domain.MessagePage{}, fmt.Errorf(
|
||||
"check chat membership: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
if !isMember {
|
||||
return domain.MessagePage{}, ErrNotFound
|
||||
}
|
||||
|
||||
var cursor *domain.CursorData
|
||||
|
||||
if cursorString != "" {
|
||||
decodedCursor, err := domain.DecodeCursor(
|
||||
cursorString,
|
||||
chatID,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.MessagePage{}, fmt.Errorf(
|
||||
"%w: %v",
|
||||
ErrInvalidCursor,
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
cursor = decodedCursor
|
||||
}
|
||||
|
||||
var rows pgx.Rows
|
||||
|
||||
if cursor == nil {
|
||||
rows, err = s.pool.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
id::text,
|
||||
chat_id::text,
|
||||
sender_id::text,
|
||||
text,
|
||||
created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
ORDER BY
|
||||
created_at,
|
||||
id
|
||||
LIMIT $2
|
||||
`,
|
||||
chatID,
|
||||
limit+1,
|
||||
)
|
||||
} else {
|
||||
rows, err = s.pool.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
id::text,
|
||||
chat_id::text,
|
||||
sender_id::text,
|
||||
text,
|
||||
created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND (created_at, id) > ($2, $3)
|
||||
ORDER BY
|
||||
created_at,
|
||||
id
|
||||
LIMIT $4
|
||||
`,
|
||||
chatID,
|
||||
cursor.CreatedAt,
|
||||
cursor.MessageID,
|
||||
limit+1,
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return domain.MessagePage{}, fmt.Errorf(
|
||||
"query messages: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
page := domain.MessagePage{
|
||||
Items: make([]domain.Message, 0, limit),
|
||||
}
|
||||
|
||||
for rows.Next() {
|
||||
var message domain.Message
|
||||
|
||||
if err := rows.Scan(
|
||||
&message.ID,
|
||||
&message.ChatID,
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
); err != nil {
|
||||
return domain.MessagePage{}, fmt.Errorf(
|
||||
"scan message page: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
page.Items = append(page.Items, message)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return domain.MessagePage{}, fmt.Errorf(
|
||||
"iterate message page: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
if len(page.Items) > limit {
|
||||
page.Items = page.Items[:limit]
|
||||
|
||||
lastMessage := page.Items[len(page.Items)-1]
|
||||
nextCursor := domain.EncodeCursor(
|
||||
lastMessage.CreatedAt,
|
||||
lastMessage.ID,
|
||||
chatID,
|
||||
)
|
||||
page.NextCursor = &nextCursor
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) CreateSession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
userID string,
|
||||
expiresAt time.Time,
|
||||
) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.pool.Exec(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO sessions (
|
||||
token_hash,
|
||||
user_id,
|
||||
expires_at
|
||||
)
|
||||
VALUES ($1, $2, $3)
|
||||
`,
|
||||
tokenHash,
|
||||
userID,
|
||||
expiresAt,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert session: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetUserBySession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) (domain.User, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var user domain.User
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
app_user.id::text,
|
||||
app_user.username,
|
||||
app_user.display_name,
|
||||
app_user.created_at
|
||||
FROM sessions AS session
|
||||
JOIN users AS app_user
|
||||
ON app_user.id = session.user_id
|
||||
WHERE session.token_hash = $1
|
||||
AND session.expires_at > CURRENT_TIMESTAMP
|
||||
`,
|
||||
tokenHash,
|
||||
).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.User{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf(
|
||||
"select user by session: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) DeleteSession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.pool.Exec(
|
||||
queryContext,
|
||||
`
|
||||
DELETE FROM sessions
|
||||
WHERE token_hash = $1
|
||||
`,
|
||||
tokenHash,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete session: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) CreateUser(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
displayName string,
|
||||
passwordHash string,
|
||||
) (domain.User, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
user := domain.User{
|
||||
ID: uuid.NewString(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
}
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO users (
|
||||
id,
|
||||
username,
|
||||
display_name,
|
||||
password_hash
|
||||
)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING created_at
|
||||
`,
|
||||
user.ID,
|
||||
user.Username,
|
||||
user.DisplayName,
|
||||
passwordHash,
|
||||
).Scan(&user.CreatedAt)
|
||||
|
||||
if err == nil {
|
||||
return user, nil
|
||||
}
|
||||
|
||||
var postgresError *pgconn.PgError
|
||||
if errors.As(err, &postgresError) &&
|
||||
postgresError.Code == "23505" &&
|
||||
postgresError.ConstraintName == "users_username_unique" {
|
||||
return domain.User{}, ErrConflict
|
||||
}
|
||||
|
||||
return domain.User{}, fmt.Errorf("insert user: %w", err)
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetUserByID(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
) (domain.User, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var user domain.User
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
id::text,
|
||||
username,
|
||||
display_name,
|
||||
created_at
|
||||
FROM users
|
||||
WHERE id = $1
|
||||
`,
|
||||
userID,
|
||||
).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.User{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("select user by id: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetUserByUsername(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
) (domain.User, string, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var (
|
||||
user domain.User
|
||||
passwordHash string
|
||||
)
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
id::text,
|
||||
username,
|
||||
display_name,
|
||||
created_at,
|
||||
password_hash
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
`,
|
||||
username,
|
||||
).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
&passwordHash,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.User{}, "", ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.User{}, "", fmt.Errorf(
|
||||
"select user by username: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
return user, passwordHash, nil
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
CreateUser(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
displayName string,
|
||||
passwordHash string,
|
||||
) (domain.User, error)
|
||||
|
||||
GetUserByID(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
) (domain.User, error)
|
||||
|
||||
GetUserByUsername(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
) (domain.User, string, error)
|
||||
|
||||
CreateChat(
|
||||
ctx context.Context,
|
||||
title string,
|
||||
memberIDs []string,
|
||||
) (domain.Chat, error)
|
||||
|
||||
GetChatByID(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
) (domain.Chat, error)
|
||||
|
||||
GetChatsForUser(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
limit int,
|
||||
cursor string,
|
||||
) (domain.ChatPage, error)
|
||||
|
||||
CreateMessage(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
senderID string,
|
||||
text string,
|
||||
) (domain.Message, error)
|
||||
|
||||
GetMessages(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
limit int,
|
||||
cursor string,
|
||||
) (domain.MessagePage, error)
|
||||
|
||||
CreateSession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
userID string,
|
||||
expiresAt time.Time,
|
||||
) error
|
||||
|
||||
GetUserBySession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) (domain.User, error)
|
||||
|
||||
DeleteSession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) error
|
||||
}
|
||||
|
||||
var _ Repository = (*PostgreSQLStore)(nil)
|
||||
@@ -34,10 +34,29 @@ func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.store.CreateChat(req.Title, req.MemberIDs)
|
||||
chat, err := h.store.CreateChat(
|
||||
r.Context(),
|
||||
req.Title,
|
||||
req.MemberIDs,
|
||||
)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
"one or more members do not exist",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
//участник не существует -> 400
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID)
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -55,14 +74,24 @@ func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.store.GetChatByID(chatID, currentUser.ID)
|
||||
chat, err := h.store.GetChatByID(
|
||||
r.Context(),
|
||||
chatID,
|
||||
currentUser.ID,
|
||||
)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
//посторонний или несуществующий чат -> 404
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", reqID)
|
||||
return
|
||||
}
|
||||
response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError, "internal error", reqID)
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -108,6 +137,7 @@ func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
page, err := h.store.GetChatsForUser(
|
||||
r.Context(),
|
||||
currentUser.ID,
|
||||
limit,
|
||||
cursor,
|
||||
@@ -126,9 +156,9 @@ func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusInternalServerError,
|
||||
response.CodeInternalError,
|
||||
"internal error",
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
|
||||
@@ -1,42 +1,77 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/store"
|
||||
)
|
||||
|
||||
type ReadinessChecker interface {
|
||||
Ping(ctx context.Context) error
|
||||
}
|
||||
|
||||
type Option func(*Handler)
|
||||
|
||||
type Handler struct {
|
||||
store *store.MemoryStore
|
||||
store store.Repository
|
||||
readinessChecker ReadinessChecker
|
||||
readinessTimeout time.Duration
|
||||
sessionTTL time.Duration
|
||||
}
|
||||
|
||||
func NewHandler(st *store.MemoryStore) *Handler {
|
||||
return &Handler{store: st}
|
||||
func NewHandler(
|
||||
repository store.Repository,
|
||||
options ...Option,
|
||||
) *Handler {
|
||||
handler := &Handler{
|
||||
store: repository,
|
||||
readinessTimeout: 2 * time.Second,
|
||||
sessionTTL: time.Hour,
|
||||
}
|
||||
|
||||
for _, option := range options {
|
||||
option(handler)
|
||||
}
|
||||
|
||||
return handler
|
||||
}
|
||||
|
||||
// декодирует тело запроса:
|
||||
// Запрещает неизвестные/лишние поля (DisallowUnknownFields) -> 400
|
||||
// Ловит синтаксические ошибки JSON -> 400
|
||||
// Проверяет, что после валидного JSON нет мусора
|
||||
func decodeJSON(r *http.Request, dst any) error {
|
||||
func WithReadiness(
|
||||
checker ReadinessChecker,
|
||||
timeout time.Duration,
|
||||
) Option {
|
||||
return func(handler *Handler) {
|
||||
handler.readinessChecker = checker
|
||||
handler.readinessTimeout = timeout
|
||||
}
|
||||
}
|
||||
|
||||
func WithSessionTTL(ttl time.Duration) Option {
|
||||
return func(handler *Handler) {
|
||||
handler.sessionTTL = ttl
|
||||
}
|
||||
}
|
||||
|
||||
func decodeJSON(r *http.Request, destination any) error {
|
||||
if r.Body == nil {
|
||||
return errors.New("request body is empty")
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
if err := decoder.Decode(destination); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// два JSON подряд или мусор в конце — ошибка
|
||||
var extra json.RawMessage
|
||||
if err := dec.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return errors.New("extra data after JSON")
|
||||
}
|
||||
|
||||
|
||||
@@ -1,20 +1,62 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab2/internal/transport/http/middleware"
|
||||
"mtusi2026lab2/internal/transport/http/response"
|
||||
)
|
||||
|
||||
// HealthLive проверяет, что процесс сервера запущен
|
||||
// HealthLive проверяет только то, что HTTP-процесс работает.
|
||||
func (h *Handler) HealthLive(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := middleware.GetRequestID(r.Context())
|
||||
response.WriteJSON(w, http.StatusOK, map[string]string{"status": "ok"}, reqID)
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusOK,
|
||||
map[string]string{"status": "ok"},
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
|
||||
// HealthReady проверяет, что сервер готов принимать входящие запросы
|
||||
// HealthReady проверяет зависимости, без которых API не может обслуживать трафик.
|
||||
func (h *Handler) HealthReady(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := middleware.GetRequestID(r.Context())
|
||||
response.WriteJSON(w, http.StatusOK, map[string]string{"status": "ok"}, reqID)
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
// Этот вариант сохраняет работоспособность изолированных unit-тестов,
|
||||
// в которых PostgreSQL намеренно не создаётся.
|
||||
if h.readinessChecker == nil {
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusOK,
|
||||
map[string]string{"status": "ok"},
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(
|
||||
r.Context(),
|
||||
h.readinessTimeout,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
if err := h.readinessChecker.Ping(ctx); err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is not ready",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusOK,
|
||||
map[string]string{"status": "ok"},
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -41,14 +41,25 @@ func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
//автор сообщения строго выводится из сессии (currentUser.ID)
|
||||
msg, err := h.store.CreateMessage(chatID, currentUser.ID, req.Text)
|
||||
msg, err := h.store.CreateMessage(
|
||||
r.Context(),
|
||||
chatID,
|
||||
currentUser.ID,
|
||||
req.Text,
|
||||
)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
// чата нет/пользователь не участник -> 404
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", reqID)
|
||||
return
|
||||
}
|
||||
response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError, "internal error", reqID)
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -66,28 +77,76 @@ func (h *Handler) GetMessages(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
query := r.URL.Query()
|
||||
|
||||
limit := 50
|
||||
limitStr := r.URL.Query().Get("limit")
|
||||
if limitStr != "" {
|
||||
val, err := strconv.Atoi(limitStr)
|
||||
// Если передан limit=0 или >100 -> 400 invalid_request
|
||||
if err != nil || val < 1 || val > 100 {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "limit must be an integer between 1 and 100", reqID)
|
||||
if query.Has("limit") {
|
||||
limitString := query.Get("limit")
|
||||
|
||||
parsedLimit, err := strconv.Atoi(limitString)
|
||||
if err != nil || parsedLimit < 1 || parsedLimit > 100 {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
"limit must be an integer between 1 and 100",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
limit = val
|
||||
|
||||
limit = parsedLimit
|
||||
}
|
||||
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
cursor := query.Get("cursor")
|
||||
if query.Has("cursor") && cursor == "" {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
"cursor must not be empty",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
page, err := h.store.GetMessages(
|
||||
r.Context(),
|
||||
chatID,
|
||||
currentUser.ID,
|
||||
limit,
|
||||
cursor,
|
||||
)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusNotFound,
|
||||
response.CodeNotFound,
|
||||
"chat not found",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if errors.Is(err, store.ErrInvalidCursor) {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
"invalid cursor",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
page, err := h.store.GetMessages(chatID, currentUser.ID, limit, cursor)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", reqID)
|
||||
return
|
||||
}
|
||||
//если курсор кривой или от другого чата -> 400 invalid_request
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID)
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
reqID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
"mtusi2026lab2/internal/security"
|
||||
"mtusi2026lab2/internal/store"
|
||||
"mtusi2026lab2/internal/transport/http/middleware"
|
||||
"mtusi2026lab2/internal/transport/http/response"
|
||||
)
|
||||
|
||||
const basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
|
||||
// dummyPasswordHash keeps the expensive Argon2id path for an unknown username.
|
||||
// The all-zero digest is intentionally not a real user's credential; only the
|
||||
// encoded parameters and lengths need to be valid for constant-cost checking.
|
||||
const dummyPasswordHash = "$argon2id$v=19$m=19456,t=2,p=1$" +
|
||||
"AAAAAAAAAAAAAAAAAAAAAA$" +
|
||||
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
|
||||
|
||||
func (h *Handler) CreateSession(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || username == "" {
|
||||
writeBasicUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
user, passwordHash, err := h.store.GetUserByUsername(
|
||||
r.Context(),
|
||||
username,
|
||||
)
|
||||
userNotFound := errors.Is(err, store.ErrNotFound)
|
||||
if userNotFound {
|
||||
passwordHash = dummyPasswordHash
|
||||
}
|
||||
if err != nil {
|
||||
if !userNotFound {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
passwordMatches, err := security.VerifyPassword(
|
||||
password,
|
||||
passwordHash,
|
||||
)
|
||||
if err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusInternalServerError,
|
||||
response.CodeInternalError,
|
||||
"stored password hash is invalid",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
if userNotFound || !passwordMatches {
|
||||
writeBasicUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
token, tokenHash, err := security.GenerateSessionToken()
|
||||
if err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusInternalServerError,
|
||||
response.CodeInternalError,
|
||||
"failed to create session",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
expiresAt := time.Now().UTC().Add(h.sessionTTL)
|
||||
|
||||
if err := h.store.CreateSession(
|
||||
r.Context(),
|
||||
tokenHash,
|
||||
user.ID,
|
||||
expiresAt,
|
||||
); err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
session := domain.Session{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: expiresAt,
|
||||
User: user,
|
||||
}
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusCreated,
|
||||
session,
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
|
||||
func (h *Handler) DeleteCurrentSession(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
tokenHash := middleware.GetCurrentSessionTokenHash(r.Context())
|
||||
|
||||
if err := h.store.DeleteSession(
|
||||
r.Context(),
|
||||
tokenHash,
|
||||
); err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusNoContent,
|
||||
nil,
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
|
||||
func writeBasicUnauthorized(
|
||||
w http.ResponseWriter,
|
||||
requestID string,
|
||||
) {
|
||||
w.Header().Set("WWW-Authenticate", basicChallenge)
|
||||
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusUnauthorized,
|
||||
response.CodeUnauthorized,
|
||||
"invalid username or password",
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
"mtusi2026lab2/internal/security"
|
||||
"mtusi2026lab2/internal/store"
|
||||
"mtusi2026lab2/internal/transport/http/middleware"
|
||||
"mtusi2026lab2/internal/transport/http/response"
|
||||
@@ -13,47 +14,106 @@ import (
|
||||
type CreateUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
// CreateUser создает нового пользователя
|
||||
func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := middleware.GetRequestID(r.Context())
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
var req CreateUserRequest
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "malformed or invalid JSON: "+err.Error(), reqID)
|
||||
var request CreateUserRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
"malformed or invalid JSON: "+err.Error(),
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
userCandidate := domain.User{
|
||||
Username: req.Username,
|
||||
DisplayName: req.DisplayName,
|
||||
Username: request.Username,
|
||||
DisplayName: request.DisplayName,
|
||||
}
|
||||
|
||||
//правила Unicode, длину и пробелы из domain
|
||||
if err := userCandidate.Validate(); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID)
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
err.Error(),
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
createdUser, err := h.store.CreateUser(userCandidate.Username, userCandidate.DisplayName)
|
||||
if err := security.ValidatePassword(request.Password); err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
err.Error(),
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
passwordHash, err := security.HashPassword(request.Password)
|
||||
if err != nil {
|
||||
// юзернейм занят — 409
|
||||
if errors.Is(err, store.ErrConflict) {
|
||||
response.WriteError(w, http.StatusConflict, response.CodeConflict, "username already exists", reqID)
|
||||
return
|
||||
}
|
||||
response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError, "failed to create user", reqID)
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusInternalServerError,
|
||||
response.CodeInternalError,
|
||||
"failed to process password",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(w, http.StatusCreated, createdUser, reqID)
|
||||
createdUser, err := h.store.CreateUser(
|
||||
r.Context(),
|
||||
request.Username,
|
||||
request.DisplayName,
|
||||
passwordHash,
|
||||
)
|
||||
if errors.Is(err, store.ErrConflict) {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusConflict,
|
||||
response.CodeConflict,
|
||||
"username already exists",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusCreated,
|
||||
createdUser,
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
|
||||
// GetMe возвращает профиль текущего пользователя
|
||||
func (h *Handler) GetMe(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := middleware.GetRequestID(r.Context())
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
response.WriteJSON(w, http.StatusOK, currentUser, reqID)
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusOK,
|
||||
currentUser,
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,42 +2,116 @@ package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab2/internal/domain"
|
||||
"mtusi2026lab2/internal/security"
|
||||
"mtusi2026lab2/internal/store"
|
||||
"mtusi2026lab2/internal/transport/http/response"
|
||||
)
|
||||
|
||||
const UserContextKey contextKey = "current_user"
|
||||
const bearerChallenge = `Bearer realm="messenger"`
|
||||
|
||||
// RequireAuth проверяет наличие и валидность X-User-Id
|
||||
func RequireAuth(st *store.MemoryStore, next http.HandlerFunc) http.HandlerFunc {
|
||||
const (
|
||||
UserContextKey contextKey = "current_user"
|
||||
sessionTokenHashKey contextKey = "session_token_hash"
|
||||
)
|
||||
|
||||
type SessionAuthenticator interface {
|
||||
GetUserBySession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) (domain.User, error)
|
||||
}
|
||||
|
||||
func RequireAuth(
|
||||
authenticator SessionAuthenticator,
|
||||
next http.HandlerFunc,
|
||||
) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := GetRequestID(r.Context())
|
||||
userID := r.Header.Get("X-User-Id")
|
||||
requestID := GetRequestID(r.Context())
|
||||
|
||||
if userID == "" {
|
||||
response.WriteError(w, http.StatusUnauthorized, response.CodeUnauthorized, "missing X-User-Id header", reqID)
|
||||
token, ok := bearerToken(r.Header.Get("Authorization"))
|
||||
if !ok {
|
||||
writeBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
//существует ли чел
|
||||
user, err := st.GetUserByID(userID)
|
||||
tokenHash := security.HashSessionToken(token)
|
||||
|
||||
user, err := authenticator.GetUserBySession(
|
||||
r.Context(),
|
||||
tokenHash,
|
||||
)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusUnauthorized, response.CodeUnauthorized, "user not found", reqID)
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), UserContextKey, user)
|
||||
ctx := context.WithValue(
|
||||
r.Context(),
|
||||
UserContextKey,
|
||||
user,
|
||||
)
|
||||
ctx = context.WithValue(
|
||||
ctx,
|
||||
sessionTokenHashKey,
|
||||
tokenHash,
|
||||
)
|
||||
|
||||
next(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
// чисто чтоб зареганного получить из контекста
|
||||
func GetCurrentUser(ctx context.Context) domain.User {
|
||||
if val, ok := ctx.Value(UserContextKey).(domain.User); ok {
|
||||
return val
|
||||
user, _ := ctx.Value(UserContextKey).(domain.User)
|
||||
return user
|
||||
}
|
||||
|
||||
func GetCurrentSessionTokenHash(ctx context.Context) []byte {
|
||||
tokenHash, _ := ctx.Value(sessionTokenHashKey).([]byte)
|
||||
|
||||
result := make([]byte, len(tokenHash))
|
||||
copy(result, tokenHash)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func bearerToken(authorization string) (string, bool) {
|
||||
parts := strings.Fields(authorization)
|
||||
|
||||
if len(parts) != 2 ||
|
||||
!strings.EqualFold(parts[0], "Bearer") ||
|
||||
parts[1] == "" {
|
||||
return "", false
|
||||
}
|
||||
return domain.User{}
|
||||
|
||||
return parts[1], true
|
||||
}
|
||||
|
||||
func writeBearerUnauthorized(
|
||||
w http.ResponseWriter,
|
||||
requestID string,
|
||||
) {
|
||||
w.Header().Set("WWW-Authenticate", bearerChallenge)
|
||||
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusUnauthorized,
|
||||
response.CodeUnauthorized,
|
||||
"invalid or expired bearer token",
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ const (
|
||||
CodeUnauthorized = "unauthorized"
|
||||
CodeNotFound = "not_found"
|
||||
CodeConflict = "conflict"
|
||||
CodeUnavailable = "unavailable"
|
||||
CodeInternalError = "internal_error"
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user