38 lines
1006 B
Go
38 lines
1006 B
Go
package identity
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
"unicode"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
func ValidatePassword(username, password string) error {
|
|
if len([]rune(password)) < 12 {
|
|
return fmt.Errorf("密码至少需要 12 个字符")
|
|
}
|
|
var upper, lower, digit bool
|
|
for _, value := range password {
|
|
upper = upper || unicode.IsUpper(value)
|
|
lower = lower || unicode.IsLower(value)
|
|
digit = digit || unicode.IsDigit(value)
|
|
}
|
|
if !upper || !lower || !digit {
|
|
return fmt.Errorf("密码必须同时包含大写字母、小写字母和数字")
|
|
}
|
|
if username != "" && strings.Contains(strings.ToLower(password), strings.ToLower(username)) {
|
|
return fmt.Errorf("密码不能包含用户名")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func HashPassword(password string) (string, error) {
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
|
return string(hash), err
|
|
}
|
|
|
|
func VerifyPassword(hash, password string) bool {
|
|
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
|
|
}
|