| 1234567891011121314151617181920212223242526272829303132333435363738394041 |
- import uuid
- import json
- from app.core.cache import redis_client
- class TicketService:
- EXPIRE_SECONDS = 60 # Tickets are short lived
- @staticmethod
- def generate_ticket(user_id: int, target_app_id: str) -> str:
- ticket = str(uuid.uuid4())
- key = f"TICKET:{ticket}"
- data = {
- "user_id": user_id,
- "target_app_id": target_app_id
- }
- redis_client.setex(key, TicketService.EXPIRE_SECONDS, json.dumps(data))
- return ticket
- @staticmethod
- def consume_ticket(ticket: str, app_id: str) -> dict:
- """
- Validates and consumes (deletes) the ticket.
- Returns ticket data if valid and matches app_id.
- """
- key = f"TICKET:{ticket}"
- data_str = redis_client.get(key)
-
- if not data_str:
- return None
-
- data = json.loads(data_str)
-
- # Verify it was meant for this app
- if data.get("target_app_id") != app_id:
- return None
-
- # Delete (One-time use)
- redis_client.delete(key)
-
- return data
|