|
| 1 | +import json |
| 2 | +from asyncio import to_thread |
| 3 | +from datetime import datetime, timezone |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | +from fastapi import APIRouter, HTTPException |
| 7 | +from pydantic import BaseModel, EmailStr |
| 8 | + |
| 9 | +from langflow.logging import logger |
| 10 | + |
| 11 | +router = APIRouter(tags=["Registration API"], prefix="/registration") |
| 12 | + |
| 13 | + |
| 14 | +# Data model for registration |
| 15 | +class RegisterRequest(BaseModel): |
| 16 | + email: EmailStr |
| 17 | + |
| 18 | + |
| 19 | +class RegisterResponse(BaseModel): |
| 20 | + email: str |
| 21 | + |
| 22 | + |
| 23 | +# File to store registrations |
| 24 | +REGISTRATION_FILE = Path("data/user/registration.json") |
| 25 | + |
| 26 | + |
| 27 | +def _ensure_registration_file(): |
| 28 | + """Ensure registration file and directory exist with proper permissions.""" |
| 29 | + try: |
| 30 | + # Ensure the directory exists with secure permissions |
| 31 | + REGISTRATION_FILE.parent.mkdir(parents=True, exist_ok=True) |
| 32 | + # Set directory permissions to owner read/write/execute only (if possible) |
| 33 | + REGISTRATION_FILE.parent.chmod(0o700) |
| 34 | + except Exception as e: |
| 35 | + logger.error(f"Failed to create registration file/directory: {e}") |
| 36 | + raise |
| 37 | + |
| 38 | + |
| 39 | +# TODO: Move functions to a separate service module |
| 40 | + |
| 41 | + |
| 42 | +def load_registration() -> dict | None: |
| 43 | + """Load the single registration from file.""" |
| 44 | + if not REGISTRATION_FILE.exists() or REGISTRATION_FILE.stat().st_size == 0: |
| 45 | + return None |
| 46 | + try: |
| 47 | + with REGISTRATION_FILE.open("rb") as f: # using binary mode for faster file IO |
| 48 | + content = f.read() |
| 49 | + return json.loads(content) |
| 50 | + except (json.JSONDecodeError, UnicodeDecodeError): |
| 51 | + logger.error(f"Corrupted registration file: {REGISTRATION_FILE}") |
| 52 | + return None |
| 53 | + |
| 54 | + |
| 55 | +def save_registration(email: str) -> bool: |
| 56 | + """Save the single registration to file. |
| 57 | +
|
| 58 | + Args: |
| 59 | + email: Email to register |
| 60 | +
|
| 61 | + Returns: |
| 62 | + True if saved successfully |
| 63 | + """ |
| 64 | + try: |
| 65 | + # Ensure the registration file and directory exist |
| 66 | + _ensure_registration_file() |
| 67 | + |
| 68 | + # Check if registration already exists |
| 69 | + existing = load_registration() |
| 70 | + |
| 71 | + # Create new registration (replaces any existing) |
| 72 | + registration = { |
| 73 | + "email": email, |
| 74 | + "registered_at": datetime.now(tz=timezone.utc).isoformat(), |
| 75 | + } |
| 76 | + |
| 77 | + # Log if replacing |
| 78 | + if existing: |
| 79 | + logger.info(f"Replacing registration: {existing.get('email')} -> {email}") |
| 80 | + |
| 81 | + # Save to file |
| 82 | + with REGISTRATION_FILE.open("w") as f: |
| 83 | + json.dump(registration, f, indent=2) |
| 84 | + |
| 85 | + logger.info(f"Registration saved: {email}") |
| 86 | + |
| 87 | + except Exception as e: |
| 88 | + logger.error(f"Error saving registration: {e}") |
| 89 | + raise |
| 90 | + else: |
| 91 | + return True |
| 92 | + |
| 93 | + |
| 94 | +@router.post("/", response_model=RegisterResponse) |
| 95 | +async def register_user(request: RegisterRequest): |
| 96 | + """Register the single user with email. |
| 97 | +
|
| 98 | + Note: Only one registration is allowed. |
| 99 | + """ |
| 100 | + try: |
| 101 | + email = request.email |
| 102 | + # Save to local file (replace existing) not dealing with 201 status for simplicity. |
| 103 | + if await to_thread(save_registration, email): |
| 104 | + return RegisterResponse(email=email) |
| 105 | + |
| 106 | + except HTTPException: |
| 107 | + raise |
| 108 | + except Exception as e: |
| 109 | + raise HTTPException(status_code=500, detail=f"Registration failed: {e!s}") from e |
| 110 | + |
| 111 | + |
| 112 | +@router.get("/") |
| 113 | +async def get_registration(): |
| 114 | + """Get the registered user (if any).""" |
| 115 | + try: |
| 116 | + registration = await to_thread(load_registration) |
| 117 | + if registration: |
| 118 | + return registration |
| 119 | + |
| 120 | + return {"message": "No user registered"} # noqa: TRY300 |
| 121 | + |
| 122 | + except Exception as e: |
| 123 | + raise HTTPException(status_code=500, detail=f"Failed to load registration: {e!s}") from e |
0 commit comments