46 lines
1.2 KiB
Go
46 lines
1.2 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
|
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/password"
|
|
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
|
)
|
|
|
|
type UserWriter interface {
|
|
CreateUser(context.Context, string, string, string) (model.User, error)
|
|
}
|
|
|
|
type Registration struct {
|
|
users UserWriter
|
|
hashSlots chan struct{}
|
|
}
|
|
|
|
func NewRegistration(users UserWriter) *Registration {
|
|
return &Registration{users: users, hashSlots: make(chan struct{}, 2)}
|
|
}
|
|
|
|
func (s *Registration) Register(ctx context.Context, username, displayName, secret string) (model.User, error) {
|
|
if !usernamePattern.MatchString(username) || !validText(displayName, 100) || password.Validate(secret) != nil {
|
|
return model.User{}, ErrInvalidRequest
|
|
}
|
|
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
select {
|
|
case s.hashSlots <- struct{}{}:
|
|
case <-ctx.Done():
|
|
return model.User{}, store.ErrUnavailable
|
|
}
|
|
hash, err := password.Hash(secret)
|
|
<-s.hashSlots
|
|
if err != nil {
|
|
return model.User{}, err
|
|
}
|
|
if ctx.Err() != nil {
|
|
return model.User{}, store.ErrUnavailable
|
|
}
|
|
return s.users.CreateUser(ctx, username, displayName, hash)
|
|
}
|