Spaces:
Running
Running
| from fastapi import APIRouter, HTTPException, Query | |
| from fastapi.responses import JSONResponse | |
| from pydantic import BaseModel | |
| from services.auth_service import ( | |
| send_verification_email, | |
| verify_email_login, | |
| get_github_auth_url, | |
| handle_github_callback, | |
| get_current_user, | |
| guest_login, | |
| ) | |
| router = APIRouter(prefix="/api/auth", tags=["auth"]) | |
| class EmailSendCodeRequest(BaseModel): | |
| email: str | |
| class EmailVerifyRequest(BaseModel): | |
| email: str | |
| code: str | |
| class GuestLoginRequest(BaseModel): | |
| nickname: str = "" | |
| async def api_send_code(req: EmailSendCodeRequest): | |
| try: | |
| result = await send_verification_email(req.email) | |
| return result | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"发送验证码失败: {str(e)}") | |
| async def api_verify_email(req: EmailVerifyRequest): | |
| try: | |
| result = await verify_email_login(req.email, req.code) | |
| return result | |
| except ValueError as e: | |
| raise HTTPException(status_code=400, detail=str(e)) | |
| async def api_guest_login(req: GuestLoginRequest): | |
| try: | |
| result = await guest_login(req.nickname) | |
| return result | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def api_github_url(): | |
| url = await get_github_auth_url() | |
| return {"url": url} | |
| async def api_github_callback(code: str = Query(...)): | |
| try: | |
| result = await handle_github_callback(code) | |
| return result | |
| except ValueError as e: | |
| raise HTTPException(status_code=400, detail=str(e)) | |
| async def api_get_me(token: str = Query(None)): | |
| if not token: | |
| raise HTTPException(status_code=401, detail="缺少认证 token") | |
| try: | |
| user = await get_current_user(token) | |
| return { | |
| "user_id": user["user_id"], | |
| "email": user.get("email"), | |
| "nickname": user.get("nickname"), | |
| "avatar_url": user.get("avatar_url"), | |
| } | |
| except ValueError as e: | |
| raise HTTPException(status_code=401, detail=str(e)) | |
| async def api_logout(): | |
| return {"success": True, "message": "已退出登录"} | |