forked from mtusi2026/mtusi2026lab2
56 lines
1.3 KiB
Go
56 lines
1.3 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"regexp"
|
|
"unicode/utf8"
|
|
"uuid"
|
|
|
|
"messenger/internal/domain"
|
|
)
|
|
|
|
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
|
|
|
const (
|
|
minPasswordLen = 12
|
|
maxPasswordLen = 128
|
|
)
|
|
|
|
type UserService struct {
|
|
repo UserRepository
|
|
}
|
|
|
|
func NewUserService(repo UserRepository) *UserService {
|
|
return &UserService{repo: repo}
|
|
}
|
|
|
|
func (s *UserService) Register(ctx context.Context, username, displayName, password string) (domain.User, error) {
|
|
if !usernameRe.MatchString(username) {
|
|
return domain.User{}, fmt.Errorf("%w: username must match [a-z0-9_]{3,32}", domain.ErrInvalidInput)
|
|
}
|
|
if err := checkText("display_name", displayName, 100); err != nil {
|
|
return domain.User{}, err
|
|
}
|
|
if err := checkText("password", password, maxPasswordLen); err != nil {
|
|
return domain.User{}, err
|
|
}
|
|
if utf8.RuneCountInString(password) < minPasswordLen {
|
|
return domain.User{}, fmt.Errorf("%w: password must be at least %d characters", domain.ErrInvalidInput, minPasswordLen)
|
|
}
|
|
hash, err := hashPassword(password)
|
|
if err != nil {
|
|
return domain.User{}, err
|
|
}
|
|
u := domain.User{
|
|
ID: uuid.New(),
|
|
Username: username,
|
|
DisplayName: displayName,
|
|
CreatedAt: now(),
|
|
}
|
|
if err := s.repo.CreateUser(ctx, u, hash); err != nil {
|
|
return domain.User{}, err
|
|
}
|
|
return u, nil
|
|
}
|