answer/pkg/checker/password.go

48 lines
1.3 KiB
Go
Raw Normal View History

2022-09-27 17:59:05 +08:00
package checker
import (
"fmt"
"regexp"
)
const (
levelD = iota
LevelC
LevelB
LevelA
LevelS
)
2022-10-22 18:40:12 +08:00
// CheckPassword
// minLength: Specifies the minimum length of a password
// maxLengthSpecifies the maximum length of a password
// minLevelSpecifies the minimum strength level required for passwords
// pwdText passwords
func CheckPassword(minLength, maxLength, minLevel int, pwd string) error {
2022-10-21 12:00:50 +08:00
// First check whether the password length is within the range
2022-09-27 17:59:05 +08:00
if len(pwd) < minLength {
return fmt.Errorf("BAD PASSWORD: The password is shorter than %d characters", minLength)
}
if len(pwd) > maxLength {
return fmt.Errorf("BAD PASSWORD: The password is logner than %d characters", maxLength)
}
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
2022-09-27 17:59:05 +08:00
var level int = levelD
patternList := []string{`[0-9]+`, `[a-z]+`, `[A-Z]+`, `[~!@#$%^&*?_-]+`}
for _, pattern := range patternList {
match, _ := regexp.MatchString(pattern, pwd)
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. ")
}
return nil
}