chore(solution): port lab3 sources

This commit is contained in:
2026-11-20 03:05:34 +03:00
parent ec540a1a72
commit 083d0d80cc
44 changed files with 2745 additions and 1 deletions
+74
View File
@@ -0,0 +1,74 @@
package service
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"time"
"messenger/internal/domain"
)
const tokenBytes = 32
type AuthService struct {
users UserRepository
sessions SessionStore
ttl time.Duration
}
func NewAuthService(users UserRepository, sessions SessionStore, ttl time.Duration) *AuthService {
return &AuthService{users: users, sessions: sessions, ttl: ttl}
}
func (s *AuthService) Login(ctx context.Context, username, password string) (domain.Session, error) {
user, hash, err := s.users.GetUserByUsername(ctx, username)
if errors.Is(err, domain.ErrNotFound) {
return domain.Session{}, domain.ErrUnauthorized
}
if err != nil {
return domain.Session{}, err
}
ok, err := verifyPassword(password, hash)
if err != nil {
return domain.Session{}, err
}
if !ok {
return domain.Session{}, domain.ErrUnauthorized
}
raw := make([]byte, tokenBytes)
if _, err := rand.Read(raw); err != nil {
return domain.Session{}, err
}
token := base64.RawURLEncoding.EncodeToString(raw)
expiresAt := now().Add(s.ttl)
if err := s.sessions.Create(ctx, HashToken(token), user.ID, expiresAt); err != nil {
return domain.Session{}, err
}
return domain.Session{Token: token, ExpiresAt: expiresAt, User: user}, nil
}
func (s *AuthService) Authenticate(ctx context.Context, token string) (domain.User, error) {
userID, err := s.sessions.Get(ctx, HashToken(token))
if err != nil {
return domain.User{}, err
}
u, err := s.users.GetUser(ctx, userID)
if errors.Is(err, domain.ErrNotFound) {
return domain.User{}, domain.ErrUnauthorized
}
return u, err
}
func (s *AuthService) Logout(ctx context.Context, token string) error {
return s.sessions.Delete(ctx, HashToken(token))
}
func HashToken(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
+81
View File
@@ -0,0 +1,81 @@
package service
import (
"context"
"errors"
"fmt"
"uuid"
"messenger/internal/domain"
)
type ChatService struct {
repo ChatRepository
}
func NewChatService(repo ChatRepository) *ChatService {
return &ChatService{repo: repo}
}
func (s *ChatService) Create(ctx context.Context, actor domain.User, title string, memberIDs []uuid.UUID) (domain.Chat, error) {
if err := checkText("title", title, 100); err != nil {
return domain.Chat{}, err
}
if len(memberIDs) < 1 || len(memberIDs) > 100 {
return domain.Chat{}, fmt.Errorf("%w: member_ids must contain 1 to 100 users", domain.ErrInvalidInput)
}
seen := make(map[uuid.UUID]struct{}, len(memberIDs))
for _, id := range memberIDs {
if _, dup := seen[id]; dup {
return domain.Chat{}, fmt.Errorf("%w: member_ids must not contain duplicates", domain.ErrInvalidInput)
}
seen[id] = struct{}{}
}
if _, ok := seen[actor.ID]; !ok {
return domain.Chat{}, fmt.Errorf("%w: member_ids must include the current user", domain.ErrInvalidInput)
}
c := domain.Chat{
ID: uuid.New(),
Title: title,
MemberIDs: memberIDs,
CreatedAt: now(),
}
if err := s.repo.CreateChat(ctx, c); err != nil {
if errors.Is(err, domain.ErrNotFound) {
return domain.Chat{}, fmt.Errorf("%w: member_ids contains unknown user", domain.ErrInvalidInput)
}
return domain.Chat{}, err
}
return c, nil
}
func (s *ChatService) Get(ctx context.Context, actor domain.User, chatID uuid.UUID) (domain.Chat, error) {
c, err := s.repo.GetChat(ctx, chatID)
if err != nil {
return domain.Chat{}, err
}
if !c.HasMember(actor.ID) {
return domain.Chat{}, domain.ErrNotFound
}
return c, nil
}
func (s *ChatService) List(ctx context.Context, actor domain.User, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
if err := checkLimit(limit); err != nil {
return domain.Page[domain.Chat]{}, err
}
if after != nil && after.Scope != actor.ID {
return domain.Page[domain.Chat]{}, fmt.Errorf("%w: cursor does not belong to this request", domain.ErrInvalidInput)
}
items, more, err := s.repo.ListUserChats(ctx, actor.ID, after, limit)
if err != nil {
return domain.Page[domain.Chat]{}, err
}
page := domain.Page[domain.Chat]{Items: items}
if more {
last := items[len(items)-1]
page.Next = &domain.Cursor{Scope: actor.ID, CreatedAt: last.CreatedAt, ID: last.ID}
}
return page, nil
}
+65
View File
@@ -0,0 +1,65 @@
package service
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"uuid"
"messenger/internal/domain"
)
type MessageService struct {
chats *ChatService
messages MessageRepository
}
func NewMessageService(chats *ChatService, messages MessageRepository) *MessageService {
return &MessageService{chats: chats, messages: messages}
}
func (s *MessageService) Send(ctx context.Context, actor domain.User, chatID uuid.UUID, key, text string) (domain.Message, error) {
if _, err := s.chats.Get(ctx, actor, chatID); err != nil {
return domain.Message{}, err
}
if err := checkText("text", text, 4000); err != nil {
return domain.Message{}, err
}
m := domain.Message{
ID: uuid.New(),
ChatID: chatID,
SenderID: actor.ID,
Text: text,
CreatedAt: now(),
}
sum := sha256.Sum256([]byte(text))
stored, err := s.messages.CreateMessageIdempotent(ctx, m, key, hex.EncodeToString(sum[:]))
if errors.Is(err, domain.ErrConflict) {
return domain.Message{}, fmt.Errorf("%w: Idempotency-Key was already used with a different body", domain.ErrConflict)
}
return stored, err
}
func (s *MessageService) History(ctx context.Context, actor domain.User, chatID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Message], error) {
if _, err := s.chats.Get(ctx, actor, chatID); err != nil {
return domain.Page[domain.Message]{}, err
}
if err := checkLimit(limit); err != nil {
return domain.Page[domain.Message]{}, err
}
if after != nil && after.Scope != chatID {
return domain.Page[domain.Message]{}, fmt.Errorf("%w: cursor belongs to another chat", domain.ErrInvalidInput)
}
items, more, err := s.messages.ListMessages(ctx, chatID, after, limit)
if err != nil {
return domain.Page[domain.Message]{}, err
}
page := domain.Page[domain.Message]{Items: items}
if more {
last := items[len(items)-1]
page.Next = &domain.Cursor{Scope: chatID, CreatedAt: last.CreatedAt, ID: last.ID}
}
return page, nil
}
+60
View File
@@ -0,0 +1,60 @@
package service
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
const (
argonMemory = 19 * 1024
argonTime = 2
argonThreads = 1
argonSaltLen = 16
argonKeyLen = 32
)
var errBadHash = errors.New("malformed password hash")
func hashPassword(password string) (string, error) {
salt := make([]byte, argonSaltLen)
if _, err := rand.Read(salt); err != nil {
return "", err
}
key := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
b64 := base64.RawStdEncoding
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version, argonMemory, argonTime, argonThreads, b64.EncodeToString(salt), b64.EncodeToString(key)), nil
}
func verifyPassword(password, encoded string) (bool, error) {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[1] != "argon2id" {
return false, errBadHash
}
var version int
var memory, time uint32
var threads uint8
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
return false, errBadHash
}
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &time, &threads); err != nil {
return false, errBadHash
}
b64 := base64.RawStdEncoding
salt, err := b64.DecodeString(parts[4])
if err != nil {
return false, errBadHash
}
want, err := b64.DecodeString(parts[5])
if err != nil {
return false, errBadHash
}
got := argon2.IDKey([]byte(password), salt, time, memory, threads, uint32(len(want)))
return subtle.ConstantTimeCompare(got, want) == 1, nil
}
+36
View File
@@ -0,0 +1,36 @@
package service
import (
"context"
"time"
"uuid"
"messenger/internal/domain"
)
type UserRepository interface {
CreateUser(ctx context.Context, u domain.User, passwordHash string) error
GetUser(ctx context.Context, id uuid.UUID) (domain.User, error)
GetUserByUsername(ctx context.Context, username string) (domain.User, string, error)
}
type ChatRepository interface {
CreateChat(ctx context.Context, c domain.Chat) error
GetChat(ctx context.Context, id uuid.UUID) (domain.Chat, error)
ListUserChats(ctx context.Context, userID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Chat, bool, error)
}
type MessageRepository interface {
CreateMessageIdempotent(ctx context.Context, m domain.Message, key, requestHash string) (domain.Message, error)
ListMessages(ctx context.Context, chatID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Message, bool, error)
}
type SessionStore interface {
Create(ctx context.Context, tokenHash string, userID uuid.UUID, expiresAt time.Time) error
Get(ctx context.Context, tokenHash string) (uuid.UUID, error)
Delete(ctx context.Context, tokenHash string) error
}
func now() time.Time {
return time.Now().UTC().Truncate(time.Microsecond)
}
+59
View File
@@ -0,0 +1,59 @@
package service
import (
"context"
"errors"
"fmt"
"regexp"
"unicode/utf8"
"uuid"
"messenger/internal/domain"
)
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
const (
minPasswordLen = 12
maxPasswordLen = 128
)
type UserService struct {
repo UserRepository
}
func NewUserService(repo UserRepository) *UserService {
return &UserService{repo: repo}
}
func (s *UserService) Register(ctx context.Context, username, displayName, password string) (domain.User, error) {
if !usernameRe.MatchString(username) {
return domain.User{}, fmt.Errorf("%w: username must match [a-z0-9_]{3,32}", domain.ErrInvalidInput)
}
if err := checkText("display_name", displayName, 100); err != nil {
return domain.User{}, err
}
if err := checkText("password", password, maxPasswordLen); err != nil {
return domain.User{}, err
}
if utf8.RuneCountInString(password) < minPasswordLen {
return domain.User{}, fmt.Errorf("%w: password must be at least %d characters", domain.ErrInvalidInput, minPasswordLen)
}
hash, err := hashPassword(password)
if err != nil {
return domain.User{}, err
}
u := domain.User{
ID: uuid.New(),
Username: username,
DisplayName: displayName,
CreatedAt: now(),
}
if err := s.repo.CreateUser(ctx, u, hash); err != nil {
if errors.Is(err, domain.ErrConflict) {
return domain.User{}, fmt.Errorf("%w: username is already taken", domain.ErrConflict)
}
return domain.User{}, err
}
return u, nil
}
+31
View File
@@ -0,0 +1,31 @@
package service
import (
"fmt"
"strings"
"unicode/utf8"
"messenger/internal/domain"
)
const (
DefaultLimit = 50
MaxLimit = 100
)
func checkText(field, value string, maxRunes int) error {
if strings.TrimSpace(value) == "" {
return fmt.Errorf("%w: %s must not be empty", domain.ErrInvalidInput, field)
}
if n := utf8.RuneCountInString(value); n > maxRunes {
return fmt.Errorf("%w: %s must be at most %d characters", domain.ErrInvalidInput, field, maxRunes)
}
return nil
}
func checkLimit(limit int) error {
if limit < 1 || limit > MaxLimit {
return fmt.Errorf("%w: limit must be between 1 and %d", domain.ErrInvalidInput, MaxLimit)
}
return nil
}