send_code.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. fmt.Println("send_code", user, err)
  41. if err != nil {
  42. return "", err
  43. } else if user == nil {
  44. // 账号不存在
  45. logrus.Debugf("[SendCode] sendcode fail,phone:%+v", phone)
  46. return "账号不存在", errors.New("sendcode fail")
  47. }
  48. return user.Email, nil
  49. }