新增用户授权功能
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import random
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import httpx
|
||||
from sqlalchemy import select, func
|
||||
@@ -7,6 +7,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.config import settings
|
||||
from app.models.user_oauth import UserOAuth
|
||||
from app.models.user_oauth_app import UserOAuthApp
|
||||
from app.utils.id_gen import generate_id
|
||||
|
||||
|
||||
@@ -23,35 +24,45 @@ OAUTH_TYPE_CONFIG = {
|
||||
10: {"port_type": 5, "name": "腾讯营销K3", "app_type": "tencent"},
|
||||
}
|
||||
|
||||
|
||||
async def get_available_app(app_type: str, db: AsyncSession) -> dict:
|
||||
if app_type == "juliang_ad":
|
||||
apps = settings.JULIANG_AD_APPS
|
||||
elif app_type == "juliang_qianchuan":
|
||||
apps = settings.JULIANG_QIANCHUAN_APPS
|
||||
elif app_type == "kuaishou":
|
||||
apps = settings.KUAISHOU_APPS
|
||||
elif app_type == "tencent":
|
||||
apps = settings.TENCENT_APPS
|
||||
else:
|
||||
raise ValueError(f"不支持的应用类型: {app_type}")
|
||||
#随机获取一个可用的应用配置
|
||||
async def get_available_app(open_type: int, db: AsyncSession) -> dict:
|
||||
# 从 user_oauth_app 表查询可用应用
|
||||
# 过滤条件:open_type 匹配、status=1(正常)、deleted_at is None
|
||||
result = await db.execute(
|
||||
select(UserOAuthApp).where(
|
||||
UserOAuthApp.open_type == open_type,
|
||||
UserOAuthApp.status == 1,
|
||||
UserOAuthApp.deleted_at.is_(None),
|
||||
)
|
||||
)
|
||||
apps = result.scalars().all()
|
||||
|
||||
if not apps:
|
||||
raise ValueError(f"{app_type}未配置应用")
|
||||
raise ValueError("没有找到可用的应用配置")
|
||||
|
||||
available_apps = []
|
||||
for app in apps:
|
||||
app_id = app.get("app_id")
|
||||
if not app_id:
|
||||
continue
|
||||
|
||||
result = await db.execute(
|
||||
select(func.count(UserOAuth.id)).where(UserOAuth.appid == app_id)
|
||||
app_id = app.app_id
|
||||
|
||||
# 查询该应用当前授权数量
|
||||
count_result = await db.execute(
|
||||
select(func.count(UserOAuth.id)).where(
|
||||
UserOAuth.appid == app_id,
|
||||
UserOAuth.deleted_at.is_(None),
|
||||
)
|
||||
)
|
||||
count = result.scalar() or 0
|
||||
count = count_result.scalar() or 0
|
||||
|
||||
if count < 5000:
|
||||
available_apps.append(app)
|
||||
# 检查是否达到最大授权数
|
||||
max_users = app.count
|
||||
if count < max_users:
|
||||
available_apps.append({
|
||||
"app_id": app.app_id,
|
||||
"secret": app.secret,
|
||||
"open_type": app.open_type,
|
||||
"auth_url": app.auth_url,
|
||||
"company": app.company,
|
||||
})
|
||||
|
||||
if not available_apps:
|
||||
raise ValueError("所有应用授权已超过最大数量")
|
||||
@@ -59,175 +70,89 @@ async def get_available_app(app_type: str, db: AsyncSession) -> dict:
|
||||
return random.choice(available_apps)
|
||||
|
||||
|
||||
async def build_oauth_url(oauth_type: int, user_id: str) -> str:
|
||||
if oauth_type == 1:
|
||||
return await _build_juliang_oauth_url(oauth_type, user_id, app_type)
|
||||
elif oauth_type == 2:
|
||||
return await _build_kuaishou_oauth_url(oauth_type, user_id)
|
||||
elif oauth_type == 3:
|
||||
return await _build_tencent_oauth_url(oauth_type, user_id)
|
||||
elif oauth_type == 4:
|
||||
return await _build_tencent_oauth_url(oauth_type, user_id)
|
||||
async def build_oauth_url(open_type: int, user_id: str, db: AsyncSession) -> str:
|
||||
if open_type == 1:
|
||||
#千川
|
||||
return await _build_jl_oauth_url(open_type, user_id, db)
|
||||
elif open_type == 2:
|
||||
#广告
|
||||
return await _build_jl_oauth_url(open_type, user_id, db)
|
||||
elif open_type == 5:
|
||||
#快手代理商
|
||||
return "无配置"
|
||||
elif open_type == 9:
|
||||
#腾讯营销K2
|
||||
return "无配置"
|
||||
elif open_type == 10:
|
||||
#腾讯营销K3
|
||||
return "无配置"
|
||||
else:
|
||||
raise ValueError(f"不支持的应用类型: {app_type}")
|
||||
|
||||
|
||||
async def _build_juliang_oauth_url(oauth_type: int, user_id: str, app_type: str) -> str:
|
||||
async with AsyncSession() as db:
|
||||
app = await get_available_app(app_type, db)
|
||||
app_id = app.get("app_id")
|
||||
|
||||
redirect_uri = "https://open.oceanengine.com/audit/oauth.html"
|
||||
rid = "ktm0cl7napb"
|
||||
if oauth_type == 1:
|
||||
redirect_uri = "https://qianchuan.jinritemai.com/openapi/qc/audit/oauth.html"
|
||||
rid = "vr7kclvmvs9"
|
||||
|
||||
#千川授权链接构建
|
||||
async def _build_jl_oauth_url(open_type: int, user_id: str, db: AsyncSession) -> str:
|
||||
app = await get_available_app(open_type, db)
|
||||
app_id = app.get("app_id")
|
||||
auth_url = app.get("auth_url")
|
||||
if not auth_url:
|
||||
raise ValueError("应用授权链接不能为空")
|
||||
params = {
|
||||
"app_id": app_id,
|
||||
"state": f"{oauth_type}:{user_id}:{app_id}:{app_type}",
|
||||
"material_auth": 1,
|
||||
"rid": rid,
|
||||
"state": f"{user_id}:{app_id}",
|
||||
}
|
||||
query_string = "&".join(f"{k}={v}" for k, v in params.items())
|
||||
return f"{redirect_uri}?{query_string}"
|
||||
return f"{auth_url}&{query_string}"
|
||||
|
||||
|
||||
async def _build_kuaishou_oauth_url(oauth_type: int, user_id: str) -> str:
|
||||
async with AsyncSession() as db:
|
||||
app = await get_available_app("kuaishou", db)
|
||||
app_id = app.get("app_id")
|
||||
|
||||
redirect_uri = f"{settings.BASE_URL}/api/user-oauth/callback"
|
||||
params = {
|
||||
"app_id": app_id,
|
||||
"redirect_uri": redirect_uri,
|
||||
"response_type": "code",
|
||||
"scope": "basic",
|
||||
"state": f"{oauth_type}:{user_id}:{app_id}:kuaishou",
|
||||
}
|
||||
query_string = "&".join(f"{k}={v}" for k, v in params.items())
|
||||
return f"https://open.kuaishou.com/oauth2/authorize?{query_string}"
|
||||
|
||||
|
||||
async def _build_tencent_oauth_url(oauth_type: int, user_id: str) -> str:
|
||||
async with AsyncSession() as db:
|
||||
app = await get_available_app("tencent", db)
|
||||
app_id = app.get("app_id")
|
||||
|
||||
redirect_uri = f"{settings.BASE_URL}/api/user-oauth/callback"
|
||||
params = {
|
||||
"app_id": app_id,
|
||||
"redirect_uri": redirect_uri,
|
||||
"response_type": "code",
|
||||
"scope": "get_user_info",
|
||||
"state": f"{oauth_type}:{user_id}:{app_id}:tencent",
|
||||
}
|
||||
query_string = "&".join(f"{k}={v}" for k, v in params.items())
|
||||
return f"https://api.e.qq.com/oauth/authorize?{query_string}"
|
||||
|
||||
|
||||
async def get_token_by_type(code: str, oauth_type: int, app_id: str, app_type: str) -> dict:
|
||||
if app_type in ("juliang_ad", "juliang_qianchuan"):
|
||||
return await get_juliang_token(code, oauth_type, app_id, app_type)
|
||||
elif app_type == "kuaishou":
|
||||
return await get_kuaishou_token(code, oauth_type, app_id)
|
||||
elif app_type == "tencent":
|
||||
return await get_tencent_token(code, oauth_type, app_id)
|
||||
else:
|
||||
raise ValueError(f"不支持的应用类型: {app_type}")
|
||||
|
||||
|
||||
async def get_juliang_token(code: str, oauth_type: int, app_id: str, app_type: str) -> dict:
|
||||
url = "https://api.oceanengine.com/open_api/oauth2/access_token/"
|
||||
|
||||
if app_type == "juliang_ad":
|
||||
apps = settings.JULIANG_AD_APPS
|
||||
else:
|
||||
apps = settings.JULIANG_QIANCHUAN_APPS
|
||||
|
||||
app = next((a for a in apps if a.get("app_id") == app_id), None)
|
||||
async def get_token(code: str, user_id: str, app_id: str, db: AsyncSession) -> dict:
|
||||
#1.根据app_id查询应用配置
|
||||
result = await db.execute(
|
||||
select(UserOAuthApp).where(UserOAuthApp.app_id == app_id)
|
||||
)
|
||||
app = result.scalar_one_or_none()
|
||||
if not app:
|
||||
raise ValueError("应用配置不存在")
|
||||
|
||||
open_type = app.open_type
|
||||
secret = app.secret
|
||||
|
||||
if open_type == 1 or open_type == 2:
|
||||
#千川或广告
|
||||
return await get_juliang_token(app_id, secret, code, open_type, user_id, db)
|
||||
elif open_type == 5:
|
||||
#快手代理商
|
||||
return await get_kuaishou_token(app_id, secret, code, open_type, user_id, db)
|
||||
elif open_type == 9 or open_type == 10:
|
||||
#腾讯营销K2或腾讯营销K3
|
||||
return await get_tencent_token(app_id, secret, code, open_type, user_id, db)
|
||||
else:
|
||||
raise ValueError(f"不支持的应用类型: {open_type}")
|
||||
|
||||
|
||||
async def get_juliang_token(app_id: str, secret: str, code: str, open_type: int, user_id: str, db: AsyncSession) -> dict:
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
#1.请求token
|
||||
url = "https://api.oceanengine.com/open_api/oauth2/access_token/"
|
||||
response = await client.post(
|
||||
url,
|
||||
data={
|
||||
json={
|
||||
"app_id": app_id,
|
||||
"secret": app.get("secret"),
|
||||
"secret": secret,
|
||||
"auth_code": code,
|
||||
},
|
||||
)
|
||||
response.raise_for_status()
|
||||
content = response.json()
|
||||
if content.get("code") != 0:
|
||||
raise ValueError(content.get("message", "获取token失败"))
|
||||
return content.get("data", {})
|
||||
|
||||
|
||||
async def get_kuaishou_token(code: str, oauth_type: int, app_id: str) -> dict:
|
||||
url = "https://open.kuaishou.com/oauth2/token"
|
||||
redirect_uri = f"{settings.BASE_URL}/api/user-oauth/callback"
|
||||
|
||||
app = next((a for a in settings.KUAISHOU_APPS if a.get("app_id") == app_id), None)
|
||||
if not app:
|
||||
raise ValueError("应用配置不存在")
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(
|
||||
url,
|
||||
data={
|
||||
"app_id": app_id,
|
||||
"secret": app.get("secret"),
|
||||
"code": code,
|
||||
"grant_type": "authorization_code",
|
||||
"redirect_uri": redirect_uri,
|
||||
},
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
|
||||
async def get_tencent_token(code: str, oauth_type: int, app_id: str) -> dict:
|
||||
url = "https://api.e.qq.com/oauth/token"
|
||||
redirect_uri = f"{settings.BASE_URL}/api/user-oauth/callback"
|
||||
|
||||
app = next((a for a in settings.TENCENT_APPS if a.get("app_id") == app_id), None)
|
||||
if not app:
|
||||
raise ValueError("应用配置不存在")
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(
|
||||
url,
|
||||
data={
|
||||
"app_id": app_id,
|
||||
"secret": app.get("secret"),
|
||||
"code": code,
|
||||
"grant_type": "authorization_code",
|
||||
"redirect_uri": redirect_uri,
|
||||
},
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
|
||||
async def get_account_info_by_type(token: dict, oauth_type: int, app_type: str) -> dict:
|
||||
if app_type in ("juliang_ad", "juliang_qianchuan"):
|
||||
return await _get_juliang_account_info(token)
|
||||
elif app_type == "kuaishou":
|
||||
return await _get_kuaishou_account_info(token)
|
||||
elif app_type == "tencent":
|
||||
return await _get_tencent_account_info(token)
|
||||
else:
|
||||
raise ValueError(f"不支持的应用类型: {app_type}")
|
||||
|
||||
|
||||
async def _get_juliang_account_info(token: dict) -> dict:
|
||||
access_token = token.get("access_token")
|
||||
url = "https://ad.oceanengine.com/openapi/oauth/user/info/"
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
data = response.json()
|
||||
if data.get("code") != 0:
|
||||
raise ValueError(data.get("message", "获取token失败")+f",错误信息:{data.get('message', '')}")
|
||||
data = data.get("data", {})
|
||||
access_token = data.get("access_token", "")
|
||||
refresh_token = data.get("refresh_token", "")
|
||||
expires_in = datetime.now() + timedelta(seconds=data.get("expires_in", 0))
|
||||
refresh_token_expires_in = datetime.now() + timedelta(seconds=data.get("refresh_token_expires_in", 0))
|
||||
#2.获取已授权角色账户,一个授权可能有多个角色账户
|
||||
url = "https://api.oceanengine.com/open_api/oauth2/advertiser/get/"
|
||||
response = await client.get(
|
||||
url,
|
||||
headers={"Access-Token": access_token},
|
||||
@@ -235,119 +160,111 @@ async def _get_juliang_account_info(token: dict) -> dict:
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
if data.get("code") != 0:
|
||||
raise ValueError(data.get("message", "获取账户信息失败"))
|
||||
raise ValueError(data.get("message", "获取已授权账户失败")+f",错误信息:{data.get('message', '')}")
|
||||
data = data.get("data", {})
|
||||
return {
|
||||
"account_id": data.get("advertiser_id", data.get("account_id", "")),
|
||||
"account_name": data.get("advertiser_name", data.get("account_name", "")),
|
||||
"account_role": data.get("role", ""),
|
||||
"account_username": data.get("username", ""),
|
||||
}
|
||||
|
||||
|
||||
async def _get_kuaishou_account_info(token: dict) -> dict:
|
||||
access_token = token.get("access_token")
|
||||
url = "https://open.kuaishou.com/api/user/info"
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
account_list = data.get("list", [])
|
||||
#3.获取已授权登录信息
|
||||
url = "https://api.oceanengine.com/open_api/2/user/info/"
|
||||
response = await client.get(
|
||||
url,
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
headers={"Access-Token": access_token},
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
return {
|
||||
"account_id": data.get("account_id", ""),
|
||||
"account_name": data.get("account_name", ""),
|
||||
"account_role": data.get("role", ""),
|
||||
"account_username": data.get("username", ""),
|
||||
}
|
||||
|
||||
|
||||
async def _get_tencent_account_info(token: dict) -> dict:
|
||||
access_token = token.get("access_token")
|
||||
url = "https://api.e.qq.com/user/info"
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.get(
|
||||
url,
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
if data.get("code") != 0:
|
||||
raise ValueError(data.get("message", "获取已授权登录信息失败")+f",错误信息:{data.get('message', '')}")
|
||||
data = data.get("data", {})
|
||||
account_username = data.get("email", "")
|
||||
account_userid = str(data.get("id", ""))
|
||||
material_auth_status = data.get("material_auth_status", False)
|
||||
#4.根据登录信息判断是否新增token或更新token,不同的登录信息对应不同的token,然后更新数据库
|
||||
#查询email,appid,user_id是否存在已授权记录
|
||||
oauth = await db.execute(
|
||||
select(UserOAuth)
|
||||
.where(UserOAuth.account_username == account_username, UserOAuth.account_userid == account_userid, UserOAuth.appid == app_id, UserOAuth.user_id == user_id)
|
||||
.limit(1)
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
return {
|
||||
"account_id": data.get("account_id", ""),
|
||||
"account_name": data.get("account_name", ""),
|
||||
"account_role": data.get("role", ""),
|
||||
"account_username": data.get("username", ""),
|
||||
}
|
||||
oauth = oauth.scalar_one_or_none()
|
||||
if not oauth:
|
||||
for account in account_list:
|
||||
#新增授权记录
|
||||
db.add(UserOAuth(
|
||||
id=generate_id(),
|
||||
account_id = str(account.get("account_id", "")),
|
||||
account_name = account.get("account_name", ""),
|
||||
account_role = account.get("account_role", ""),
|
||||
account_username = account_username,
|
||||
account_userid = account_userid,
|
||||
user_id = user_id,
|
||||
appid = app_id,
|
||||
open_type = open_type,
|
||||
port_type = 1,
|
||||
access_token = access_token,
|
||||
access_token_expired = expires_in,
|
||||
refresh_token = refresh_token,
|
||||
refresh_token_expired = refresh_token_expires_in,
|
||||
material_auth_status = material_auth_status,
|
||||
))
|
||||
await db.commit()
|
||||
else:
|
||||
# 查询现有授权记录(未删除的)
|
||||
existing_accounts = await db.execute(
|
||||
select(UserOAuth).where(
|
||||
UserOAuth.account_username == account_username,
|
||||
UserOAuth.account_userid == account_userid,
|
||||
UserOAuth.appid == app_id,
|
||||
UserOAuth.user_id == user_id,
|
||||
UserOAuth.deleted_at.is_(None),
|
||||
)
|
||||
)
|
||||
existing_accounts = {acc.account_id: acc for acc in existing_accounts.scalars().all()}
|
||||
|
||||
# 新的账户列表
|
||||
new_account_ids = {str(account.get("account_id")) for account in account_list}
|
||||
old_account_ids = set(existing_accounts.keys())
|
||||
|
||||
async def save_oauth_token(
|
||||
db: AsyncSession,
|
||||
user_id: str,
|
||||
oauth_type: int,
|
||||
token: dict,
|
||||
account_info: dict,
|
||||
app_id: str,
|
||||
) -> UserOAuth:
|
||||
config = OAUTH_TYPE_CONFIG.get(oauth_type)
|
||||
if not config:
|
||||
raise ValueError(f"不支持的oauth_type: {oauth_type}")
|
||||
# 1. 软删除已消失的账户
|
||||
for account_id in old_account_ids - new_account_ids:
|
||||
existing_accounts[account_id].deleted_at = datetime.now()
|
||||
|
||||
access_token = token.get("access_token")
|
||||
access_token_expired = token.get("expires_in")
|
||||
refresh_token = token.get("refresh_token")
|
||||
refresh_token_expired = token.get("refresh_token_expires_in")
|
||||
# 2. 更新或新增账户
|
||||
for account in account_list:
|
||||
account_id = str(account.get("account_id", ""))
|
||||
if account_id in existing_accounts:
|
||||
# 更新现有记录
|
||||
existing_oauth = existing_accounts[account_id]
|
||||
existing_oauth.account_name = account.get("account_name", "")
|
||||
existing_oauth.account_role = account.get("account_role", "")
|
||||
existing_oauth.access_token = access_token
|
||||
existing_oauth.access_token_expired = expires_in
|
||||
existing_oauth.refresh_token = refresh_token
|
||||
existing_oauth.refresh_token_expired = refresh_token_expires_in
|
||||
existing_oauth.material_auth_status = material_auth_status
|
||||
else:
|
||||
# 新增记录
|
||||
db.add(UserOAuth(
|
||||
id=generate_id(),
|
||||
account_id=str(account_id),
|
||||
account_name=account.get("account_name", ""),
|
||||
account_role=account.get("account_role", ""),
|
||||
account_username=account_username,
|
||||
account_userid = account_userid,
|
||||
user_id=user_id,
|
||||
appid=app_id,
|
||||
open_type=open_type,
|
||||
port_type=1,
|
||||
access_token = access_token,
|
||||
access_token_expired=expires_in,
|
||||
refresh_token=refresh_token,
|
||||
refresh_token_expired=refresh_token_expires_in,
|
||||
material_auth_status=material_auth_status,
|
||||
))
|
||||
await db.commit()
|
||||
|
||||
expires_at = None
|
||||
if access_token_expired:
|
||||
expires_at = datetime.now().timestamp() + int(access_token_expired)
|
||||
expires_at = datetime.fromtimestamp(expires_at)
|
||||
#5.返回成功
|
||||
return {"message": "授权成功"}
|
||||
|
||||
refresh_expires_at = None
|
||||
if refresh_token_expired:
|
||||
refresh_expires_at = datetime.now().timestamp() + int(refresh_token_expired)
|
||||
refresh_expires_at = datetime.fromtimestamp(refresh_expires_at)
|
||||
|
||||
existing = await db.execute(
|
||||
select(UserOAuth).where(
|
||||
UserOAuth.user_id == user_id,
|
||||
UserOAuth.open_type == oauth_type,
|
||||
UserOAuth.account_id == account_info.get("account_id", ""),
|
||||
).limit(1)
|
||||
)
|
||||
existing_oauth = existing.scalar_one_or_none()
|
||||
|
||||
if existing_oauth:
|
||||
existing_oauth.access_token = access_token
|
||||
existing_oauth.access_token_expired = expires_at
|
||||
existing_oauth.refresh_token = refresh_token
|
||||
existing_oauth.refresh_token_expired = refresh_expires_at
|
||||
existing_oauth.account_name = account_info.get("account_name", "")
|
||||
existing_oauth.account_role = account_info.get("account_role", "")
|
||||
existing_oauth.account_username = account_info.get("account_username", "")
|
||||
existing_oauth.appid = app_id
|
||||
await db.flush()
|
||||
return existing_oauth
|
||||
|
||||
user_oauth = UserOAuth(
|
||||
id=generate_id(),
|
||||
account_id=account_info.get("account_id", ""),
|
||||
account_name=account_info.get("account_name", ""),
|
||||
account_role=account_info.get("account_role", ""),
|
||||
account_username=account_info.get("account_username", ""),
|
||||
user_id=user_id,
|
||||
open_type=oauth_type,
|
||||
port_type=config["port_type"],
|
||||
appid=app_id,
|
||||
access_token=access_token,
|
||||
access_token_expired=expires_at,
|
||||
refresh_token=refresh_token,
|
||||
refresh_token_expired=refresh_expires_at,
|
||||
material_auth_status=True,
|
||||
)
|
||||
|
||||
db.add(user_oauth)
|
||||
await db.flush()
|
||||
return user_oauth
|
||||
async def get_kuaishou_token(app_id: str, secret: str, code: str, oauth_type: int, user_id: str, db: AsyncSession) -> dict:
|
||||
return "未配置"
|
||||
async def get_tencent_token(app_id: str, secret: str, code: str, oauth_type: int, user_id: str, db: AsyncSession) -> str:
|
||||
return "未配置"
|
||||
Reference in New Issue
Block a user