import lab3 files

This commit is contained in:
Голиков Maximillian Антон
2026-10-18 21:14:01 +03:00
parent ec540a1a72
commit 76322040e5
64 changed files with 4446 additions and 0 deletions
+95
View File
@@ -0,0 +1,95 @@
package service
import (
"context"
"errors"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"high-loud-apps-labs/internal/domain"
)
type ChatService struct {
chats domain.ChatRepository
users domain.UserRepository
}
func NewChatService(chats domain.ChatRepository, users domain.UserRepository) *ChatService {
return &ChatService{chats: chats, users: users}
}
func (s *ChatService) Create(ctx context.Context, creatorID, title string, memberIDs []string) (*domain.Chat, error) {
if strings.TrimSpace(title) == "" {
return nil, &domain.ValidationError{
Field: "title",
Message: "не может состоять только из пробелов",
}
}
if utf8.RuneCountInString(title) > 100 {
return nil, &domain.ValidationError{
Field: "title",
Message: "не более 100 символов",
}
}
seen := make(map[string]struct{}, len(memberIDs))
for _, id := range memberIDs {
if _, dup := seen[id]; dup {
return nil, &domain.ValidationError{
Field: "member_ids",
Message: "дубликаты запрещены",
}
}
seen[id] = struct{}{}
}
if _, ok := seen[creatorID]; !ok {
return nil, &domain.ValidationError{
Field: "member_ids",
Message: "создатель должен входить в список участников",
}
}
for _, id := range memberIDs {
if _, err := s.users.GetByID(ctx, id); err != nil {
if errors.Is(err, domain.ErrNotFound) {
return nil, &domain.ValidationError{
Field: "member_ids",
Message: "неизвестный участник " + id,
}
}
return nil, err
}
}
c := &domain.Chat{
ID: uuid.NewString(),
Title: title,
MemberIDs: append([]string(nil), memberIDs...),
CreatedAt: time.Now().UTC(),
}
if err := s.chats.Create(ctx, c); err != nil {
return nil, err
}
return c, nil
}
func (s *ChatService) Get(ctx context.Context, userID, chatID string) (*domain.Chat, error) {
c, err := s.chats.GetByID(ctx, chatID)
if err != nil {
return nil, err
}
for _, m := range c.MemberIDs {
if m == userID {
return c, nil
}
}
return nil, &domain.NotFoundError{Entity: "chat", ID: chatID}
}
func (s *ChatService) List(ctx context.Context, userID string, limit int, cursor *string) ([]domain.Chat, *string, error) {
return s.chats.ListByMember(ctx, userID, limit, cursor)
}
+100
View File
@@ -0,0 +1,100 @@
package service
import (
"context"
"encoding/json"
"net/http"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"high-loud-apps-labs/internal/domain"
"high-loud-apps-labs/internal/httpapi/dto"
)
type MessageService struct {
messages domain.MessageRepository
chats domain.ChatRepository
idempotencyTTL time.Duration
}
func NewMessageService(
messages domain.MessageRepository,
chats domain.ChatRepository,
idempotencyTTL time.Duration,
) *MessageService {
return &MessageService{
messages: messages,
chats: chats,
idempotencyTTL: idempotencyTTL,
}
}
func (s *MessageService) Create(ctx context.Context, senderID, chatID, text, idempotencyKey, requestPath string,
) (*domain.CreateIdempotentResult, error) {
if strings.TrimSpace(text) == "" {
return nil, &domain.ValidationError{
Field: "text",
Message: "не может состоять только из пробелов",
}
}
if utf8.RuneCountInString(text) > 4000 {
return nil, &domain.ValidationError{
Field: "text",
Message: "не более 4000 символов",
}
}
if err := s.ensureMember(ctx, senderID, chatID); err != nil {
return nil, err
}
fresh := &domain.Message{
ID: uuid.NewString(),
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: time.Now().UTC(),
}
body, err := json.Marshal(dto.MessageFromDomain(fresh))
if err != nil {
return nil, err
}
return s.messages.CreateIdempotent(
ctx,
domain.IdempotencyScope{
UserID: senderID,
Method: http.MethodPost,
Path: requestPath,
Key: idempotencyKey,
},
domain.RequestHash(text),
fresh,
body,
s.idempotencyTTL,
)
}
func (s *MessageService) List(ctx context.Context, userID, chatID string, limit int, cursor *string) ([]domain.Message, *string, error) {
if err := s.ensureMember(ctx, userID, chatID); err != nil {
return nil, nil, err
}
return s.messages.ListByChat(ctx, chatID, limit, cursor)
}
func (s *MessageService) ensureMember(ctx context.Context, userID, chatID string) error {
c, err := s.chats.GetByID(ctx, chatID)
if err != nil {
return err
}
for _, m := range c.MemberIDs {
if m == userID {
return nil
}
}
return &domain.NotFoundError{Entity: "chat", ID: chatID}
}
+112
View File
@@ -0,0 +1,112 @@
package service
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
// PasswordHasher хеширует пароли и проверяет пароль сохранённого хеша.
type PasswordHasher interface {
Hash(password string) (string, error)
Verify(password, encoded string) (bool, error)
}
type Argon2idHasher struct {
memory uint32
iterations uint32
parallelism uint8
saltLength uint32
keyLength uint32
}
func NewArgon2idHasher() *Argon2idHasher {
return &Argon2idHasher{
memory: 64 * 1024,
iterations: 3,
parallelism: 4,
saltLength: 16,
keyLength: 32,
}
}
func (h *Argon2idHasher) Hash(password string) (string, error) {
salt := make([]byte, h.saltLength)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("генерация соли: %w", err)
}
key := argon2.IDKey(
[]byte(password),
salt,
h.iterations,
h.memory,
h.parallelism,
h.keyLength,
)
return fmt.Sprintf(
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version,
h.memory,
h.iterations,
h.parallelism,
base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(key),
), nil
}
// Verify сравнивает пароль с сохранённым PHC-хешем.
// Возвращает false и nil при неверном пароле.
// Возвращает false и ошибку, если строка хеша повреждена или несовместима.
func (h *Argon2idHasher) Verify(password, encoded string) (bool, error) {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[1] != "argon2id" {
return false, errors.New("некорректный формат хеша")
}
var version int
if n, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || n != 1 {
return false, errors.New("некорректная версия хеша")
}
if version != argon2.Version {
return false, errors.New("неподдерживаемая версия Argon2")
}
var (
memory uint32
iterations uint32
parallelism uint8
)
if n, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &iterations, &parallelism); err != nil || n != 3 {
return false, errors.New("некорректные параметры хеша")
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil {
return false, errors.New("некорректная соль")
}
wantKey, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil {
return false, errors.New("некорректный ключ")
}
gotKey := argon2.IDKey(
[]byte(password),
salt,
iterations,
memory,
parallelism,
uint32(len(wantKey)),
)
return subtle.ConstantTimeCompare(gotKey, wantKey) == 1, nil
}
var _ PasswordHasher = (*Argon2idHasher)(nil)
+127
View File
@@ -0,0 +1,127 @@
package service
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"time"
"high-loud-apps-labs/internal/domain"
)
// SessionService отвечает за вход, проверку и отзыв сессий.
type SessionService struct {
users domain.UserRepository
sessions domain.SessionRepository
hasher PasswordHasher
ttl time.Duration
}
// NewSessionService создаёт сервис с заданным TTL сессий.
func NewSessionService(
users domain.UserRepository,
sessions domain.SessionRepository,
hasher PasswordHasher,
ttl time.Duration,
) *SessionService {
return &SessionService{
users: users,
sessions: sessions,
hasher: hasher,
ttl: ttl,
}
}
// Login проверяет username/password и создаёт новую сессию.
// Возвращает сессию, открытый токен и пользователя.
// Открытый токен уходит клиенту; в БД сохраняется только его SHA-256.
func (s *SessionService) Login(ctx context.Context, username, password string) (*domain.Session, string, *domain.User, error) {
user, err := s.users.GetByUsername(ctx, username)
if err != nil {
if errors.Is(err, domain.ErrNotFound) {
return nil, "", nil, &domain.UnauthorizedError{Reason: "неверные учётные данные"}
}
return nil, "", nil, err
}
ok, err := s.hasher.Verify(password, user.PasswordHash)
if err != nil {
return nil, "", nil, err
}
if !ok {
return nil, "", nil, &domain.UnauthorizedError{Reason: "неверные учётные данные"}
}
token, err := generateToken()
if err != nil {
return nil, "", nil, err
}
tokenHash := sha256.Sum256([]byte(token))
now := time.Now().UTC()
session := &domain.Session{
TokenHash: tokenHash[:],
UserID: user.ID,
ExpiresAt: now.Add(s.ttl),
CreatedAt: now,
}
if err := s.sessions.Create(ctx, session); err != nil {
return nil, "", nil, err
}
return session, token, user, nil
}
// Resolve проверяет токен и возвращает пользователя сессии.
// Истёкший, отозванный или неизвестный токен - UnauthorizedError по контракту
func (s *SessionService) Resolve(ctx context.Context, token string) (*domain.User, error) {
if token == "" {
return nil, &domain.UnauthorizedError{Reason: "пустой токен"}
}
tokenHash := sha256.Sum256([]byte(token))
session, err := s.sessions.GetByTokenHash(ctx, tokenHash[:])
if err != nil {
if errors.Is(err, domain.ErrNotFound) {
return nil, &domain.UnauthorizedError{Reason: "неизвестный токен"}
}
return nil, err
}
if !session.ExpiresAt.After(time.Now().UTC()) {
return nil, &domain.UnauthorizedError{Reason: "сессия истекла"}
}
user, err := s.users.GetByID(ctx, session.UserID)
if err != nil {
if errors.Is(err, domain.ErrNotFound) {
return nil, &domain.UnauthorizedError{Reason: "пользователь сессии не найден"}
}
return nil, err
}
return user, nil
}
// Revoke удаляет сессию по токену.
func (s *SessionService) Revoke(ctx context.Context, token string) error {
if token == "" {
return nil
}
tokenHash := sha256.Sum256([]byte(token))
return s.sessions.DeleteByTokenHash(ctx, tokenHash[:])
}
// generateToken возвращает 32 случайных байта в base64url без паддинга=.
func generateToken() (string, error) {
buf := make([]byte, 32)
if _, err := rand.Read(buf); err != nil {
return "", fmt.Errorf("генерация токена: %w", err)
}
return base64.RawURLEncoding.EncodeToString(buf), nil
}
+78
View File
@@ -0,0 +1,78 @@
package service
import (
"context"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"high-loud-apps-labs/internal/domain"
)
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
type UserService struct {
users domain.UserRepository
hasher PasswordHasher
}
func NewUserService(users domain.UserRepository, hasher PasswordHasher) *UserService {
return &UserService{users: users, hasher: hasher}
}
func (s *UserService) Create(ctx context.Context, username, displayName, password string) (*domain.User, error) {
if !usernamePattern.MatchString(username) {
return nil, &domain.ValidationError{
Field: "username",
Message: "должен соответствовать ^[a-z0-9_]{3,32}$",
}
}
if strings.TrimSpace(displayName) == "" {
return nil, &domain.ValidationError{
Field: "display_name",
Message: "не может состоять только из пробелов",
}
}
if utf8.RuneCountInString(displayName) > 100 {
return nil, &domain.ValidationError{
Field: "display_name",
Message: "не более 100 символов",
}
}
passwordRunes := utf8.RuneCountInString(password)
if passwordRunes < 12 || passwordRunes > 128 {
return nil, &domain.ValidationError{
Field: "password",
Message: "длина 12–128 символов",
}
}
hash, err := s.hasher.Hash(password)
if err != nil {
return nil, err
}
u := &domain.User{
ID: uuid.NewString(),
Username: username,
DisplayName: displayName,
PasswordHash: hash,
CreatedAt: time.Now().UTC(),
}
if err := s.users.Create(ctx, u); err != nil {
return nil, err
}
return u, nil
}
func (s *UserService) GetByID(ctx context.Context, id string) (*domain.User, error) {
return s.users.GetByID(ctx, id)
}
func (s *UserService) GetByUsername(ctx context.Context, username string) (*domain.User, error) {
return s.users.GetByUsername(ctx, username)
}