forked from mtusi2026/mtusi2026lab5
ЛР 5: асинхронная обработка изображений, уровень 5
This commit is contained in:
@@ -0,0 +1,291 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/imagecheck"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
var _ AttachmentsService = (*Attachments)(nil)
|
||||
|
||||
// ObjectKeyPrefix — префикс ключей оригиналов. Очиститель обходит только его.
|
||||
const ObjectKeyPrefix = "originals/"
|
||||
|
||||
// Предел на компенсирующее удаление объекта, когда запись метаданных не удалась.
|
||||
const compensationTimeout = 5 * time.Second
|
||||
|
||||
type AttachmentLimits struct {
|
||||
MaxUploadBytes int64
|
||||
MaxImagePixels int64
|
||||
MaxConcurrentUploads int
|
||||
}
|
||||
|
||||
type attachmentRepo interface {
|
||||
store.ChatStore
|
||||
store.AttachmentStore
|
||||
}
|
||||
|
||||
type Attachments struct {
|
||||
repo attachmentRepo
|
||||
objects objectstore.Store
|
||||
limits AttachmentLimits
|
||||
checker *imagecheck.Checker
|
||||
// uploads — слоты загрузок. Вместе с лимитом размера они ограничивают диск реплики под временные
|
||||
// файлы; память на одну загрузку от размера файла не зависит.
|
||||
uploads chan struct{}
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func NewAttachments(repo attachmentRepo, objects objectstore.Store, limits AttachmentLimits, logger *slog.Logger) *Attachments {
|
||||
return &Attachments{
|
||||
repo: repo,
|
||||
objects: objects,
|
||||
limits: limits,
|
||||
checker: imagecheck.New(limits.MaxImagePixels),
|
||||
uploads: make(chan struct{}, limits.MaxConcurrentUploads),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Upload сохраняет проверенный оригинал в staging и публикует устойчивое задание до ответа 202.
|
||||
func (a *Attachments) Upload(ctx context.Context, in UploadInput) (domain.Attachment, error) {
|
||||
chatID, err := validate.CanonicalUUID("chat_id", in.ChatID)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if _, err := a.repo.ChatByID(ctx, in.CallerID, chatID); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if err := validate.Filename(in.Filename); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
declared, err := parseImageType(in.ContentType)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if in.ContentLength > a.limits.MaxUploadBytes {
|
||||
return domain.Attachment{}, domain.ErrPayloadTooLarge
|
||||
}
|
||||
|
||||
select {
|
||||
case a.uploads <- struct{}{}:
|
||||
defer func() { <-a.uploads }()
|
||||
default:
|
||||
return domain.Attachment{}, domain.ErrRateLimited
|
||||
}
|
||||
|
||||
spool, size, sum, err := a.spoolBody(in.Body)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
defer spool.Close()
|
||||
|
||||
if err := a.checkImage(ctx, spool, declared); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if _, err := spool.Seek(0, io.SeekStart); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: spool: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
|
||||
id := uuid.NewString()
|
||||
att := domain.Attachment{
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
OwnerID: in.CallerID,
|
||||
Filename: in.Filename,
|
||||
ContentType: declared,
|
||||
SizeBytes: size,
|
||||
SHA256: sum,
|
||||
ObjectKey: "staging/" + id,
|
||||
Status: "queued",
|
||||
}
|
||||
if err := a.objects.Put(ctx, att.ObjectKey, att.ContentType, spool, size); err != nil {
|
||||
// Объект мог успеть сохраниться. Удалять его здесь бессмысленно: при недоступном S3 удаление
|
||||
// тоже не пройдёт, а клиент лишние секунды ждал бы ответа. Его уберёт очиститель.
|
||||
a.logger.Warn("attachment object put failed", slog.Any("err", err))
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
saved, err := a.repo.CreateAttachment(ctx, att)
|
||||
if err != nil {
|
||||
a.compensate(ctx, att)
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if os.Getenv("FAULT_AFTER_UPLOAD_COMMIT") == "1" {
|
||||
os.Exit(86)
|
||||
} // Только для локальной проверки окна COMMIT/publish.
|
||||
return saved, nil
|
||||
}
|
||||
|
||||
// checkImage сравнивает заявленный тип с настоящим до декодирования: подмена типа не тратит память.
|
||||
func (a *Attachments) checkImage(ctx context.Context, file io.ReadSeeker, declared string) error {
|
||||
detected, err := a.checker.Inspect(file)
|
||||
if err == nil && detected != declared {
|
||||
return domain.ErrUnsupportedMedia
|
||||
}
|
||||
if err == nil {
|
||||
err = a.checker.Decode(ctx, file)
|
||||
}
|
||||
switch {
|
||||
case err == nil:
|
||||
return nil
|
||||
case errors.Is(err, imagecheck.ErrTooManyPixels):
|
||||
return domain.ErrPayloadTooLarge
|
||||
case errors.Is(err, imagecheck.ErrUnsupported):
|
||||
return domain.ErrUnsupportedMedia
|
||||
case errors.Is(err, imagecheck.ErrBusy):
|
||||
return domain.ErrRateLimited
|
||||
}
|
||||
return fmt.Errorf("%w: image check: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
|
||||
// compensate убирает объект, для которого метаданные не сохранились. Контекст отвязан от запроса:
|
||||
// клиент мог уже отключиться. Удалять можно, только убедившись, что строки нет: ошибка INSERT не
|
||||
// доказывает отсутствие записи (COMMIT мог пройти, а ответ потеряться), и удаление оставило бы
|
||||
// подтверждённую строку без файла. Если проверить нельзя, объект остаётся очистителю: он удаляет
|
||||
// только объекты без строки и только после grace period (cmd/janitor).
|
||||
func (a *Attachments) compensate(ctx context.Context, att domain.Attachment) {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), compensationTimeout)
|
||||
defer cancel()
|
||||
exists, err := a.repo.AttachmentExists(ctx, att.ID)
|
||||
if err != nil {
|
||||
a.logger.Warn("orphan check failed, object is left to the janitor", slog.String("object_key", att.ObjectKey), slog.Any("err", err))
|
||||
return
|
||||
}
|
||||
if exists {
|
||||
a.logger.Warn("metadata write reported an error but the row exists, object is kept", slog.String("attachment_id", att.ID))
|
||||
return
|
||||
}
|
||||
if err := a.objects.Delete(ctx, att.ObjectKey); err != nil {
|
||||
a.logger.Warn("compensating delete failed, object is left to the janitor", slog.String("object_key", att.ObjectKey), slog.Any("err", err))
|
||||
}
|
||||
}
|
||||
|
||||
// spoolBody пишет тело во временный файл и считает SHA-256 на лету. Файл удаляется из каталога сразу
|
||||
// после создания: данные живут, пока он открыт, поэтому при любом завершении, даже kill -9, на диске
|
||||
// ничего не остаётся и отдельная уборка не нужна. Это не хранилище: 201 вернётся только после S3.
|
||||
func (a *Attachments) spoolBody(body io.Reader) (*os.File, int64, string, error) {
|
||||
file, err := os.CreateTemp("", "upload-*")
|
||||
if err != nil {
|
||||
return nil, 0, "", fmt.Errorf("%w: spool: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
if err := os.Remove(file.Name()); err != nil {
|
||||
file.Close()
|
||||
return nil, 0, "", fmt.Errorf("%w: spool: %v", domain.ErrUnavailable, err)
|
||||
}
|
||||
|
||||
hash := sha256.New()
|
||||
source := &errorTrackingReader{r: body}
|
||||
// LimitReader на байт больше лимита: так отличается файл ровно на границе от файла больше неё.
|
||||
n, err := io.Copy(io.MultiWriter(file, hash), io.LimitReader(source, a.limits.MaxUploadBytes+1))
|
||||
switch {
|
||||
case source.err != nil:
|
||||
file.Close()
|
||||
// Клиент оборвал передачу или не уложился в таймаут. Отвечать чаще всего уже некому.
|
||||
return nil, 0, "", &validate.Error{Field: "body", Reason: "cannot read body"}
|
||||
case err != nil:
|
||||
file.Close()
|
||||
return nil, 0, "", fmt.Errorf("%w: spool: %v", domain.ErrUnavailable, err)
|
||||
case n > a.limits.MaxUploadBytes:
|
||||
file.Close()
|
||||
return nil, 0, "", domain.ErrPayloadTooLarge
|
||||
}
|
||||
return file, n, hex.EncodeToString(hash.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// errorTrackingReader отделяет ошибку чтения от клиента (400) от ошибки записи на диск (503).
|
||||
type errorTrackingReader struct {
|
||||
r io.Reader
|
||||
err error
|
||||
}
|
||||
|
||||
func (e *errorTrackingReader) Read(p []byte) (int, error) {
|
||||
n, err := e.r.Read(p)
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
e.err = err
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func parseImageType(header string) (string, error) {
|
||||
mediaType, _, err := mime.ParseMediaType(header)
|
||||
if err != nil {
|
||||
return "", domain.ErrUnsupportedMedia
|
||||
}
|
||||
switch mediaType {
|
||||
case domain.ContentTypePNG, domain.ContentTypeJPEG:
|
||||
return mediaType, nil
|
||||
}
|
||||
return "", domain.ErrUnsupportedMedia
|
||||
}
|
||||
|
||||
func (a *Attachments) Get(ctx context.Context, callerID, attachmentID string) (domain.Attachment, error) {
|
||||
id, err := validate.CanonicalUUID("attachment_id", attachmentID)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
return a.repo.AttachmentForMember(ctx, callerID, id)
|
||||
}
|
||||
|
||||
func (a *Attachments) Content(ctx context.Context, callerID, attachmentID, variant string) (domain.Attachment, io.ReadCloser, error) {
|
||||
if err := validateVariantName(variant); err != nil {
|
||||
return domain.Attachment{}, nil, err
|
||||
}
|
||||
att, err := a.Get(ctx, callerID, attachmentID)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, nil, err
|
||||
}
|
||||
if att.Status != domain.StatusReady {
|
||||
return domain.Attachment{}, nil, domain.ErrConflict
|
||||
}
|
||||
if variant != VariantOriginal {
|
||||
found := false
|
||||
for _, v := range att.Variants {
|
||||
if v.Name == variant {
|
||||
att.ObjectKey = variant + "s/" + att.ID
|
||||
att.ContentType, att.SizeBytes, att.SHA256 = v.ContentType, v.SizeBytes, v.SHA256
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return domain.Attachment{}, nil, domain.ErrNotFound
|
||||
}
|
||||
}
|
||||
body, size, err := a.objects.Get(ctx, att.ObjectKey)
|
||||
if err != nil {
|
||||
if errors.Is(err, objectstore.ErrNotFound) {
|
||||
return domain.Attachment{}, nil, fmt.Errorf("attachment %s: object missing in bucket", att.ID)
|
||||
}
|
||||
a.logger.Warn("attachment object get failed", slog.Any("err", err))
|
||||
return domain.Attachment{}, nil, err
|
||||
}
|
||||
if size != att.SizeBytes {
|
||||
body.Close()
|
||||
return domain.Attachment{}, nil, fmt.Errorf("attachment %s: object size %d differs from metadata %d", att.ID, size, att.SizeBytes)
|
||||
}
|
||||
return att, body, nil
|
||||
}
|
||||
|
||||
func validateVariantName(variant string) error {
|
||||
switch variant {
|
||||
case VariantOriginal, "thumbnail", "crop", "optimized":
|
||||
return nil
|
||||
}
|
||||
return &validate.Error{Field: "variant", Reason: "unknown variant"}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/token"
|
||||
)
|
||||
|
||||
var (
|
||||
_ AuthService = (*Auth)(nil)
|
||||
)
|
||||
|
||||
type Auth struct {
|
||||
users store.UserStore
|
||||
sessions session.Store
|
||||
hasher *password.Hasher
|
||||
ttl time.Duration
|
||||
now func() time.Time
|
||||
|
||||
dummyHash string
|
||||
}
|
||||
|
||||
func NewAuth(users store.UserStore, sessions session.Store, hasher *password.Hasher, ttl time.Duration) (*Auth, error) {
|
||||
dummy, err := hasher.Hash(context.Background(), "dummy-password-for-timing")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("auth: dummy hash: %w", err)
|
||||
}
|
||||
return &Auth{
|
||||
users: users,
|
||||
sessions: sessions,
|
||||
hasher: hasher,
|
||||
ttl: ttl,
|
||||
now: time.Now,
|
||||
dummyHash: dummy,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *Auth) Login(ctx context.Context, username, plainPassword string) (domain.Session, error) {
|
||||
user, hash, err := a.users.CredentialsByUsername(ctx, username)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
_, _ = a.hasher.Verify(ctx, plainPassword, a.dummyHash)
|
||||
return domain.Session{}, domain.ErrUnauthorized
|
||||
case err != nil:
|
||||
return domain.Session{}, err
|
||||
}
|
||||
|
||||
ok, err := a.hasher.Verify(ctx, plainPassword, hash)
|
||||
if err != nil {
|
||||
if errors.Is(err, password.ErrMalformedHash) {
|
||||
return domain.Session{}, domain.ErrUnauthorized
|
||||
}
|
||||
return domain.Session{}, err
|
||||
}
|
||||
if !ok {
|
||||
return domain.Session{}, domain.ErrUnauthorized
|
||||
}
|
||||
|
||||
plain, tokenHash, err := token.New()
|
||||
if err != nil {
|
||||
return domain.Session{}, err
|
||||
}
|
||||
expiresAt := a.now().Add(a.ttl).UTC().Truncate(time.Second)
|
||||
if err := a.sessions.Save(ctx, tokenHash, session.Session{UserID: user.ID, ExpiresAt: expiresAt}); err != nil {
|
||||
return domain.Session{}, err
|
||||
}
|
||||
return domain.Session{Token: plain, ExpiresAt: expiresAt, User: user}, nil
|
||||
}
|
||||
|
||||
func (a *Auth) Authenticate(ctx context.Context, plainToken string) (string, error) {
|
||||
tokenHash, err := token.Parse(plainToken)
|
||||
if err != nil {
|
||||
return "", domain.ErrUnauthorized
|
||||
}
|
||||
s, err := a.sessions.Get(ctx, tokenHash)
|
||||
if errors.Is(err, session.ErrNotFound) {
|
||||
return "", domain.ErrUnauthorized
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !a.now().Before(s.ExpiresAt) {
|
||||
return "", domain.ErrUnauthorized
|
||||
}
|
||||
return s.UserID, nil
|
||||
}
|
||||
|
||||
func (a *Auth) Logout(ctx context.Context, plainToken string) error {
|
||||
tokenHash, err := token.Parse(plainToken)
|
||||
if err != nil {
|
||||
return domain.ErrUnauthorized
|
||||
}
|
||||
return a.sessions.Delete(ctx, tokenHash)
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
var (
|
||||
_ ChatsService = (*Chats)(nil)
|
||||
)
|
||||
|
||||
type Chats struct {
|
||||
store store.ChatStore
|
||||
}
|
||||
|
||||
func NewChats(s store.ChatStore) *Chats {
|
||||
return &Chats{store: s}
|
||||
}
|
||||
|
||||
func (c *Chats) Create(ctx context.Context, callerID, title string, memberIDs []string) (domain.Chat, error) {
|
||||
if err := validate.ChatTitle(title); err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
memberIDs, err := validate.MemberIDs(memberIDs, callerID)
|
||||
if err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
return c.store.CreateChat(ctx, callerID, title, memberIDs)
|
||||
}
|
||||
|
||||
func (c *Chats) Get(ctx context.Context, callerID, chatID string) (domain.Chat, error) {
|
||||
chatID, err := validate.CanonicalUUID("chat_id", chatID)
|
||||
if err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
return c.store.ChatByID(ctx, callerID, chatID)
|
||||
}
|
||||
|
||||
func (c *Chats) List(ctx context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error) {
|
||||
if err := validate.Limit(limit); err != nil {
|
||||
return domain.Page[domain.Chat]{}, err
|
||||
}
|
||||
return c.store.ListChats(ctx, callerID, cursor, limit)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
var (
|
||||
_ MessagesService = (*Messages)(nil)
|
||||
)
|
||||
|
||||
type Messages struct {
|
||||
store store.MessageStore
|
||||
}
|
||||
|
||||
func NewMessages(s store.MessageStore) *Messages {
|
||||
return &Messages{store: s}
|
||||
}
|
||||
|
||||
func (m *Messages) Send(ctx context.Context, callerID, chatID, idempotencyKey, text string, attachmentIDs []string) (domain.Message, error) {
|
||||
chatID, err := validate.CanonicalUUID("chat_id", chatID)
|
||||
if err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
if err := validate.IdempotencyKey(idempotencyKey); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
ids, err := validate.AttachmentIDs(attachmentIDs)
|
||||
if err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
if err := validate.MessageText(text, len(ids) > 0); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
return m.store.AddMessage(ctx, callerID, chatID, idempotencyKey, text, ids)
|
||||
}
|
||||
|
||||
func (m *Messages) List(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) {
|
||||
chatID, err := validate.CanonicalUUID("chat_id", chatID)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
if err := validate.Limit(limit); err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
return m.store.ListMessages(ctx, callerID, chatID, cursor, limit)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
type UsersService interface {
|
||||
Register(ctx context.Context, username, displayName, password string) (domain.User, error)
|
||||
Me(ctx context.Context, callerID string) (domain.User, error)
|
||||
}
|
||||
|
||||
type ChatsService interface {
|
||||
Create(ctx context.Context, callerID, title string, memberIDs []string) (domain.Chat, error)
|
||||
Get(ctx context.Context, callerID, chatID string) (domain.Chat, error)
|
||||
List(ctx context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error)
|
||||
}
|
||||
|
||||
type MessagesService interface {
|
||||
Send(ctx context.Context, callerID, chatID, idempotencyKey, text string, attachmentIDs []string) (domain.Message, error)
|
||||
List(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error)
|
||||
}
|
||||
|
||||
// VariantOriginal — вариант содержимого по умолчанию.
|
||||
const VariantOriginal = "original"
|
||||
|
||||
// UploadInput — параметры загрузки файла. Body читается не дальше лимита размера.
|
||||
type UploadInput struct {
|
||||
CallerID string
|
||||
ChatID string
|
||||
Filename string
|
||||
ContentType string
|
||||
ContentLength int64
|
||||
Body io.Reader
|
||||
}
|
||||
|
||||
type AttachmentsService interface {
|
||||
Upload(ctx context.Context, in UploadInput) (domain.Attachment, error)
|
||||
Get(ctx context.Context, callerID, attachmentID string) (domain.Attachment, error)
|
||||
// Content возвращает метаданные и поток байтов. Поток обязательно закрыть.
|
||||
Content(ctx context.Context, callerID, attachmentID, variant string) (domain.Attachment, io.ReadCloser, error)
|
||||
}
|
||||
|
||||
type AuthService interface {
|
||||
Login(ctx context.Context, username, password string) (domain.Session, error)
|
||||
Authenticate(ctx context.Context, token string) (userID string, err error)
|
||||
Logout(ctx context.Context, token string) error
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
var (
|
||||
_ UsersService = (*Users)(nil)
|
||||
)
|
||||
|
||||
type Users struct {
|
||||
store store.UserStore
|
||||
hasher *password.Hasher
|
||||
}
|
||||
|
||||
func NewUsers(s store.UserStore, h *password.Hasher) *Users {
|
||||
return &Users{store: s, hasher: h}
|
||||
}
|
||||
|
||||
func (u *Users) Register(ctx context.Context, username, displayName, plainPassword string) (domain.User, error) {
|
||||
if err := validate.Username(username); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
if err := validate.DisplayName(displayName); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
if err := validate.Password(plainPassword); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
hash, err := u.hasher.Hash(ctx, plainPassword)
|
||||
if err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
return u.store.CreateUser(ctx, username, displayName, hash)
|
||||
}
|
||||
|
||||
func (u *Users) Me(ctx context.Context, callerID string) (domain.User, error) {
|
||||
return u.store.UserByID(ctx, callerID)
|
||||
}
|
||||
Reference in New Issue
Block a user