-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidation.go
More file actions
104 lines (92 loc) · 2.45 KB
/
validation.go
File metadata and controls
104 lines (92 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"encoding/json"
"fmt"
"os"
"regexp"
"strings"
"sync"
)
var (
usernameAllowedRe = regexp.MustCompile("^[a-z0-9_]+$")
bannedWordsOnce sync.Once
bannedWords []string
bannedWordsErr error
)
func loadBannedWordsLocal() ([]string, error) {
bannedWordsOnce.Do(func() {
file, err := os.Open("./banned_words.json")
if err != nil {
bannedWordsErr = fmt.Errorf("error opening banned_words.json: %w", err)
return
}
defer file.Close()
var words []string
if err := json.NewDecoder(file).Decode(&words); err != nil {
bannedWordsErr = fmt.Errorf("error decoding banned_words.json: %w", err)
return
}
bannedWords = words
})
return bannedWords, bannedWordsErr
}
func ValidateUsername(username Username) (bool, string) {
usernameLower := string(username.ToLower())
if usernameLower == "" {
return false, "Username is required"
}
if len(usernameLower) < 3 || len(usernameLower) > 20 {
return false, "Username must be between 3 and 20 characters"
}
if strings.Contains(usernameLower, " ") {
return false, "Username cannot contain spaces"
}
if !usernameAllowedRe.MatchString(usernameLower) {
return false, "Username contains invalid characters"
}
words, err := loadBannedWordsLocal()
if err == nil {
for _, banned := range words {
u := strings.ReplaceAll(usernameLower, "1", "l")
u = strings.ReplaceAll(u, "3", "e")
u = strings.ReplaceAll(u, "5", "s")
u = strings.ReplaceAll(u, "7", "t")
u = strings.ReplaceAll(u, "9", "i")
u = strings.ReplaceAll(u, "0", "o")
u = strings.ReplaceAll(u, "8", "b")
u = strings.ReplaceAll(u, "@", "a")
if strings.Contains(strings.ToLower(u), strings.ToLower(banned)) {
return false, "Username contains a banned word"
}
}
}
return true, ""
}
func ValidatePasswordHash(password string) (bool, string) {
if password == "" {
return false, "Username and password are required"
}
if len(password) != 32 {
return false, "Invalid password hash"
}
if password == "d41d8cd98f00b204e9800998ecf8427e" {
return false, "Password cannot be empty"
}
if regexp.MustCompile("^[a-fA-F0-9]{32}$").FindStringIndex(password) == nil {
return false, "Invalid password hash"
}
return true, ""
}
func IsIpInBannedList(ip string) bool {
ips := strings.SplitSeq(os.Getenv("BANNED_IPS"), ",")
for ipAddr := range ips {
ipAddr = strings.TrimSpace(ipAddr)
if ipAddr == "" {
continue
}
if strings.EqualFold(ipAddr, ip) {
return true
}
}
return false
}