| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350 |
- """
- Steam账号管理接口
- """
- from fastapi import APIRouter, Depends, HTTPException, Request
- from sqlalchemy.orm import Session
- from pydantic import BaseModel
- from typing import Optional, List
- from app.database import get_db
- from app.models.steam_account import SteamAccount
- from app.models.user import User
- from app.core.encrypt import encryptor
- from app.core.logger import get_client_logger
- logger = get_client_logger()
- from app.config import settings
- from datetime import datetime
- from app.utils.timezone import beijing_now
- router = APIRouter()
- class SteamAccountRequest(BaseModel):
- """Steam账号请求"""
- user_id: int
- steam_username: str
- steam_id: Optional[str] = None
- shared_secret: str
- identity_secret: str
- class SteamAccountUpdateRequest(BaseModel):
- """Steam账号更新请求"""
- user_id: int
- steam_username: Optional[str] = None
- steam_id: Optional[str] = None
- shared_secret: Optional[str] = None
- identity_secret: Optional[str] = None
- is_active: Optional[int] = None
- @router.get("/steam-accounts")
- async def get_steam_accounts(
- request: Request,
- db: Session = Depends(get_db)
- ):
- """获取Steam账号列表"""
- try:
- # 获取请求参数
- params = dict(request.query_params)
-
- # 解密请求数据(如果有)
- user_id = None
- if settings.ENCRYPT_ENABLED:
- encrypted_data = params.get("encrypted", "")
- if encrypted_data:
- decrypted = encryptor.decrypt(encrypted_data)
- user_id = decrypted.get("user_id")
- else:
- user_id = params.get("user_id")
- if user_id:
- user_id = int(user_id)
-
- if not user_id:
- return {"code": 400, "msg": "缺少用户ID"}
-
- # 验证用户是否存在
- user = db.query(User).filter(User.id == user_id).first()
- if not user:
- return {"code": 404, "msg": "用户不存在"}
-
- # 查询Steam账号列表
- accounts = db.query(SteamAccount).filter(
- SteamAccount.user_id == user_id,
- SteamAccount.is_deleted == 0
- ).order_by(SteamAccount.created_at.desc()).all()
-
- # 格式化返回数据
- accounts_data = []
- for account in accounts:
- # 解密共享密钥和身份密钥
- shared_secret = ""
- identity_secret = ""
- try:
- if account.shared_secret:
- shared_secret = encryptor.decrypt(account.shared_secret)
- if account.identity_secret:
- identity_secret = encryptor.decrypt(account.identity_secret)
- except Exception as e:
- logger.error(f"解密Steam账号密钥失败: {e}")
-
- accounts_data.append({
- "id": account.id,
- "steam_username": account.steam_username,
- "steam_id": account.steam_id,
- "shared_secret": shared_secret,
- "identity_secret": identity_secret,
- "is_active": account.is_active,
- "last_used_time": account.last_used_time.isoformat() if account.last_used_time else None,
- "created_at": account.created_at.isoformat() if account.created_at else None,
- "updated_at": account.updated_at.isoformat() if account.updated_at else None
- })
-
- return {
- "code": 200,
- "msg": "成功",
- "data": accounts_data
- }
-
- except Exception as e:
- logger.exception("获取Steam账号列表失败")
- return {"code": 500, "msg": "系统异常,操作未完成,请稍后重试;若持续发生请联系客服"}
- @router.post("/steam-accounts")
- async def create_steam_account(
- request: Request,
- db: Session = Depends(get_db)
- ):
- """添加Steam账号"""
- try:
- # 获取请求数据
- data = await request.json()
-
- # 解密请求数据
- if settings.ENCRYPT_ENABLED:
- encrypted_data = data.get("encrypted", "")
- if not encrypted_data:
- return {"code": 400, "msg": "缺少加密数据"}
- decrypted = encryptor.decrypt(encrypted_data)
- else:
- decrypted = data
-
- req = SteamAccountRequest(**decrypted)
-
- # 验证用户是否存在
- user = db.query(User).filter(User.id == req.user_id).first()
- if not user:
- return {"code": 404, "msg": "用户不存在"}
-
- # 检查Steam用户名是否已存在
- existing = db.query(SteamAccount).filter(
- SteamAccount.user_id == req.user_id,
- SteamAccount.steam_username == req.steam_username
- ).first()
- if existing:
- return {"code": 400, "msg": "该Steam账号已存在"}
-
- # 加密存储共享密钥和身份密钥
- encrypted_shared_secret = encryptor.encrypt(req.shared_secret)
- encrypted_identity_secret = encryptor.encrypt(req.identity_secret)
-
- # 创建Steam账号
- steam_account = SteamAccount(
- user_id=req.user_id,
- steam_username=req.steam_username,
- steam_id=req.steam_id,
- shared_secret=encrypted_shared_secret,
- identity_secret=encrypted_identity_secret,
- is_active=1,
- created_at=beijing_now(),
- updated_at=beijing_now()
- )
- db.add(steam_account)
- # 创建历史记录
- from app.utils.history import create_steam_account_history
- create_steam_account_history(db, steam_account, "INSERT")
- # 一次性提交所有更改
- db.commit()
- db.refresh(steam_account)
- logger.info(f"用户 {req.user_id} 添加Steam账号成功: {req.steam_username}")
- return {
- "code": 200,
- "msg": "添加成功",
- "data": {
- "id": steam_account.id,
- "steam_username": steam_account.steam_username
- }
- }
-
- except Exception as e:
- try:
- db.rollback()
- except Exception:
- logger.warning("回滚数据库事务时发生异常")
- logger.exception("添加Steam账号失败")
- return {"code": 500, "msg": "系统异常,操作未完成,请稍后重试;若持续发生请联系客服"}
- @router.put("/steam-accounts/{account_id}")
- async def update_steam_account(
- account_id: int,
- request: Request,
- db: Session = Depends(get_db)
- ):
- """更新Steam账号"""
- try:
- # 获取请求数据
- data = await request.json()
-
- # 解密请求数据
- if settings.ENCRYPT_ENABLED:
- encrypted_data = data.get("encrypted", "")
- if not encrypted_data:
- return {"code": 400, "msg": "缺少加密数据"}
- decrypted = encryptor.decrypt(encrypted_data)
- else:
- decrypted = data
-
- req = SteamAccountUpdateRequest(**decrypted)
-
- # 查找Steam账号
- account = db.query(SteamAccount).filter(SteamAccount.id == account_id).first()
- if not account:
- return {"code": 404, "msg": "Steam账号不存在"}
-
- # 验证用户ID是否匹配
- if account.user_id != req.user_id:
- return {"code": 403, "msg": "无权访问该账号"}
-
- # 更新字段
- if req.steam_username is not None:
- # 检查新用户名是否与其他账号冲突
- existing = db.query(SteamAccount).filter(
- SteamAccount.user_id == req.user_id,
- SteamAccount.steam_username == req.steam_username,
- SteamAccount.id != account_id
- ).first()
- if existing:
- return {"code": 400, "msg": "该Steam账号已存在"}
- account.steam_username = req.steam_username
-
- if req.steam_id is not None:
- account.steam_id = req.steam_id
-
- if req.shared_secret is not None:
- account.shared_secret = encryptor.encrypt(req.shared_secret)
-
- if req.identity_secret is not None:
- account.identity_secret = encryptor.encrypt(req.identity_secret)
-
- if req.is_active is not None:
- account.is_active = req.is_active
-
- account.updated_at = beijing_now()
- # 创建历史记录
- from app.utils.history import create_steam_account_history
- create_steam_account_history(db, account, "UPDATE")
- # 一次性提交所有更改
- db.commit()
- logger.info(f"用户 {req.user_id} 更新Steam账号成功: {account_id}")
- return {
- "code": 200,
- "msg": "更新成功",
- "data": {
- "id": account.id,
- "steam_username": account.steam_username
- }
- }
-
- except Exception as e:
- try:
- db.rollback()
- except Exception:
- logger.warning("回滚数据库事务时发生异常")
- logger.exception("更新Steam账号失败")
- return {"code": 500, "msg": "系统异常,操作未完成,请稍后重试;若持续发生请联系客服"}
- @router.delete("/steam-accounts/{account_id}")
- async def delete_steam_account(
- account_id: int,
- request: Request,
- db: Session = Depends(get_db)
- ):
- """删除Steam账号"""
- try:
- # 获取请求数据(从body或query参数)
- data = {}
- try:
- # 尝试从body获取
- body = await request.body()
- if body:
- import json
- data = json.loads(body)
- except:
- pass
-
- # 如果body为空,尝试从query参数获取
- if not data:
- params = dict(request.query_params)
- if settings.ENCRYPT_ENABLED:
- encrypted_data = params.get("encrypted", "")
- if encrypted_data:
- data = encryptor.decrypt(encrypted_data)
- else:
- data = params
- else:
- data = params
-
- # 解密请求数据
- user_id = None
- if settings.ENCRYPT_ENABLED and isinstance(data, dict):
- encrypted_data = data.get("encrypted", "")
- if encrypted_data:
- decrypted = encryptor.decrypt(encrypted_data)
- user_id = decrypted.get("user_id")
- elif isinstance(data, dict):
- user_id = data.get("user_id")
- if user_id:
- try:
- user_id = int(user_id)
- except:
- pass
-
- if not user_id:
- return {"code": 400, "msg": "缺少用户ID"}
-
- # 查找Steam账号
- account = db.query(SteamAccount).filter(SteamAccount.id == account_id, SteamAccount.is_deleted == 0).first()
- if not account:
- return {"code": 404, "msg": "Steam账号不存在"}
- # 验证用户ID是否匹配
- if account.user_id != user_id:
- return {"code": 403, "msg": "无权访问该账号"}
- # 软删除账号
- account.is_deleted = 1
- account.updated_at = beijing_now()
- # 创建历史记录
- from app.utils.history import create_steam_account_history
- create_steam_account_history(db, account, "DELETE")
- # 一次性提交所有更改
- db.commit()
-
- logger.info(f"用户 {user_id} 删除Steam账号成功: {account_id}")
- return {
- "code": 200,
- "msg": "删除成功"
- }
-
- except Exception as e:
- try:
- db.rollback()
- except Exception:
- logger.warning("回滚数据库事务时发生异常")
- logger.exception("删除Steam账号失败")
- return {"code": 500, "msg": "系统异常,操作未完成,请稍后重试;若持续发生请联系客服"}
|