github.com/SupenBysz/gf-admin-community@v0.7.4/internal/logic/sys_captcha/sys_captcha.go (about) 1 package sys_captcha 2 3 import ( 4 "context" 5 "github.com/SupenBysz/gf-admin-community/sys_service" 6 "github.com/gogf/gf/v2/util/gconv" 7 "github.com/yitter/idgenerator-go/idgen" 8 9 "github.com/gogf/gf/v2/crypto/gmd5" 10 "github.com/gogf/gf/v2/frame/g" 11 "github.com/gogf/gf/v2/net/ghttp" 12 "github.com/gogf/gf/v2/util/gmode" 13 "github.com/mojocn/base64Captcha" 14 ) 15 16 type sCaptcha struct{} 17 18 var ( 19 captchaStore = base64Captcha.DefaultMemStore 20 captchaDriver = newDriver() 21 ) 22 23 func init() { 24 sys_service.RegisterCaptcha(New()) 25 } 26 27 // New Captcha 验证码管理服务 28 func New() *sCaptcha { 29 return &sCaptcha{} 30 } 31 32 func newDriver() *base64Captcha.DriverString { 33 driver := &base64Captcha.DriverString{ 34 Height: 44, 35 Width: 126, 36 NoiseCount: 9, 37 // ShowLineOptions: base64Captcha.OptionShowSineLine | base64Captcha.OptionShowSlimeLine | base64Captcha.OptionShowHollowLine, 38 // ShowLineOptions: base64Captcha.OptionShowSineLine, 39 Length: 4, 40 Source: "1234567890", 41 Fonts: []string{"wqy-microhei.ttc"}, 42 } 43 return driver.ConvertFonts() 44 } 45 46 // MakeCaptcha 创建验证码,直接输出验证码图片内容到HTTP Response. 47 func (s *sCaptcha) MakeCaptcha(ctx context.Context) error { 48 var ( 49 request = g.RequestFromCtx(ctx) 50 captcha = base64Captcha.NewCaptcha(captchaDriver, captchaStore) 51 ) 52 53 _, content, answer := captcha.Driver.GenerateIdQuestionAnswer() 54 item, _ := captcha.Driver.DrawCaptcha(content) 55 request.Response.Header().Add("captchaId", gconv.String(idgen.NextId())) 56 captcha.Store.Set(gmd5.MustEncryptString(answer), answer) 57 _, err := item.WriteTo(request.Response.Writer) 58 return err 59 } 60 61 // VerifyAndClear 校验验证码,并清空缓存的验证码信息 62 func (s *sCaptcha) VerifyAndClear(_ *ghttp.Request, value string) bool { 63 // 开发模式不校验验证码 64 if gmode.IsDevelop() { 65 return true 66 } 67 return captchaStore.Verify(gmd5.MustEncryptString(value), value, true) 68 }