ticket_service.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import uuid
  2. import json
  3. from app.core.cache import redis_client
  4. class TicketService:
  5. EXPIRE_SECONDS = 60 # Tickets are short lived
  6. @staticmethod
  7. def generate_ticket(user_id: int, target_app_id: str) -> str:
  8. ticket = str(uuid.uuid4())
  9. key = f"TICKET:{ticket}"
  10. data = {
  11. "user_id": user_id,
  12. "target_app_id": target_app_id
  13. }
  14. redis_client.setex(key, TicketService.EXPIRE_SECONDS, json.dumps(data))
  15. return ticket
  16. @staticmethod
  17. def consume_ticket(ticket: str, app_id: str) -> dict:
  18. """
  19. Validates and consumes (deletes) the ticket.
  20. Returns ticket data if valid and matches app_id.
  21. """
  22. key = f"TICKET:{ticket}"
  23. data_str = redis_client.get(key)
  24. if not data_str:
  25. return None
  26. data = json.loads(data_str)
  27. # Verify it was meant for this app
  28. if data.get("target_app_id") != app_id:
  29. return None
  30. # Delete (One-time use)
  31. redis_client.delete(key)
  32. return data