Andrei Neagoie Python Guide
def __init__(self, secret_key: str, token_expiry_minutes: int = 60): """ Initialize token manager Args: secret_key: Secret key for JWT signing token_expiry_minutes: Token expiration time in minutes """ self.secret_key = secret_key self.token_expiry_minutes = token_expiry_minutes
def login(self, email: str, password: str, ip_address: str) -> Tuple[str, User]: """ Authenticate user and return JWT token Args: email: User's email password: User's password ip_address: Client IP for rate limiting Returns: Tuple of (jwt_token, user_object) Raises: UserNotFoundError: If user doesn't exist InvalidPasswordError: If password is incorrect RateLimitExceededError: If too many attempts """ # Check rate limit by IP self.rate_limiter.check_rate_limit(ip_address) self.rate_limiter.record_attempt(ip_address) # Find user user = self.users.get(email) if not user: raise UserNotFoundError("User not found") # Check if account is locked if user.is_locked(): remaining = (user.locked_until - datetime.utcnow()).seconds raise AuthenticationError(f"Account locked. Try again in remaining seconds") # Verify password if not self.password_hasher.verify_password(password, user.password_hash): user.failed_attempts += 1 # Lock account if max attempts exceeded if user.failed_attempts >= self.max_failed_attempts: user.locked_until = datetime.utcnow() + timedelta(minutes=self.lockout_minutes) raise AuthenticationError( f"Too many failed attempts. Account locked for self.lockout_minutes minutes" ) raise InvalidPasswordError("Invalid password") # Successful login - reset failed attempts and update last login user.failed_attempts = 0 user.last_login = datetime.utcnow() # Generate token token = self.token_manager.generate_token(user.user_id, user.email) return token, user andrei neagoie python
class InvalidPasswordError(AuthenticationError): """Raised when password is incorrect""" pass ip_address: str) ->
