verifycode.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package verifycode
  2. import (
  3. "strings"
  4. "sync"
  5. "github.com/runningwater/gohub/pkg/app"
  6. "github.com/runningwater/gohub/pkg/config"
  7. "github.com/runningwater/gohub/pkg/helpers"
  8. "github.com/runningwater/gohub/pkg/logger"
  9. "github.com/runningwater/gohub/pkg/sms"
  10. )
  11. type VerifyCode struct {
  12. Store Store
  13. }
  14. var once sync.Once
  15. var internalVerifyCode *VerifyCode
  16. func NewVerifyCode() *VerifyCode {
  17. once.Do(func() {
  18. internalVerifyCode = &VerifyCode{
  19. Store: NewRedisStore(),
  20. }
  21. })
  22. return internalVerifyCode
  23. }
  24. // SendSMS 发送验证码
  25. // 发送验证码到手机, 调用示例
  26. //
  27. // verifycode.NewVerifyCode().SendSMS(request.Phone)
  28. func (v *VerifyCode) SendSMS(phone string) bool {
  29. // 生成验证码
  30. code := v.generateVerifyCode(phone)
  31. // 方便本地和 测试环境调试
  32. if !app.IsProduction() &&
  33. strings.HasPrefix(phone, config.GetString("verifycode.debug_phone_prefix")) {
  34. // 测试环境,直接返回成功
  35. return true
  36. }
  37. // 发送验证码
  38. return sms.NewSMS().Send(phone, sms.Message{
  39. Template: config.GetString("sms.aliyun.template_code"),
  40. Data: map[string]string{"code": code},
  41. })
  42. }
  43. // CheckAnswer 检查验证码是否正确
  44. // key: 手机号 或 Email
  45. func (v *VerifyCode) CheckAnswer(key, answer string) bool {
  46. logger.DebugJSON("验证码", "检查验证码是否正确", map[string]string{key: answer})
  47. // 方便本地和 测试环境调试
  48. if !app.IsProduction() &&
  49. (strings.HasPrefix(key, config.GetString("verifycode.debug_phone_prefix")) || strings.HasPrefix(key, config.GetString("verifycode.debug_email_prefix"))) {
  50. return true
  51. }
  52. return v.Store.Verify(key, answer, false)
  53. }
  54. // 生成验证码, 并放置于 Redis 中
  55. func (v *VerifyCode) generateVerifyCode(key string) string {
  56. // 生成随机码
  57. code := helpers.RandomNumber(config.GetInt("verifycode.code_length"))
  58. if app.IsLocal() {
  59. code = config.GetString("verifycode.debug_code")
  60. }
  61. logger.DebugJSON("验证码", "生成验证码", map[string]string{key: code})
  62. // 存储验证码到 Redis
  63. v.Store.Set(key, code)
  64. return code
  65. }