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