feat:完善项目
This commit is contained in:
87
app/handle/captcha.go
Normal file
87
app/handle/captcha.go
Normal file
@ -0,0 +1,87 @@
|
||||
package handle
|
||||
|
||||
import (
|
||||
"ArmedPolice/app/service"
|
||||
"ArmedPolice/config"
|
||||
"ArmedPolice/serve/cache"
|
||||
"ArmedPolice/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(content string) error
|
||||
|
||||
const (
|
||||
// SmsCaptchaEffectiveTime 短信验证码有效时间
|
||||
SmsCaptchaEffectiveTime int = 3600 * 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)
|
||||
// 存储redis
|
||||
if err := cache.Cache.Set(mobile, code, SmsCaptchaEffectiveTime); err != nil {
|
||||
return err
|
||||
}
|
||||
// 发送短信
|
||||
//NewSms().Handle(mobile)
|
||||
return callback(mobile)
|
||||
}
|
||||
|
||||
// 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{}
|
||||
}
|
Reference in New Issue
Block a user