sms_service.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import random
  2. import string
  3. from app.core.cache import redis_client
  4. class SmsService:
  5. @staticmethod
  6. def send_code(mobile: str) -> str:
  7. """
  8. Generates and 'sends' a 6-digit code.
  9. Returns the code for dev/mock purposes (or logs it).
  10. """
  11. code = ''.join(random.choices(string.digits, k=6))
  12. # Store in Redis: SMS:{mobile} -> code
  13. key = f"SMS:{mobile}"
  14. # Expire in 5 minutes
  15. redis_client.setex(key, 300, code)
  16. # In production, call actual SMS provider here.
  17. print(f"=======================================")
  18. print(f" [MOCK SMS] To: {mobile}, Code: {code}")
  19. print(f"=======================================")
  20. return code
  21. @staticmethod
  22. def verify_code(mobile: str, code: str) -> bool:
  23. key = f"SMS:{mobile}"
  24. stored_code = redis_client.get(key)
  25. if not stored_code:
  26. return False
  27. if stored_code == code:
  28. redis_client.delete(key) # One-time use
  29. return True
  30. return False