forked from mtusi2026/mtusi2026lab4
feat: lab4 - S3 attachments, image validation, failover
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
// Package validate implements the field rules stated in contracts/README.md.
|
||||
package validate
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const (
|
||||
UsernameMinLen = 3
|
||||
UsernameMaxLen = 32
|
||||
DisplayNameMaxLen = 100
|
||||
PasswordMinLen = 12
|
||||
PasswordMaxLen = 128
|
||||
TitleMaxLen = 100
|
||||
MessageMaxRunes = 4000
|
||||
)
|
||||
|
||||
// UUID reports whether s has the canonical 8-4-4-4-12 hex shape.
|
||||
func UUID(s string) bool {
|
||||
if len(s) != 36 {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(s); i++ {
|
||||
switch i {
|
||||
case 8, 13, 18, 23:
|
||||
if s[i] != '-' {
|
||||
return false
|
||||
}
|
||||
default:
|
||||
if !isHex(s[i]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Username enforces ^[a-z0-9_]{3,32}$.
|
||||
func Username(s string) bool {
|
||||
if len(s) < UsernameMinLen || len(s) > UsernameMaxLen {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' {
|
||||
continue
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// NonBlank requires at least one non-whitespace code point.
|
||||
func NonBlank(s string) bool {
|
||||
return strings.TrimSpace(s) != ""
|
||||
}
|
||||
|
||||
// DisplayName allows 1..100 code points and rejects whitespace-only values.
|
||||
func DisplayName(s string) bool {
|
||||
return NonBlank(s) && RuneLen(s) <= DisplayNameMaxLen
|
||||
}
|
||||
|
||||
// Password checks the 12..128 code point range; Basic auth carries UTF-8.
|
||||
func Password(s string) bool {
|
||||
n := RuneLen(s)
|
||||
return n >= PasswordMinLen && n <= PasswordMaxLen
|
||||
}
|
||||
|
||||
// Title allows 1..100 code points and rejects whitespace-only values.
|
||||
func Title(s string) bool {
|
||||
return NonBlank(s) && RuneLen(s) <= TitleMaxLen
|
||||
}
|
||||
|
||||
// MessageText allows 1..4000 code points and rejects whitespace-only values.
|
||||
func MessageText(s string) bool {
|
||||
return NonBlank(s) && RuneLen(s) <= MessageMaxRunes
|
||||
}
|
||||
|
||||
// RuneLen counts Unicode code points, not bytes.
|
||||
func RuneLen(s string) int {
|
||||
return utf8.RuneCountInString(s)
|
||||
}
|
||||
|
||||
func isHex(c byte) bool {
|
||||
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
|
||||
}
|
||||
Reference in New Issue
Block a user