forked from mtusi2026/mtusi2026lab2
chore(solution): pull lab1 solution
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"uuid"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
type UserService struct {
|
||||
repo UserRepository
|
||||
}
|
||||
|
||||
func NewUserService(repo UserRepository) *UserService {
|
||||
return &UserService{repo: repo}
|
||||
}
|
||||
|
||||
func (s *UserService) Register(ctx context.Context, username, displayName 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
|
||||
}
|
||||
u := domain.User{
|
||||
ID: uuid.New(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: now(),
|
||||
}
|
||||
if err := s.repo.CreateUser(ctx, u); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (s *UserService) Authenticate(ctx context.Context, id uuid.UUID) (domain.User, error) {
|
||||
u, err := s.repo.GetUser(ctx, id)
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
return domain.User{}, domain.ErrUnauthorized
|
||||
}
|
||||
return u, err
|
||||
}
|
||||
Reference in New Issue
Block a user