|
| 1 | +from fastapi import APIRouter, Query, HTTPException |
| 2 | +from pydantic import BaseModel, Field |
| 3 | +import random |
| 4 | +import string |
| 5 | + |
| 6 | +router = APIRouter(prefix="/tools/password", tags=["Password Tools"]) |
| 7 | + |
| 8 | +# Response model for password generation |
| 9 | +class PasswordResponse(BaseModel): |
| 10 | + password: str = Field( |
| 11 | + example="a9B!7xTq@1l#", |
| 12 | + description="A randomly generated password" |
| 13 | + ) |
| 14 | + |
| 15 | +@router.get( |
| 16 | + "/generate", |
| 17 | + response_model=PasswordResponse, |
| 18 | + summary="Generate a secure random password", |
| 19 | + response_description="Returns a randomly generated password based on query parameters" |
| 20 | +) |
| 21 | +def generate_password( |
| 22 | + length: int = Query(12, ge=4, le=128, description="Length of the password"), |
| 23 | + include_symbols: bool = Query(True, description="Include special characters"), |
| 24 | + include_numbers: bool = Query(True, description="Include digits"), |
| 25 | + include_uppercase: bool = Query(True, description="Include uppercase letters"), |
| 26 | + include_lowercase: bool = Query(True, description="Include lowercase letters") |
| 27 | +): |
| 28 | + """ |
| 29 | + Generate a secure, random password. |
| 30 | +
|
| 31 | + You can customize: |
| 32 | + - Length |
| 33 | + - Whether to include symbols, numbers, uppercase, and lowercase characters |
| 34 | +
|
| 35 | + Returns: |
| 36 | + A JSON object containing the generated password. |
| 37 | + """ |
| 38 | + character_pool = "" |
| 39 | + |
| 40 | + if include_lowercase: |
| 41 | + character_pool += string.ascii_lowercase |
| 42 | + if include_uppercase: |
| 43 | + character_pool += string.ascii_uppercase |
| 44 | + if include_numbers: |
| 45 | + character_pool += string.digits |
| 46 | + if include_symbols: |
| 47 | + character_pool += string.punctuation |
| 48 | + |
| 49 | + if not character_pool: |
| 50 | + raise HTTPException( |
| 51 | + status_code=400, |
| 52 | + detail="At least one character set must be selected." |
| 53 | + ) |
| 54 | + |
| 55 | + password = ''.join(random.choices(character_pool, k=length)) |
| 56 | + return {"password": password} |
| 57 | + |
0 commit comments