Andrei Neagoie Python - ~repack~
def __init__( self, secret_key: str, max_failed_attempts: int = 5, lockout_minutes: int = 15 ): """ Initialize authentication service Args: secret_key: Secret key for JWT max_failed_attempts: Number of failed attempts before lockout lockout_minutes: Lockout duration in minutes """ self.users: Dict[str, User] = {} self.token_manager = TokenManager(secret_key) self.password_hasher = PasswordHasher() self.rate_limiter = RateLimiter() self.max_failed_attempts = max_failed_attempts self.lockout_minutes = lockout_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
def test_verify_wrong_password(self): hasher = PasswordHasher() hashed = hasher.hash_password("Correct123!") assert not hasher.verify_password("Wrong456!", hashed) class TestAuthenticationService: @pytest.fixture def auth_service(self): return AuthenticationService(secret_key="test-secret-key-123") def __init__( self
test_auth.py content: """
