Перенести пользователей в PostgreSQL и добавить пароли

This commit is contained in:
2026-10-06 14:54:34 +03:00
parent 46c00436a0
commit 618d3919d1
17 changed files with 482 additions and 219 deletions
+37 -1
View File
@@ -2,11 +2,14 @@ package user
import (
"context"
"errors"
"fmt"
"sync"
"github.com/google/uuid"
"messenger/internal/platform/ident"
"messenger/internal/platform/password"
)
type Service struct {
@@ -17,17 +20,50 @@ func NewService(repo Repository) *Service {
return &Service{repo: repo}
}
func (s *Service) Register(ctx context.Context, username, displayName string) (User, error) {
// 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.
func (s *Service) Authenticate(ctx context.Context, username, plain string) (User, error) {
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)
}