first init

This commit is contained in:
xingc
2025-02-18 14:26:47 +08:00
commit 48a02974fc
41 changed files with 2297 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
# -*- coding = utf-8 -*-
# @Time : 2025/2/13 下午3:48
# @File : __init__.py.py
# @Software : PyCharm
# @Author : xingc
# @Desc :

View 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}}

View File

@@ -0,0 +1,16 @@
# -*- coding = utf-8 -*-
# @Time : 2025/2/17 下午2:30
# @File : schema.py
# @Software : PyCharm
# @Author : xingc
# @Desc :
from typing import Optional
from pydantic import BaseModel, constr
class WechatLoginIn(BaseModel):
code: str
phone: Optional[constr(pattern='^1[0-9]{10}$')] = None
encrypted_data: Optional[str] = None
iv: Optional[str] = None

View File

@@ -0,0 +1,9 @@
# -*- coding = utf-8 -*-
# @Time : 2025/2/17 下午8:14
# @File : services.py
# @Software : PyCharm
# @Author : xingc
# @Desc :
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")