82 lines
2.2 KiB
Python
82 lines
2.2 KiB
Python
from datetime import datetime, timedelta, timezone
|
|
from typing import Any
|
|
|
|
from sqlalchemy import select
|
|
from sqlalchemy.orm import Session
|
|
|
|
LOGIN_MAX_FAILURES_KEY = "login_max_failures"
|
|
LOGIN_LOCK_MINUTES_KEY = "login_lock_minutes"
|
|
# 仅在 site_setting 缺少对应行时使用。运行时以数据库为准。
|
|
_DEFAULT_MAX_FAILURES = 5
|
|
_DEFAULT_LOCK_MINUTES = 15
|
|
|
|
|
|
def _now() -> datetime:
|
|
return datetime.now(timezone.utc)
|
|
|
|
|
|
def _as_utc(value: datetime) -> datetime:
|
|
if value.tzinfo is None:
|
|
return value.replace(tzinfo=timezone.utc)
|
|
return value.astimezone(timezone.utc)
|
|
|
|
|
|
def _naive_utc(value: datetime) -> datetime:
|
|
return _as_utc(value).replace(tzinfo=None)
|
|
|
|
|
|
def is_currently_locked(user: Any) -> bool:
|
|
locked_until = getattr(user, "locked_until", None)
|
|
if not isinstance(locked_until, datetime):
|
|
return False
|
|
return _as_utc(locked_until) > _now()
|
|
|
|
|
|
def _stored_int(found: dict[str, Any], key: str, fallback: int) -> int:
|
|
if key not in found:
|
|
return fallback
|
|
raw = found[key]
|
|
if raw is None:
|
|
return fallback
|
|
text = str(raw).strip()
|
|
if not text:
|
|
return fallback
|
|
try:
|
|
return int(text)
|
|
except ValueError:
|
|
return fallback
|
|
|
|
|
|
def read_login_policy(db: Session) -> tuple[int, int]:
|
|
from app.models.content import SiteSetting
|
|
|
|
rows = db.scalars(
|
|
select(SiteSetting).where(SiteSetting.key.in_((LOGIN_MAX_FAILURES_KEY, LOGIN_LOCK_MINUTES_KEY)))
|
|
).all()
|
|
found = {row.key: row.value for row in rows}
|
|
return (
|
|
_stored_int(found, LOGIN_MAX_FAILURES_KEY, _DEFAULT_MAX_FAILURES),
|
|
_stored_int(found, LOGIN_LOCK_MINUTES_KEY, _DEFAULT_LOCK_MINUTES),
|
|
)
|
|
|
|
|
|
def record_failure(db: Session, user: Any) -> None:
|
|
max_failures, lock_minutes = read_login_policy(db)
|
|
count = int(getattr(user, "failed_login_count", 0) or 0) + 1
|
|
if count >= max_failures:
|
|
user.failed_login_count = 0
|
|
user.locked_until = _naive_utc(_now() + timedelta(minutes=lock_minutes))
|
|
else:
|
|
user.failed_login_count = count
|
|
db.add(user)
|
|
db.commit()
|
|
db.refresh(user)
|
|
|
|
|
|
def clear_failures(db: Session, user: Any) -> None:
|
|
user.failed_login_count = 0
|
|
user.locked_until = None
|
|
db.add(user)
|
|
db.commit()
|
|
db.refresh(user)
|