40 lines
1.3 KiB
Python
40 lines
1.3 KiB
Python
|
|
from datetime import timedelta
|
||
|
|
|
||
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||
|
|
|
||
|
|
from app.config import settings
|
||
|
|
from app.schemas.auth import WxLoginRequest
|
||
|
|
from app.services.user_service import get_or_create_wechat_user
|
||
|
|
from app.utils.security import create_access_token
|
||
|
|
from app.utils.wx_api import code2session
|
||
|
|
|
||
|
|
|
||
|
|
async def login_with_wechat(session: AsyncSession, payload: WxLoginRequest) -> dict:
|
||
|
|
wx_data = await code2session(payload.code)
|
||
|
|
openid = wx_data.get("openid")
|
||
|
|
if not openid:
|
||
|
|
raise ValueError(wx_data.get("errmsg") or "微信登录失败")
|
||
|
|
|
||
|
|
user, is_new_user = await get_or_create_wechat_user(
|
||
|
|
session,
|
||
|
|
openid=openid,
|
||
|
|
unionid=wx_data.get("unionid"),
|
||
|
|
subscribe_audit=payload.subscribe_audit,
|
||
|
|
subscribe_match=payload.subscribe_match,
|
||
|
|
)
|
||
|
|
|
||
|
|
access_token = create_access_token({"user_id": user.id, "token_type": "access"})
|
||
|
|
refresh_token = create_access_token(
|
||
|
|
{"user_id": user.id, "token_type": "refresh"},
|
||
|
|
expires_delta=timedelta(days=30),
|
||
|
|
)
|
||
|
|
return {
|
||
|
|
"access_token": access_token,
|
||
|
|
"refresh_token": refresh_token,
|
||
|
|
"token_type": "bearer",
|
||
|
|
"expires_in": settings.jwt_access_token_expire_minutes * 60,
|
||
|
|
"user_id": user.id,
|
||
|
|
"audit_status": user.audit_status,
|
||
|
|
"is_new_user": is_new_user,
|
||
|
|
}
|