Files
mtusi2026lab2/app/internal/common/validator.go
T

152 lines
2.9 KiB
Go

package common
import (
"bytes"
"encoding/json"
"io"
"regexp"
"strconv"
"strings"
"unicode/utf8"
"github.com/go-playground/validator"
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
)
var (
validate = validator.New()
usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
)
func BindJSON(c fiber.Ctx, req any) error {
contentType := c.Get(fiber.HeaderContentType)
if !strings.HasPrefix(contentType, "application/json") {
return UnsupportedMedia("invalid JSON body")
}
body := c.Body()
if len(body) == 0 {
return BadRequest("request body is empty")
}
decoder := json.NewDecoder(bytes.NewReader(body))
decoder.DisallowUnknownFields()
if err := decoder.Decode(req); err != nil {
return BadRequest("invalid JSON body")
}
var extra json.RawMessage
if err := decoder.Decode(&extra); err != io.EOF {
return BadRequest("request body has extra trailing bytes")
}
if err := validate.Struct(req); err != nil {
return BadRequest("field validation failed")
}
return nil
}
func blank(s string) bool {
return strings.TrimSpace(s) == ""
}
func strLenBetween(s string, min, max int) bool {
n := utf8.RuneCountInString(s)
return n >= min && n <= max
}
func ValidateCreateUser(username, displayName string) string {
if !usernameRegex.MatchString(username) {
return "username must match ^[a-z0-9_]{3,32}$"
}
if blank(displayName) {
return "display_name must not be empty or only whitespace"
}
if !strLenBetween(displayName, 1, 100) {
return "display_name must be between 1 and 100 Unicode code points"
}
return ""
}
func ValidatePassword(password string) string {
if blank(password) {
return "password must not be empty or only whitespace"
}
if !strLenBetween(password, 12, 128) {
return "password must be between 12 and 128 Unicode code points"
}
return ""
}
func ValidateChatTitle(title string) string {
if blank(title) {
return "title must not be empty or only whitespace"
}
if !strLenBetween(title, 1, 100) {
return "title must be between 1 and 100 Unicode code points"
}
return ""
}
func ValidateMessageText(text string) string {
if blank(text) {
return "text must not be empty or only whitespace"
}
if !strLenBetween(text, 1, 4000) {
return "text must be between 1 and 4000 Unicode code points"
}
return ""
}
func validateLimitStr(s string) (int, bool) {
n, err := strconv.Atoi(s)
if err != nil {
return 0, false
}
if n < 1 || n > 100 {
return 0, false
}
return n, true
}
func ValidateMemberIDs(ids []uuid.UUID, callerID uuid.UUID) string {
if len(ids) < 1 || len(ids) > 100 {
return "member_ids must contain between 1 and 100 members"
}
seen := make(map[uuid.UUID]bool, len(ids))
callerFound := false
for _, id := range ids {
if seen[id] {
return "member_ids must not contain duplicates"
}
seen[id] = true
if id == callerID {
callerFound = true
}
}
if !callerFound {
return "caller must be included in member_ids"
}
return ""
}