Files
ArmedPolice/app/service/captcha.go

107 lines
2.4 KiB
Go
Raw Normal View History

2021-11-02 09:43:19 +08:00
package service
import (
"errors"
"github.com/mojocn/base64Captcha"
)
type Param struct {
obj interface{}
}
type CaptchaInfo struct {
Key string `json:"key"`
Captcha string `json:"captcha"`
}
type CaptchaType string
const (
CaptchaTypeForDefault CaptchaType = "default"
CaptchaTypeForAudio CaptchaType = "audio"
CaptchaTypeForString CaptchaType = "string"
CaptchaTypeForMath CaptchaType = "math"
CaptchaTypeForChinese CaptchaType = "chinese"
)
var drivers = map[CaptchaType]func() base64Captcha.Driver{
CaptchaTypeForDefault: captchaForDigit,
CaptchaTypeForAudio: captchaForAudio,
CaptchaTypeForString: captchaForString,
CaptchaTypeForMath: captchaForMath,
CaptchaTypeForChinese: captchaForChinese,
}
var store = base64Captcha.DefaultMemStore
func captchaForDigit() base64Captcha.Driver {
drive := new(base64Captcha.DriverDigit)
drive.Width = 100
drive.Height = 40
drive.DotCount = 80
drive.Length = 6
drive.MaxSkew = 0.7
return drive
}
func captchaForAudio() base64Captcha.Driver {
drive := new(base64Captcha.DriverAudio)
drive.Language = "zh"
drive.Length = 4
return drive
}
func captchaForString() base64Captcha.Driver {
drive := new(base64Captcha.DriverString)
drive.Width = 100
drive.Width = 40
drive.Source = "设想,你在,处理,消费者,的音,频输,出音,频可,能无,论什,么都,没有,任何,输出,或者,它可,能是,单声道,立体声,或是,环绕立,体声的,不想要,的值"
drive.Length = 2
return drive.ConvertFonts()
}
func captchaForMath() base64Captcha.Driver {
drive := new(base64Captcha.DriverMath)
drive.Width = 100
drive.Height = 40
drive.NoiseCount = 1
return drive.ConvertFonts()
}
func captchaForChinese() base64Captcha.Driver {
drive := new(base64Captcha.DriverChinese)
drive.Width = 100
drive.Width = 40
drive.Source = "1234567890qwertyuioplkjhgfdsazxcvbnm"
drive.Length = 4
return drive.ConvertFonts()
}
func (this *Param) Create() (*CaptchaInfo, error) {
obj := this.obj.(CaptchaType)
drive, has := drivers[obj]
if !has {
return nil, errors.New("参数异常")
}
c := base64Captcha.NewCaptcha(drive(), store)
key, captcha, err := c.Generate()
if err != nil {
return nil, err
}
return &CaptchaInfo{Key: key, Captcha: captcha}, nil
}
func (this *Param) Validate() bool {
obj := this.obj.(*CaptchaInfo)
return store.Verify(obj.Key, obj.Captcha, true)
}
func Captcha(obj interface{}) *Param {
return &Param{obj: obj}
}