lab 3 done
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUsernameTaken = errors.New("username is already taken")
|
||||
ErrUserNotFound = errors.New("user not found")
|
||||
ErrChatNotFound = errors.New("chat not found")
|
||||
ErrNotMember = errors.New("user is not a chat member")
|
||||
)
|
||||
|
||||
// Repository is the persistence port required by the chat use case.
|
||||
type Repository interface {
|
||||
Ready(ctx context.Context) error
|
||||
UserByUsername(ctx context.Context, username string) (domain.User, string, bool, error)
|
||||
CreateUser(ctx context.Context, username, displayName, passwordHash string) (domain.User, error)
|
||||
User(ctx context.Context, id string) (domain.User, bool, error)
|
||||
CreateChat(ctx context.Context, title string, memberIDs []string) (domain.Chat, error)
|
||||
ChatForUser(ctx context.Context, chatID, userID string) (domain.Chat, error)
|
||||
ListChats(ctx context.Context, userID string, after *domain.Position, limit int) ([]domain.Chat, error)
|
||||
CreateMessage(ctx context.Context, chatID, senderID, text, key string) (domain.Message, error)
|
||||
ListMessages(ctx context.Context, chatID string, after *domain.Position, limit int) ([]domain.Message, error)
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password"
|
||||
)
|
||||
|
||||
type UseCase struct {
|
||||
repository Repository
|
||||
sessions Sessions
|
||||
sessionTTL time.Duration
|
||||
}
|
||||
|
||||
func New(repository Repository, sessions Sessions, ttl time.Duration) *UseCase {
|
||||
return &UseCase{repository: repository, sessions: sessions, sessionTTL: ttl}
|
||||
}
|
||||
|
||||
func (u *UseCase) CreateUser(ctx context.Context, user domain.User, secret string) (domain.User, error) {
|
||||
if !validUsername(user.Username) {
|
||||
return domain.User{}, invalid("username должен соответствовать [a-z0-9_]{3,32}")
|
||||
}
|
||||
if !validRequiredText(user.DisplayName, 100) {
|
||||
return domain.User{}, invalid("display_name должен содержать от 1 до 100 символов")
|
||||
}
|
||||
if !validPassword(secret) {
|
||||
return domain.User{}, invalid("password должен содержать от 12 до 128 символов")
|
||||
}
|
||||
hash, err := password.Hash(ctx, secret)
|
||||
if err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
created, err := u.repository.CreateUser(ctx, user.Username, user.DisplayName, hash)
|
||||
if errors.Is(err, ErrUsernameTaken) {
|
||||
return domain.User{}, domain.NewApplicationError(domain.ErrorConflict, "Пользователь с таким username уже существует")
|
||||
}
|
||||
return created, err
|
||||
}
|
||||
|
||||
func (u *UseCase) CreateChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error) {
|
||||
if !validRequiredText(chat.Title, 100) {
|
||||
return domain.Chat{}, invalid("title должен содержать от 1 до 100 символов")
|
||||
}
|
||||
if len(chat.MemberIDs) < 1 || len(chat.MemberIDs) > 100 {
|
||||
return domain.Chat{}, invalid("member_ids должен содержать от 1 до 100 участников")
|
||||
}
|
||||
|
||||
normalizedIDs := make([]string, len(chat.MemberIDs))
|
||||
seen := make(map[string]struct{}, len(chat.MemberIDs))
|
||||
callerIncluded := false
|
||||
for index, memberID := range chat.MemberIDs {
|
||||
normalized, valid := normalizeUUID(memberID)
|
||||
if !valid {
|
||||
return domain.Chat{}, invalid("member_ids содержит некорректный UUID")
|
||||
}
|
||||
if _, duplicate := seen[normalized]; duplicate {
|
||||
return domain.Chat{}, invalid("member_ids содержит повторяющиеся UUID")
|
||||
}
|
||||
normalizedIDs[index] = normalized
|
||||
seen[normalized] = struct{}{}
|
||||
callerIncluded = callerIncluded || normalized == callerID
|
||||
}
|
||||
if !callerIncluded {
|
||||
return domain.Chat{}, invalid("текущий пользователь должен входить в member_ids")
|
||||
}
|
||||
|
||||
created, err := u.repository.CreateChat(ctx, chat.Title, normalizedIDs)
|
||||
if errors.Is(err, ErrUserNotFound) {
|
||||
return domain.Chat{}, invalid("member_ids содержит неизвестного пользователя")
|
||||
}
|
||||
return created, err
|
||||
}
|
||||
|
||||
func (u *UseCase) GetChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error) {
|
||||
chatID, valid := normalizeUUID(chat.ID)
|
||||
if !valid {
|
||||
return domain.Chat{}, invalid("Некорректный chat_id")
|
||||
}
|
||||
return u.chatForUser(ctx, chatID, callerID)
|
||||
}
|
||||
|
||||
func (u *UseCase) ListChats(ctx context.Context, callerID string, pagination domain.Pagination) (domain.ChatPage, error) {
|
||||
if pagination.Limit < 1 || pagination.Limit > 100 {
|
||||
return domain.ChatPage{}, invalid("limit должен быть целым числом от 1 до 100")
|
||||
}
|
||||
items, err := u.repository.ListChats(ctx, callerID, pagination.After, pagination.Limit+1)
|
||||
if err != nil {
|
||||
return domain.ChatPage{}, err
|
||||
}
|
||||
page := domain.ChatPage{Items: items, HasMore: len(items) > pagination.Limit}
|
||||
if page.HasMore {
|
||||
page.Items = page.Items[:pagination.Limit]
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (u *UseCase) CreateMessage(ctx context.Context, callerID string, message domain.Message) (domain.Message, error) {
|
||||
chatID, valid := normalizeUUID(message.ChatID)
|
||||
if !valid {
|
||||
return domain.Message{}, invalid("Некорректный chat_id")
|
||||
}
|
||||
if _, err := u.chatForUser(ctx, chatID, callerID); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
if !validRequiredText(message.Text, 4000) {
|
||||
return domain.Message{}, invalid("text должен содержать от 1 до 4000 символов")
|
||||
}
|
||||
created, err := u.repository.CreateMessage(ctx, chatID, callerID, message.Text, message.IdempotencyKey)
|
||||
if errors.Is(err, ErrChatNotFound) || errors.Is(err, ErrNotMember) {
|
||||
return domain.Message{}, notFound()
|
||||
}
|
||||
return created, err
|
||||
}
|
||||
|
||||
func (u *UseCase) ListMessages(ctx context.Context, callerID string, chat domain.Chat, pagination domain.Pagination) (domain.MessagePage, error) {
|
||||
chatID, valid := normalizeUUID(chat.ID)
|
||||
if !valid {
|
||||
return domain.MessagePage{}, invalid("Некорректный chat_id")
|
||||
}
|
||||
if _, err := u.chatForUser(ctx, chatID, callerID); err != nil {
|
||||
return domain.MessagePage{}, err
|
||||
}
|
||||
if pagination.Limit < 1 || pagination.Limit > 100 {
|
||||
return domain.MessagePage{}, invalid("limit должен быть целым числом от 1 до 100")
|
||||
}
|
||||
items, err := u.repository.ListMessages(ctx, chatID, pagination.After, pagination.Limit+1)
|
||||
if err != nil {
|
||||
return domain.MessagePage{}, err
|
||||
}
|
||||
page := domain.MessagePage{Items: items, HasMore: len(items) > pagination.Limit}
|
||||
if page.HasMore {
|
||||
page.Items = page.Items[:pagination.Limit]
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (u *UseCase) chatForUser(ctx context.Context, chatID, callerID string) (domain.Chat, error) {
|
||||
chat, err := u.repository.ChatForUser(ctx, chatID, callerID)
|
||||
if errors.Is(err, ErrChatNotFound) || errors.Is(err, ErrNotMember) {
|
||||
return domain.Chat{}, notFound()
|
||||
}
|
||||
return chat, err
|
||||
}
|
||||
|
||||
func invalid(message string) error {
|
||||
return domain.NewApplicationError(domain.ErrorInvalid, message)
|
||||
}
|
||||
|
||||
func unauthorized() error {
|
||||
return domain.NewApplicationError(domain.ErrorUnauthorized, "Требуется действительная сессия")
|
||||
}
|
||||
|
||||
func notFound() error {
|
||||
return domain.NewApplicationError(domain.ErrorNotFound, "Объект не найден")
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password"
|
||||
)
|
||||
|
||||
type Sessions interface {
|
||||
Put(context.Context, string, domain.Session) error
|
||||
Get(context.Context, string) (domain.Session, bool, error)
|
||||
Delete(context.Context, string) (bool, error)
|
||||
Ready(context.Context) error
|
||||
}
|
||||
|
||||
func validPassword(value string) bool {
|
||||
n := utf8.RuneCountInString(value)
|
||||
return utf8.ValidString(value) && n >= 12 && n <= 128 && strings.TrimSpace(value) != ""
|
||||
}
|
||||
|
||||
func tokenKey(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (u *UseCase) Authenticate(ctx context.Context, token string) (domain.User, error) {
|
||||
decoded, err := base64.RawURLEncoding.DecodeString(token)
|
||||
if err != nil || len(decoded) != 32 {
|
||||
return domain.User{}, unauthorized()
|
||||
}
|
||||
session, exists, err := u.sessions.Get(ctx, tokenKey(token))
|
||||
if err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
if !exists || !time.Now().Before(session.ExpiresAt) {
|
||||
return domain.User{}, unauthorized()
|
||||
}
|
||||
user, exists, err := u.repository.User(ctx, session.UserID)
|
||||
if err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
if !exists {
|
||||
return domain.User{}, unauthorized()
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (u *UseCase) CreateSession(ctx context.Context, username, secret string) (domain.Login, error) {
|
||||
if !validUsername(username) || !validPassword(secret) {
|
||||
return domain.Login{}, unauthorized()
|
||||
}
|
||||
user, hash, exists, err := u.repository.UserByUsername(ctx, username)
|
||||
if err != nil {
|
||||
return domain.Login{}, err
|
||||
}
|
||||
if !exists {
|
||||
hash = password.DummyHash
|
||||
}
|
||||
valid, err := password.Verify(ctx, secret, hash)
|
||||
if err != nil {
|
||||
return domain.Login{}, err
|
||||
}
|
||||
if !valid || !exists {
|
||||
return domain.Login{}, unauthorized()
|
||||
}
|
||||
var raw [32]byte
|
||||
if _, err = rand.Read(raw[:]); err != nil {
|
||||
return domain.Login{}, err
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(raw[:])
|
||||
expires := time.Now().UTC().Add(u.sessionTTL)
|
||||
if err = u.sessions.Put(ctx, tokenKey(token), domain.Session{UserID: user.ID, ExpiresAt: expires}); err != nil {
|
||||
return domain.Login{}, err
|
||||
}
|
||||
return domain.Login{Token: token, ExpiresAt: expires, User: user}, nil
|
||||
}
|
||||
|
||||
func (u *UseCase) DeleteSession(ctx context.Context, token string) error {
|
||||
deleted, err := u.sessions.Delete(ctx, tokenKey(token))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !deleted {
|
||||
return unauthorized()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *UseCase) Ready(ctx context.Context) error {
|
||||
if err := u.repository.Ready(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return u.sessions.Ready(ctx)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPasswordContract(t *testing.T) {
|
||||
for _, value := range []string{"", "too-short", strings.Repeat(" ", 12), strings.Repeat("x", 129), strings.Repeat("x", 12) + string([]byte{0xff})} {
|
||||
if validPassword(value) {
|
||||
t.Fatal("invalid password accepted")
|
||||
}
|
||||
}
|
||||
for _, value := range []string{strings.Repeat("🔑", 128), "valid:password", " password with spaces "} {
|
||||
if !validPassword(value) {
|
||||
t.Fatal("valid Unicode password rejected")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func normalizeUUID(value string) (string, bool) {
|
||||
parsed, err := uuid.Parse(value)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
normalized := parsed.String()
|
||||
if !strings.EqualFold(value, normalized) {
|
||||
return "", false
|
||||
}
|
||||
return normalized, true
|
||||
}
|
||||
|
||||
func validUsername(value string) bool {
|
||||
if len(value) < 3 || len(value) > 32 {
|
||||
return false
|
||||
}
|
||||
for _, char := range value {
|
||||
if char != '_' && (char < 'a' || char > 'z') && (char < '0' || char > '9') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func validRequiredText(value string, maxRunes int) bool {
|
||||
length := utf8.RuneCountInString(value)
|
||||
return utf8.ValidString(value) && length >= 1 && length <= maxRunes && strings.TrimSpace(value) != ""
|
||||
}
|
||||
Reference in New Issue
Block a user