Files
Nexus/server/infrastructure/database/admin_repo.py
T
Your Name 32feb1b6db fix: 全站 ruff 清零 — 77 errors → 0
Fixes:
- F821: install.py site_url 未定义(NameError)、sync_v2.py os 未导入、script_jobs.py LOG f-string
- F401: 移除 22 个未使用导入(models/__init__.py、install.py、auth.py 等)
- B904: 20 个 except 块 raise 添加 from e/from None
- S110: 20 个有意的 try-except-pass 添加 noqa 注释(SSH清理/DDL幂等/WS断连)
- B007: 3 个未使用循环变量重命名(dirs→_dirs、server_id→_server_id)
- F541: 3 个无占位符 f-string 修正
- F841: auth.py 未使用 ip_address 变量移除
- S105: auth_service.py Redis key prefix 误报 noqa
- B023: script_execution_flush.py 循环变量绑定修复

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 20:07:45 +08:00

55 lines
2.0 KiB
Python

"""Nexus — Admin & LoginAttempt Repository (Async SQLAlchemy)"""
from typing import Optional
from sqlalchemy import select, func
from sqlalchemy.ext.asyncio import AsyncSession
from server.domain.models import Admin, LoginAttempt
class AdminRepositoryImpl:
def __init__(self, session: AsyncSession):
self.session = session
async def get_by_id(self, id: int) -> Optional[Admin]:
result = await self.session.execute(select(Admin).where(Admin.id == id))
return result.scalar_one_or_none()
async def get_by_username(self, username: str) -> Optional[Admin]:
result = await self.session.execute(select(Admin).where(Admin.username == username))
return result.scalar_one_or_none()
async def get_by_refresh_token(self, refresh_token: str) -> Optional[Admin]:
result = await self.session.execute(select(Admin).where(Admin.jwt_refresh_token == refresh_token))
return result.scalar_one_or_none()
async def create(self, admin: Admin) -> Admin:
self.session.add(admin)
await self.session.commit()
return admin
async def update(self, admin: Admin) -> Admin:
await self.session.commit()
return admin
class LoginAttemptRepositoryImpl:
def __init__(self, session: AsyncSession):
self.session = session
async def create(self, attempt: LoginAttempt) -> LoginAttempt:
self.session.add(attempt)
await self.session.commit()
return attempt
async def count_recent_failures(self, username: str, ip_address: str, minutes: int = 15) -> int:
from datetime import datetime, timedelta, timezone
cutoff = datetime.now(timezone.utc) - timedelta(minutes=minutes)
result = await self.session.execute(
select(func.count(LoginAttempt.id))
.where(LoginAttempt.username == username)
.where(LoginAttempt.ip_address == ip_address)
.where(LoginAttempt.success == False)
.where(LoginAttempt.attempted_at >= cutoff)
)
return result.scalar_one() or 0