116 lines
4.3 KiB
Python
116 lines
4.3 KiB
Python
"""登录 / 退出 / 当前用户 / 自己的设置(昵称、密码)。
|
||
|
||
登录失败按「账号 + IP」限流:连错 5 次锁 5 分钟,成功一次即清零。
|
||
进程内计数,重启即复位——防的是脚本撞库,不追求分布式精确。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import time
|
||
from collections import defaultdict, deque
|
||
|
||
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
||
from sqlalchemy.orm import Session
|
||
|
||
from .. import audit, config, security
|
||
from ..db import get_db
|
||
from ..models import User
|
||
from ..schemas import LoginIn, PasswordIn, ProfileIn
|
||
|
||
router = APIRouter()
|
||
|
||
MAX_FAILS = 5
|
||
LOCK_SECONDS = 300
|
||
_failures: dict[str, deque] = defaultdict(deque)
|
||
|
||
|
||
def _throttle_key(request: Request, username: str) -> str:
|
||
return f"{audit.client_ip(request) or '?'}|{username}"
|
||
|
||
|
||
def _check_lock(key: str) -> None:
|
||
now = time.time()
|
||
hits = _failures[key]
|
||
while hits and now - hits[0] > LOCK_SECONDS:
|
||
hits.popleft()
|
||
if len(hits) >= MAX_FAILS:
|
||
wait = int(LOCK_SECONDS - (now - hits[0])) + 1
|
||
raise HTTPException(status_code=429, detail=f"密码连续输错 {MAX_FAILS} 次,请 {wait} 秒后再试")
|
||
|
||
|
||
def _mark_fail(key: str) -> None:
|
||
_failures[key].append(time.time())
|
||
|
||
|
||
def _clear_fail(key: str) -> None:
|
||
_failures.pop(key, None)
|
||
|
||
|
||
@router.post("/auth/login")
|
||
def login(body: LoginIn, request: Request, response: Response, db: Session = Depends(get_db)):
|
||
username = (body.username or "").strip()
|
||
key = _throttle_key(request, username)
|
||
_check_lock(key)
|
||
user = db.query(User).filter(User.username == username).one_or_none()
|
||
if user is None or not security.verify_password(body.password or "", user.password_hash, user.password_salt):
|
||
_mark_fail(key)
|
||
audit.note(request, f"登录失败:{username}", username=username or None)
|
||
raise HTTPException(status_code=401, detail="用户名或密码不正确")
|
||
if not user.active:
|
||
audit.note(request, f"账号已停用:{username}", username=username or None)
|
||
raise HTTPException(status_code=403, detail="该账号已被停用,请联系管理员")
|
||
_clear_fail(key)
|
||
token = security.start_session(
|
||
db, user, ip=audit.client_ip(request), user_agent=request.headers.get("user-agent")
|
||
)
|
||
request.state.user = user
|
||
response.set_cookie(
|
||
security.SESSION_COOKIE, token,
|
||
max_age=config.SESSION_DAYS * 86400,
|
||
httponly=True, samesite="lax", path="/",
|
||
)
|
||
return user.to_dict()
|
||
|
||
|
||
@router.post("/auth/logout")
|
||
def logout(request: Request, response: Response, db: Session = Depends(get_db)):
|
||
token = request.cookies.get(security.SESSION_COOKIE)
|
||
if token:
|
||
request.state.user = security.user_from_token(db, token)
|
||
db.query(security.UserSession).filter(security.UserSession.token == token).delete()
|
||
db.commit()
|
||
response.delete_cookie(security.SESSION_COOKIE, path="/")
|
||
return {"ok": True}
|
||
|
||
|
||
@router.get("/auth/me")
|
||
def me(user: User = Depends(security.current_user)):
|
||
return user.to_dict()
|
||
|
||
|
||
@router.put("/auth/me")
|
||
def update_me(body: ProfileIn, user: User = Depends(security.current_user), db: Session = Depends(get_db)):
|
||
name = (body.name or "").strip()
|
||
if not name:
|
||
raise HTTPException(status_code=400, detail="昵称不能为空")
|
||
user.name = name[:64]
|
||
db.commit()
|
||
return user.to_dict()
|
||
|
||
|
||
@router.post("/auth/password")
|
||
def change_password(body: PasswordIn, request: Request, response: Response,
|
||
user: User = Depends(security.current_user), db: Session = Depends(get_db)):
|
||
if not security.verify_password(body.old_password or "", user.password_hash, user.password_salt):
|
||
raise HTTPException(status_code=400, detail="原密码不正确")
|
||
new = (body.new_password or "").strip()
|
||
if len(new) < 6:
|
||
raise HTTPException(status_code=400, detail="新密码至少 6 位")
|
||
if new == (body.old_password or ""):
|
||
raise HTTPException(status_code=400, detail="新密码不能与原密码相同")
|
||
user.password_hash, user.password_salt = security.hash_password(new)
|
||
audit.note(request, "修改自己的密码")
|
||
# 改密后其余设备全部下线,只保留当前这次登录
|
||
keep = request.cookies.get(security.SESSION_COOKIE)
|
||
security.revoke_all(db, user.id, keep_token=keep)
|
||
return {"ok": True}
|