verifyCode.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. // Package service
  2. /**
  3. * @ File: verifyCode
  4. * @ Date: 2021/5/12 10:15
  5. * @ Author: JYQ
  6. * @ Description: 图片验证码相关
  7. */
  8. package service
  9. import (
  10. "encoding/json"
  11. pb "sportfitness/base/api/grpc/base"
  12. "sportfitness/base/assembly/base/repository/postgre"
  13. "sportfitness/base/assembly/base/repository/redis"
  14. "sportfitness/base/assembly/base/repository/sms"
  15. "sportfitness/base/errors"
  16. "strconv"
  17. "time"
  18. "github.com/mojocn/base64Captcha"
  19. )
  20. type VerifyCode struct {
  21. base
  22. }
  23. func (VerifyCode) GenImage(height, width int) (id, pic string) {
  24. if height == 0 {
  25. height = 80
  26. }
  27. if width == 0 {
  28. width = 240
  29. }
  30. if height < 80 || width < 80 {
  31. panic(errors.ParamError("height or width", "小于80"))
  32. }
  33. captcha := base64Captcha.NewCaptcha(
  34. base64Captcha.NewDriverDigit(
  35. height,
  36. width,
  37. 4,
  38. 0.7,
  39. 20,
  40. ),
  41. redis.CaptchaStore{})
  42. id, pic, err := captcha.Generate()
  43. if err != nil {
  44. panic(err)
  45. }
  46. return
  47. }
  48. func (v VerifyCode) GetPhoneVFCode(sId int64, account, ip, templateCode, codeId, imgCode string,
  49. verifyType pb.VerifyType, expireDuration time.Duration) string {
  50. // 校验图形验证码是否正确
  51. if !(redis.CaptchaStore{}.Verify(codeId, imgCode, true)) {
  52. panic(errors.ErrVerifyCode)
  53. }
  54. // 校验手机号是否存在 todo 调用手机号校验接口
  55. // 根据sId查询短信签名 todo 以后会存在数据库中,目前只是写在代码层
  56. signName, _ := postgre.PGVerifyCode{}.GetShopSmsConf(sId)
  57. code := strconv.Itoa(RandomInt(6))
  58. now := time.Now()
  59. vf := &postgre.VCode{
  60. SId: sId,
  61. Account: account,
  62. SendType: postgre.VFCodeTypePhone,
  63. CodeType: verifyType,
  64. Code: code,
  65. Ip: ip,
  66. CreateAt: now.Unix(),
  67. ExpireAt: now.Add(expireDuration).Unix(),
  68. }
  69. str, err := json.Marshal(vf)
  70. if err != nil {
  71. panic(errors.M2JError)
  72. }
  73. rs, err := postgre.PGVerifyCode{}.CreateVerifyCode(string(str), sId)
  74. if err != nil {
  75. panic(errors.PGError)
  76. }
  77. sms.PhoneCode{}.SendCode(vf, templateCode, signName)
  78. return rs
  79. }
  80. func (v VerifyCode) CheckPhoneVFCode(sId int64, account, code string, verifyType pb.VerifyType) bool {
  81. vf := &postgre.VCode{
  82. SId: sId,
  83. Account: account,
  84. SendType: postgre.VFCodeTypePhone,
  85. CodeType: verifyType,
  86. Code: code,
  87. }
  88. str, err := json.Marshal(vf)
  89. if err != nil {
  90. panic(errors.M2JError)
  91. }
  92. b, err := postgre.PGVerifyCode{}.CheckPhoneVerifyCode(string(str), sId)
  93. if err != nil {
  94. panic(errors.PGError)
  95. }
  96. return b
  97. }