Files
mtusi2026lab4/internal/domain/validation.go
T

102 lines
2.7 KiB
Go

package domain
import (
"fmt"
"regexp"
"strings"
"unicode/utf8"
"github.com/google/uuid"
)
const MaxMessageAttachments = 10
var usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
func ValidateUser(username, displayName string) error {
if !usernameRegex.MatchString(username) {
return fmt.Errorf("username must match [a-z0-9_]{3,32}")
}
nameRunes := utf8.RuneCountInString(displayName)
if nameRunes < 1 || nameRunes > 100 {
return fmt.Errorf("display_name length must be between 1 and 100 code points")
}
if strings.TrimSpace(displayName) == "" {
return fmt.Errorf("display_name cannot be only whitespace")
}
return nil
}
// Validate remains as a compatibility convenience for existing callers.
func (u User) Validate() error {
return ValidateUser(u.Username, u.DisplayName)
}
func ValidateChatInput(title string, memberIDs []string, callerID string) error {
titleRunes := utf8.RuneCountInString(title)
if titleRunes < 1 || titleRunes > 100 || strings.TrimSpace(title) == "" {
return fmt.Errorf("invalid chat title")
}
if len(memberIDs) == 0 {
return fmt.Errorf("member_ids cannot be empty")
}
if len(memberIDs) > 100 {
return fmt.Errorf("member_ids must contain at most 100 users")
}
hasCaller := false
seen := make(map[string]struct{}, len(memberIDs))
for _, id := range memberIDs {
if _, err := uuid.Parse(id); err != nil {
return fmt.Errorf("invalid member uuid: %s", id)
}
if _, exists := seen[id]; exists {
return fmt.Errorf("duplicate member_id: %s", id)
}
seen[id] = struct{}{}
if id == callerID {
hasCaller = true
}
}
if !hasCaller {
return fmt.Errorf("caller must be in member_ids")
}
return nil
}
func ValidateMessageInput(text string, attachmentIDs []string) error {
textRunes := utf8.RuneCountInString(text)
if textRunes > 4000 {
return fmt.Errorf("message text length must be at most 4000 code points")
}
if len(attachmentIDs) > MaxMessageAttachments {
return fmt.Errorf("attachment_ids must contain at most %d items", MaxMessageAttachments)
}
seen := make(map[string]struct{}, len(attachmentIDs))
for _, attachmentID := range attachmentIDs {
parsedID, err := uuid.Parse(attachmentID)
if err != nil {
return fmt.Errorf("invalid attachment uuid: %s", attachmentID)
}
canonicalID := parsedID.String()
if _, exists := seen[canonicalID]; exists {
return fmt.Errorf("duplicate attachment_id: %s", attachmentID)
}
seen[canonicalID] = struct{}{}
}
if strings.TrimSpace(text) == "" && len(attachmentIDs) == 0 {
return fmt.Errorf("message must contain non-blank text or at least one attachment")
}
return nil
}
// ValidateMessageText remains for callers that create text-only messages.
func ValidateMessageText(text string) error {
return ValidateMessageInput(text, nil)
}