answer/pkg/checker/password.go

48 lines
1.0 KiB
Go
Raw Normal View History

2022-09-27 17:59:05 +08:00
package checker
import (
"fmt"
"regexp"
"strings"
2022-09-27 17:59:05 +08:00
)
const (
levelD = iota
LevelC
LevelB
LevelA
LevelS
)
const (
PasswordCannotContainSpaces = "error.password.space_invalid"
)
// CheckPassword checks the password strength
func CheckPassword(password string) error {
if strings.Contains(password, " ") {
return fmt.Errorf(PasswordCannotContainSpaces)
2022-09-27 17:59:05 +08:00
}
// TODO Currently there is no requirement for password strength
minLevel := 0
2022-10-21 12:00:50 +08:00
// The password strength level is initialized to D.
// The regular is used to verify the password strength.
// If the matching is successful, the password strength increases by 1
level := levelD
2022-09-27 17:59:05 +08:00
patternList := []string{`[0-9]+`, `[a-z]+`, `[A-Z]+`, `[~!@#$%^&*?_-]+`}
for _, pattern := range patternList {
match, _ := regexp.MatchString(pattern, password)
2022-09-27 17:59:05 +08:00
if match {
level++
}
}
2022-10-21 12:00:50 +08:00
// If the final password strength falls below the required minimum strength, return with an error
2022-09-27 17:59:05 +08:00
if level < minLevel {
return fmt.Errorf("the password does not satisfy the current policy requirements")
2022-09-27 17:59:05 +08:00
}
return nil
}