Перенесите реализацию ЛР 4 на стенд ЛР 5
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
// Package user is the users module. The entity mirrors the table row and
|
||||
// carries no behaviour; New only enforces input invariants and CreatedAt
|
||||
// derives from the UUIDv7 id. The password itself is never kept: the service
|
||||
// validates it and stores only its hash.
|
||||
package user
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/ident"
|
||||
)
|
||||
|
||||
const (
|
||||
MaxDisplayNameCodePoints = 100
|
||||
MinPasswordCodePoints = 12
|
||||
MaxPasswordCodePoints = 128
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = apperr.NotFound("user not found")
|
||||
ErrUsernameTaken = apperr.Conflict("username already taken")
|
||||
// ErrInvalidCredentials covers an unknown username and a wrong password
|
||||
// alike, so a login attempt cannot probe which usernames exist.
|
||||
ErrInvalidCredentials = apperr.Unauthorized("invalid username or password")
|
||||
)
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
type User struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
PasswordHash string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func New(id uuid.UUID, username, displayName string) (User, error) {
|
||||
if !usernamePattern.MatchString(username) {
|
||||
return User{}, apperr.Invalid("username must match [a-z0-9_]{3,32}")
|
||||
}
|
||||
if strings.TrimSpace(displayName) == "" {
|
||||
return User{}, apperr.Invalid("display_name must not be blank")
|
||||
}
|
||||
if utf8.RuneCountInString(displayName) > MaxDisplayNameCodePoints {
|
||||
return User{}, apperr.Invalid(fmt.Sprintf("display_name must be at most %d characters", MaxDisplayNameCodePoints))
|
||||
}
|
||||
// PostgreSQL text cannot hold U+0000.
|
||||
if strings.ContainsRune(displayName, 0) {
|
||||
return User{}, apperr.Invalid("display_name must not contain the NUL character")
|
||||
}
|
||||
return User{
|
||||
ID: id,
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: ident.TimeOf(id),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ValidatePassword checks the contract length in Unicode code points.
|
||||
func ValidatePassword(plain string) error {
|
||||
if strings.TrimSpace(plain) == "" {
|
||||
return apperr.Invalid("password must not be blank")
|
||||
}
|
||||
if n := utf8.RuneCountInString(plain); n < MinPasswordCodePoints || n > MaxPasswordCodePoints {
|
||||
return apperr.Invalid(fmt.Sprintf("password must be %d to %d characters", MinPasswordCodePoints, MaxPasswordCodePoints))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user