first init
This commit is contained in:
72
core/routers/auth/routes.py
Normal file
72
core/routers/auth/routes.py
Normal file
@@ -0,0 +1,72 @@
|
||||
# -*- coding = utf-8 -*-
|
||||
# @Time : 2025/2/13 下午5:02
|
||||
# @File : routes.py
|
||||
# @Software : PyCharm
|
||||
# @Author : xingc
|
||||
# @Desc :
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
import redis.asyncio as aioredis
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from . import schema
|
||||
from config import settings
|
||||
from core.db.engine import get_async_session, get_cache
|
||||
from core.db.models import User
|
||||
from core.db.crud import CRUD
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
auth_router = APIRouter(prefix='/auth', tags=['认证模块'])
|
||||
|
||||
|
||||
async def get_wechat_session(code: str):
|
||||
url = "https://api.weixin.qq.com/sns/jscode2session"
|
||||
params = {
|
||||
"appid": settings.APPID,
|
||||
"secret": settings.APPSECRET,
|
||||
"js_code": code,
|
||||
"grant_type": "authorization_code",
|
||||
}
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.get(url, params=params)
|
||||
if response.status_code != 200:
|
||||
raise HTTPException(status_code=400, detail="Failed to fetch session from WeChat")
|
||||
data = response.json()
|
||||
if "errcode" in data:
|
||||
logger.warning(f"WeChat session error: {data['errcode']}")
|
||||
raise HTTPException(status_code=400, detail=data["errmsg"])
|
||||
|
||||
return data
|
||||
|
||||
|
||||
@auth_router.post('/wechat_login')
|
||||
async def wechat_login(
|
||||
payload: schema.WechatLoginIn,
|
||||
db_session: AsyncSession = Depends(get_async_session),
|
||||
redis_conn: aioredis.Redis = Depends(get_cache)
|
||||
):
|
||||
# 获取微信 session
|
||||
wechat_session = await get_wechat_session(payload.code)
|
||||
logger.info(f"WeChat session: {wechat_session}")
|
||||
openid = wechat_session.get("openid")
|
||||
|
||||
if openid:
|
||||
raise HTTPException(status_code=400, detail="Invalid WeChat session")
|
||||
|
||||
db_crud = CRUD(db_session, User)
|
||||
user = await db_crud.get(filters={'openid': openid})
|
||||
if user is None:
|
||||
# 新用户注册
|
||||
if not payload.encrypted_data or not payload.iv:
|
||||
raise HTTPException(400, detail="需要用户授权信息")
|
||||
# user = await db_crud.create(
|
||||
# data={
|
||||
# 'wechat_openid': openid,
|
||||
# 'wechat_union_id': union_id,
|
||||
# },
|
||||
# filters={'union_id': union_id}
|
||||
# )
|
||||
|
||||
return {'data': {'openid': openid}}
|
||||
Reference in New Issue
Block a user