kra-oa/internal/biz/security.go

77 lines
2.0 KiB
Go

package biz
import (
"context"
"errors"
)
type SecurityConfig struct {
ID uint
CaptchaOpen int
CaptchaTimeout int
KeyLong int
ImgWidth int
ImgHeight int
PwdMinLength int
PwdRequireUpper bool
PwdRequireLower bool
PwdRequireDigit bool
PwdRequireSpecial bool
LimitEnable bool
LimitWindow int
LimitCount int
LockEnable bool
LockThreshold int
LockDuration int
PwdExpireEnable bool
PwdExpireDays int
ForceNewUserChangePassword bool
}
type SecurityRepo interface {
SecurityConfig(context.Context) (*SecurityConfig, error)
SaveSecurityConfig(context.Context, *SecurityConfig) error
}
type SecurityUsecase struct{ SecurityRepo }
func NewSecurityUsecase(repo SecurityRepo) *SecurityUsecase {
return &SecurityUsecase{SecurityRepo: repo}
}
func (uc *SecurityUsecase) UpdateSecurity(ctx context.Context, value *SecurityConfig) error {
return uc.SaveSecurityConfig(ctx, value)
}
func (uc *SecurityUsecase) ValidatePassword(value *SecurityConfig, password string) error {
if len([]rune(password)) < value.PwdMinLength {
return errors.New("密码长度不足")
}
hasUpper, hasLower, hasDigit, hasSpecial := false, false, false, false
for _, ch := range password {
switch {
case ch >= 'A' && ch <= 'Z':
hasUpper = true
case ch >= 'a' && ch <= 'z':
hasLower = true
case ch >= '0' && ch <= '9':
hasDigit = true
default:
hasSpecial = true
}
}
if value.PwdRequireUpper && !hasUpper {
return errors.New("密码必须包含大写字母")
}
if value.PwdRequireLower && !hasLower {
return errors.New("密码必须包含小写字母")
}
if value.PwdRequireDigit && !hasDigit {
return errors.New("密码必须包含数字")
}
if value.PwdRequireSpecial && !hasSpecial {
return errors.New("密码必须包含特殊字符")
}
return nil
}