forked from mtusi2026/mtusi2026lab2
feat: persist data in PostgreSQL and add Basic/Bearer sessions in Redis
This commit is contained in:
+18
-11
@@ -2,9 +2,9 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"unicode/utf8"
|
||||
"uuid"
|
||||
|
||||
"messenger/internal/domain"
|
||||
@@ -12,6 +12,11 @@ import (
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
const (
|
||||
minPasswordLen = 12
|
||||
maxPasswordLen = 128
|
||||
)
|
||||
|
||||
type UserService struct {
|
||||
repo UserRepository
|
||||
}
|
||||
@@ -20,29 +25,31 @@ func NewUserService(repo UserRepository) *UserService {
|
||||
return &UserService{repo: repo}
|
||||
}
|
||||
|
||||
func (s *UserService) Register(ctx context.Context, username, displayName string) (domain.User, error) {
|
||||
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); err != nil {
|
||||
if err := s.repo.CreateUser(ctx, u, hash); 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