72 lines
2.1 KiB
Go
72 lines
2.1 KiB
Go
// 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))
|
|
}
|
|
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
|
|
}
|