79 lines
1.9 KiB
Go
79 lines
1.9 KiB
Go
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)
|
||
}
|