def test_expired_token(self, auth_service): # Create service with very short expiry service = AuthenticationService(secret_key="test-key") service.token_manager.token_expiry_minutes = 0 # Expired immediately service.register_user("test@example.com", "ValidPass123!") token, _ = service.login("test@example.com", "ValidPass123!", "10.0.0.1") with pytest.raises(AuthenticationError, match="expired"): service.verify_token(token) if name == " main ": # Initialize service with secure secret key (use environment variable in production) auth_service = AuthenticationService(secret_key="your-strong-secret-key-here")
class RateLimitExceededError(AuthenticationError): """Raised when too many attempts""" pass andrei neagoie python
def register_user(self, email: str, password: str) -> User: """ Register a new user Args: email: User's email address password: User's password Returns: Created User object Raises: ValidationError: If email is invalid or user already exists """ # Validate email if not re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]2,$', email): raise ValidationError("Invalid email format") # Check if user already exists if email in self.users: raise ValidationError("User already exists") # Hash password password_hash = self.password_hasher.hash_password(password) # Create user user = User( user_id=str(uuid4()), email=email, password_hash=password_hash, created_at=datetime.utcnow() ) self.users[email] = user return user _ = service.login("test@example.com"
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") "10.0.0.1") with pytest.raises(AuthenticationError
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_rate_limiting(self, auth_service): auth_service.register_user("test@example.com", "ValidPass123!") ip = "192.168.1.100" # Try wrong password 5 times for _ in range(5): with pytest.raises(InvalidPasswordError): auth_service.login("test@example.com", "wrong", ip) # 6th attempt should trigger rate limit with pytest.raises(RateLimitExceededError): auth_service.login("test@example.com", "wrong", ip)