Files
mtusi2026lab2/internal/user/service.go
T

89 lines
2.4 KiB
Go

package user
import (
"context"
"errors"
"fmt"
"sync"
"github.com/google/uuid"
"messenger/internal/platform/ident"
"messenger/internal/platform/password"
)
type Service struct {
repo Repository
}
func NewService(repo Repository) *Service {
return &Service{repo: repo}
}
// Register validates every field before hashing, so invalid input never pays
// for the KDF.
func (s *Service) Register(ctx context.Context, username, displayName, plain string) (User, error) {
u, err := New(ident.New(), username, displayName)
if err != nil {
return User{}, err
}
if err := ValidatePassword(plain); err != nil {
return User{}, err
}
u.PasswordHash = password.Hash(plain)
if err := s.repo.Create(ctx, u); err != nil {
return User{}, err
}
return u, nil
}
// dummyHash is verified for unknown usernames, so a failed login takes the
// same time whether or not the user exists.
var dummyHash = sync.OnceValue(func() string {
return password.Hash("timing-equaliser-password")
})
// Authenticate returns the user whose password matches, or
// ErrInvalidCredentials for an unknown username and a wrong password alike.
// The username comes straight from the Basic header, so one that cannot
// exist (including NUL or invalid UTF-8, which the database would reject)
// is answered without a query, but after the same KDF work.
func (s *Service) Authenticate(ctx context.Context, username, plain string) (User, error) {
if !usernamePattern.MatchString(username) {
_, _ = password.Verify(dummyHash(), plain)
return User{}, ErrInvalidCredentials
}
u, err := s.repo.GetByUsername(ctx, username)
if errors.Is(err, ErrNotFound) {
_, _ = password.Verify(dummyHash(), plain)
return User{}, ErrInvalidCredentials
}
if err != nil {
return User{}, fmt.Errorf("find user: %w", err)
}
ok, err := password.Verify(u.PasswordHash, plain)
if err != nil {
return User{}, fmt.Errorf("verify password of user %s: %w", u.ID, err)
}
if !ok {
return User{}, ErrInvalidCredentials
}
return u, nil
}
func (s *Service) GetByID(ctx context.Context, id uuid.UUID) (User, error) {
return s.repo.GetByID(ctx, id)
}
// ExistingIDs serves the chats module when it validates member lists.
func (s *Service) ExistingIDs(ctx context.Context, ids []uuid.UUID) ([]uuid.UUID, error) {
if len(ids) == 0 {
return []uuid.UUID{}, nil
}
found, err := s.repo.ExistingIDs(ctx, ids)
if err != nil {
return nil, fmt.Errorf("user lookup: %w", err)
}
return found, nil
}