base.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package system
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/mojocn/base64Captcha"
  5. "github.com/sirupsen/logrus"
  6. "go.uber.org/zap"
  7. "lc-fangdaosha/global"
  8. "lc-fangdaosha/model/common/response"
  9. systemResp "lc-fangdaosha/model/system/response"
  10. "time"
  11. )
  12. // 当开启多服务器部署时,替换下面的配置,使用redis共享存储验证码
  13. // var store = captcha.NewDefaultRedisStore()
  14. var store = base64Captcha.DefaultMemStore
  15. type BaseApi struct{}
  16. // Captcha
  17. // @Tags Base
  18. // @Summary 生成验证码
  19. // @Security ApiKeyAuth
  20. // @accept application/json
  21. // @Produce application/json
  22. // @Success 200 {object} response.Response{data=systemResp.SysCaptchaResponse,msg=string} "生成验证码,返回包括随机数id,base64,验证码长度,是否开启验证码"
  23. // @Router /base/captcha [get]
  24. func (b *BaseApi) Captcha(c *gin.Context) {
  25. // 判断验证码是否开启
  26. openCaptcha := global.Config.Captcha.OpenCaptcha
  27. openCaptchaTimeOut := global.Config.Captcha.OpenCaptchaTimeOut // 缓存超时时间
  28. key := c.ClientIP()
  29. v, ok := global.BlackCache.Get(key)
  30. if !ok {
  31. global.BlackCache.Set(key, 1, time.Second*time.Duration(openCaptchaTimeOut))
  32. }
  33. var oc bool
  34. if openCaptcha == 0 || openCaptcha < interfaceToInt(v) {
  35. oc = true
  36. }
  37. // 字符,公式,验证码配置
  38. // 生成默认数字的driver
  39. driver := base64Captcha.NewDriverDigit(global.Config.Captcha.ImgHeight, global.Config.Captcha.ImgWidth, global.Config.Captcha.KeyLong, 0.7, 80)
  40. // cp := base64Captcha.NewCaptcha(driver, store.UseWithCtx(c)) // v8下使用redis
  41. cp := base64Captcha.NewCaptcha(driver, store)
  42. id, b64s, err := cp.Generate()
  43. if err != nil {
  44. logrus.Error("验证码获取失败!", zap.Error(err))
  45. response.FailWithMessage("验证码获取失败", c)
  46. return
  47. }
  48. response.OkWithDetailed(systemResp.SysCaptchaResponse{
  49. CaptchaId: id,
  50. PicPath: b64s,
  51. CaptchaLength: global.Config.Captcha.KeyLong,
  52. OpenCaptcha: oc,
  53. }, "验证码获取成功", c)
  54. }
  55. // 类型转换
  56. func interfaceToInt(v interface{}) (i int) {
  57. switch v := v.(type) {
  58. case int:
  59. i = v
  60. default:
  61. i = 0
  62. }
  63. return
  64. }