Andrei Neagoie Python _verified_ May 2026
class TestPasswordHasher: def test_hash_password_valid(self): hasher = PasswordHasher() password = "SecurePass123!" hashed = hasher.hash_password(password) assert ":" in hashed assert hasher.verify_password(password, hashed)
class ValidationError(AuthenticationError): """Raised when input validation fails""" pass
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 andrei neagoie python
import jwt from jwt.exceptions import InvalidTokenError, ExpiredSignatureError class AuthenticationError(Exception): """Base exception for authentication errors""" pass
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') email: str) ->
class RateLimitExceededError(AuthenticationError): """Raised when too many attempts""" pass
def test_hash_password_weak(self): hasher = PasswordHasher() with pytest.raises(ValidationError): hasher.hash_password("weak") token: str) ->
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




