Andrei Neagoie Python Here
def test_account_lockout(self, auth_service): auth_service.register_user("test@example.com", "ValidPass123!") # Try wrong password 5 times (max_failed_attempts=5) for _ in range(5): with pytest.raises(InvalidPasswordError): auth_service.login("test@example.com", "wrong", "127.0.0.1") # Next attempt should lock account with pytest.raises(AuthenticationError, match="Account locked"): auth_service.login("test@example.com", "ValidPass123!", "127.0.0.1")
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 andrei neagoie python
def verify_token(self, token: str) -> User: """ Verify JWT token and return associated user Args: token: JWT token Returns: User object Raises: AuthenticationError: If token is invalid or user not found """ payload = self.token_manager.validate_token(token) user_id = payload.get('user_id') email = payload.get('email') user = self.users.get(email) if not user or user.user_id != user_id: raise AuthenticationError("Invalid token: user not found") if not user.is_active: raise AuthenticationError("User account is deactivated") if user.is_locked(): raise AuthenticationError("User account is locked") return user """ To run tests: pytest test_auth.py -v def test_account_lockout(self, auth_service): auth_service
def test_hash_password_weak(self): hasher = PasswordHasher() with pytest.raises(ValidationError): hasher.hash_password("weak") "127.0.0.1") def __init__( self
def generate_token(self, user_id: str, email: str) -> str: """ Generate JWT token for authenticated user Args: user_id: User's unique identifier email: User's email address Returns: JWT token string """ payload = 'user_id': user_id, 'email': email, 'exp': datetime.utcnow() + timedelta(minutes=self.token_expiry_minutes), 'iat': datetime.utcnow(), 'jti': str(uuid4()) # Unique token ID return jwt.encode(payload, self.secret_key, algorithm='HS256')