send_code.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package service
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "math/rand"
  7. "time"
  8. "youngee_b_api/consts"
  9. "youngee_b_api/db"
  10. "youngee_b_api/model/system_model"
  11. "youngee_b_api/redis"
  12. "github.com/sirupsen/logrus"
  13. )
  14. var SendCode *sendCode
  15. func SendCodeInit(config *system_model.Session) {
  16. sendCode := new(sendCode)
  17. sendCode.sessionTTL = time.Duration(config.TTL) * time.Minute
  18. SendCode = sendCode
  19. }
  20. type sendCode struct {
  21. sessionTTL time.Duration
  22. }
  23. func (s *sendCode) GetCode(ctx context.Context) string {
  24. rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
  25. vcode := fmt.Sprintf("%06v", rnd.Int31n(1000000))
  26. return vcode
  27. }
  28. func (s *sendCode) SetSession(ctx context.Context, phone string, vcode string) error {
  29. err := redis.Set(ctx, s.getRedisKey(phone), vcode, s.sessionTTL)
  30. if err != nil {
  31. return err
  32. }
  33. return nil
  34. }
  35. func (s *sendCode) getRedisKey(key string) string {
  36. return fmt.Sprintf("%s%s", consts.SessionRedisPrefix, key)
  37. }
  38. func (s *sendCode) GetEmailByPhone(ctx context.Context, phone string) (string, error) {
  39. user, err := db.GetUserByPhone(ctx, phone)
  40. if err != nil {
  41. return "", err
  42. } else if user == nil {
  43. // 账号不存在
  44. logrus.Debugf("[SendCode] sendcode fail,phone:%+v", phone)
  45. return "账号不存在", errors.New("sendcode fail")
  46. }
  47. return user.Email, nil
  48. }