Files
2022-02-11 11:02:29 +08:00

87 lines
1.8 KiB
Go

package handle
import (
"SciencesServer/app/service"
"SciencesServer/config"
"SciencesServer/serve/cache"
"SciencesServer/utils"
)
type ICaptcha interface {
validate() (bool, error)
}
type (
// Captcha 验证码
Captcha struct{}
// CaptchaSms 短信验证码
CaptchaSms struct {
Mobile string `json:"mobile"`
Captcha string `json:"captcha"`
}
// CaptchaImage 图形验证码
CaptchaImage struct {
Key string `json:"key"`
Captcha string `json:"captcha"`
}
)
type SmsCallback func(mobile, code string, function func() error) error
const (
// SmsCaptchaEffectiveTime 短信验证码有效时间
SmsCaptchaEffectiveTime int = 60 * 3
)
func (this *CaptchaSms) validate() (bool, error) {
code, err := cache.Cache.Get(this.Mobile)
if err != nil {
return false, err
}
if this.Captcha != code {
return false, nil
}
return true, cache.Cache.Del(this.Mobile)
}
func (this *CaptchaImage) validate() (bool, error) {
return service.Captcha(&service.CaptchaInfo{Key: this.Key, Captcha: this.Captcha}).Validate(), nil
}
// Sms 短信
func (this *Captcha) Sms(length int, mobile string, callback SmsCallback) error {
code := utils.GetRandomCode(length)
// 发送短信
//NewSms().Handle(mobile)
return callback(mobile, code, func() error {
// 存储redis
return cache.Cache.Set(mobile, code, SmsCaptchaEffectiveTime)
})
}
// Image 图形
func (this *Captcha) Image(captchaType service.CaptchaType) (*CaptchaImage, error) {
captcha, err := service.Captcha(captchaType).Create()
if err != nil {
return nil, err
}
return &CaptchaImage{Key: captcha.Key, Captcha: captcha.Captcha}, nil
}
// Validate 验证
func (this *Captcha) Validate(captcha ICaptcha) (bool, error) {
if config.IsDebug() {
return true, nil
}
return captcha.validate()
}
func NewCaptcha() *Captcha {
return &Captcha{}
}