forked from mtusi2026/mtusi2026lab3
78 lines
1.9 KiB
Go
78 lines
1.9 KiB
Go
package domain
|
|
|
|
import (
|
|
"fmt"
|
|
"regexp"
|
|
"strings"
|
|
"unicode/utf8"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
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 ValidateMessageText(text string) error {
|
|
textRunes := utf8.RuneCountInString(text)
|
|
if textRunes < 1 || textRunes > 4000 {
|
|
return fmt.Errorf("message text length must be between 1 and 4000 code points")
|
|
}
|
|
if strings.TrimSpace(text) == "" {
|
|
return fmt.Errorf("message text cannot be only whitespace")
|
|
}
|
|
return nil
|
|
}
|