api/app/api/v1/auth.py
2025-04-09 10:49:02 +08:00

57 lines
1.8 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.schemas.auth import WechatLogin, LoginResponse
from app.schemas.user import UserCreate
from app.services import wechat as wechat_service
from app.services import user as user_service
from app.core.security import create_access_token
from app.db.database import get_db
router = APIRouter()
@router.post("/login/wechat", response_model=LoginResponse, tags=["auth"])
async def wechat_login(
login_data: WechatLogin,
db: AsyncSession = Depends(get_db)
):
"""
微信登录接口
- 使用微信临时登录凭证(code)获取openid和unionid
- 如果用户不存在,则创建新用户
- 生成JWT令牌
"""
try:
# 调用微信API获取openid和unionid
openid, unionid = await wechat_service.code2session(login_data.code)
# 检查用户是否存在
existing_user = await user_service.get_user_by_openid(db, openid=openid)
is_new_user = existing_user is None
if is_new_user:
# 创建新用户
user_create = UserCreate(
openid=openid,
unionid=unionid
)
user = await user_service.create_user(db, user=user_create)
else:
user = existing_user
# 创建访问令牌 - 使用openid作为标识
access_token = create_access_token(subject=openid)
# 返回登录响应
return LoginResponse(
access_token=access_token,
is_new_user=is_new_user,
openid=openid
)
except wechat_service.WechatLoginError as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=str(e)
)