-
Notifications
You must be signed in to change notification settings - Fork 40
/
validate.go
66 lines (58 loc) · 1.56 KB
/
validate.go
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
package passwordvalidator
import (
"errors"
"fmt"
"strings"
)
// Validate returns nil if the password has greater than or
// equal to the minimum entropy. If not, an error is returned
// that explains how the password can be strengthened. This error
// is safe to show the client
func Validate(password string, minEntropy float64) error {
entropy := getEntropy(password)
if entropy >= minEntropy {
return nil
}
hasReplace := false
hasSep := false
hasOtherSpecial := false
hasLower := false
hasUpper := false
hasDigits := false
for _, c := range password {
switch {
case strings.ContainsRune(replaceChars, c):
hasReplace = true
case strings.ContainsRune(sepChars, c):
hasSep = true
case strings.ContainsRune(otherSpecialChars, c):
hasOtherSpecial = true
case strings.ContainsRune(lowerChars, c):
hasLower = true
case strings.ContainsRune(upperChars, c):
hasUpper = true
case strings.ContainsRune(digitsChars, c):
hasDigits = true
}
}
allMessages := []string{}
if !hasOtherSpecial || !hasSep || !hasReplace {
allMessages = append(allMessages, "including more special characters")
}
if !hasLower {
allMessages = append(allMessages, "using lowercase letters")
}
if !hasUpper {
allMessages = append(allMessages, "using uppercase letters")
}
if !hasDigits {
allMessages = append(allMessages, "using numbers")
}
if len(allMessages) > 0 {
return fmt.Errorf(
"insecure password, try %v or using a longer password",
strings.Join(allMessages, ", "),
)
}
return errors.New("insecure password, try using a longer password")
}