|
| 1 | +import uuid |
| 2 | + |
| 3 | +from fast_captcha import img_captcha |
| 4 | +from fastapi import APIRouter, Depends |
| 5 | +from fastapi_limiter.depends import RateLimiter |
| 6 | +from starlette.concurrency import run_in_threadpool |
| 7 | + |
| 8 | +from backend.app.admin.schema.captcha import GetCaptchaDetail |
| 9 | +from backend.common.response.response_schema import ResponseSchemaModel, response_base |
| 10 | +from backend.core.conf import settings |
| 11 | +from backend.database.db import CurrentSession |
| 12 | +from backend.database.redis import redis_client |
| 13 | +from backend.utils.dynamic_config import load_login_config |
| 14 | + |
| 15 | +router = APIRouter() |
| 16 | + |
| 17 | + |
| 18 | +@router.get( |
| 19 | + '/captcha', |
| 20 | + summary='获取登录验证码', |
| 21 | + dependencies=[Depends(RateLimiter(times=5, seconds=10))], |
| 22 | +) |
| 23 | +async def get_captcha(db: CurrentSession) -> ResponseSchemaModel[GetCaptchaDetail]: |
| 24 | + await load_login_config(db) |
| 25 | + img, code = await run_in_threadpool(img_captcha, img_byte='base64') |
| 26 | + captcha_uuid = str(uuid.uuid4()) |
| 27 | + await redis_client.set( |
| 28 | + f'{settings.LOGIN_CAPTCHA_REDIS_PREFIX}:{captcha_uuid}', |
| 29 | + code, |
| 30 | + ex=settings.LOGIN_CAPTCHA_EXPIRE_SECONDS, |
| 31 | + ) |
| 32 | + data = GetCaptchaDetail( |
| 33 | + is_enabled=settings.LOGIN_CAPTCHA_ENABLED, |
| 34 | + expire_seconds=settings.LOGIN_CAPTCHA_EXPIRE_SECONDS, |
| 35 | + uuid=captcha_uuid, |
| 36 | + image=img, |
| 37 | + ) |
| 38 | + return response_base.success(data=data) |
0 commit comments