feat: login mit serverseitigen sessions
- POST /api/auth/login|logout, GET /api/auth/me - Session-Token nur gehasht gespeichert, Cookie HttpOnly/Secure/SameSite=Lax - Ablauf nach 30 Tagen Inaktivität bzw. spätestens 90 Tagen - Sessions pro Gerät auflisten und widerrufen, Rotation beim Login - Passwortänderung beendet alle anderen Sessions Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
04161bcf1d
commit
18f0d04ce9
11 files changed
+556
-3
No files matched your search
@@ -0,0 +1,19 @@
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models import LoginAttempt, User
|
||||
from app.security import hash_password, password_needs_rehash, verify_password
|
||||
from app.services.users import get_by_username, normalize_username
|
||||
|
||||
|
||||
def authenticate(db: Session, username: str, password: str, ip: str | None) -> User | None:
|
||||
"""Verify credentials and record the attempt. Inactive users cannot log in."""
|
||||
username = normalize_username(username)[:255]
|
||||
user = get_by_username(db, username)
|
||||
valid = verify_password(user.password_hash if user else None, password)
|
||||
success = valid and user is not None and user.is_active
|
||||
|
||||
db.add(LoginAttempt(username=username, ip=ip, success=success))
|
||||
if success and password_needs_rehash(user.password_hash):
|
||||
user.password_hash = hash_password(password)
|
||||
db.commit()
|
||||
return user if success else None
|
||||
@@ -0,0 +1,96 @@
|
||||
from datetime import timedelta
|
||||
|
||||
from sqlalchemy import delete, or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.config import get_settings
|
||||
from app.models import User, UserSession, utcnow
|
||||
from app.security import hash_token, new_token
|
||||
|
||||
# last_seen_at is only written when older than this, to avoid a write per request
|
||||
TOUCH_INTERVAL = timedelta(minutes=5)
|
||||
|
||||
|
||||
def create_session(
|
||||
db: Session, user: User, ip: str | None, user_agent: str | None
|
||||
) -> tuple[UserSession, str]:
|
||||
"""Create a session and return it with the raw token (only ever stored in the cookie)."""
|
||||
token = new_token()
|
||||
now = utcnow()
|
||||
session = UserSession(
|
||||
token_hash=hash_token(token),
|
||||
csrf_token=new_token(),
|
||||
user_id=user.id,
|
||||
created_at=now,
|
||||
last_seen_at=now,
|
||||
expires_at=now + timedelta(days=get_settings().session_max_days),
|
||||
ip=ip,
|
||||
user_agent=(user_agent or "")[:255] or None,
|
||||
)
|
||||
db.add(session)
|
||||
db.commit()
|
||||
return session, token
|
||||
|
||||
|
||||
def resolve_session(db: Session, token: str | None) -> UserSession | None:
|
||||
"""Return the valid session for a raw token; expired sessions are deleted."""
|
||||
if not token:
|
||||
return None
|
||||
session = db.scalar(select(UserSession).where(UserSession.token_hash == hash_token(token)))
|
||||
if session is None:
|
||||
return None
|
||||
|
||||
now = utcnow()
|
||||
idle_deadline = session.last_seen_at + timedelta(days=get_settings().session_idle_days)
|
||||
if now >= session.expires_at or now >= idle_deadline or not session.user.is_active:
|
||||
db.delete(session)
|
||||
db.commit()
|
||||
return None
|
||||
|
||||
if now - session.last_seen_at >= TOUCH_INTERVAL:
|
||||
session.last_seen_at = now
|
||||
db.commit()
|
||||
return session
|
||||
|
||||
|
||||
def list_sessions(db: Session, user_id: int) -> list[UserSession]:
|
||||
return list(
|
||||
db.scalars(
|
||||
select(UserSession)
|
||||
.where(UserSession.user_id == user_id)
|
||||
.order_by(UserSession.last_seen_at.desc())
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def revoke_session(db: Session, user_id: int, session_id: int) -> bool:
|
||||
result = db.execute(
|
||||
delete(UserSession).where(UserSession.id == session_id, UserSession.user_id == user_id)
|
||||
)
|
||||
db.commit()
|
||||
return result.rowcount > 0
|
||||
|
||||
|
||||
def revoke_other_sessions(db: Session, user_id: int, keep_session_id: int) -> int:
|
||||
result = db.execute(
|
||||
delete(UserSession).where(UserSession.user_id == user_id, UserSession.id != keep_session_id)
|
||||
)
|
||||
db.commit()
|
||||
return result.rowcount
|
||||
|
||||
|
||||
def revoke_all_sessions(db: Session, user_id: int) -> None:
|
||||
db.execute(delete(UserSession).where(UserSession.user_id == user_id))
|
||||
db.commit()
|
||||
|
||||
|
||||
def delete_expired_sessions(db: Session) -> int:
|
||||
now = utcnow()
|
||||
idle_cutoff = now - timedelta(days=get_settings().session_idle_days)
|
||||
result = db.execute(
|
||||
delete(UserSession).where(
|
||||
or_(UserSession.expires_at <= now, UserSession.last_seen_at <= idle_cutoff)
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
return result.rowcount
|
||||
Reference in new issue
Block a user