Andrei Neagoie Python -

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

def test_login_success(self, auth_service): auth_service.register_user("test@example.com", "ValidPass123!") token, user = auth_service.login("test@example.com", "ValidPass123!", "192.168.1.1") assert token is not None assert user.email == "test@example.com"

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") andrei neagoie python

class RateLimitExceededError(AuthenticationError): """Raised when too many attempts""" pass

class UserNotFoundError(AuthenticationError): """Raised when user doesn't exist""" pass def login(self, email: str, password: str, ip_address: str)

@staticmethod def _validate_password_strength(password: str) -> None: """ Validate password meets security requirements Requirements: - Minimum 8 characters - At least 1 uppercase letter - At least 1 lowercase letter - At least 1 digit - At least 1 special character Raises: ValidationError: If password doesn't meet requirements """ if len(password) < 8: raise ValidationError("Password must be at least 8 characters long") if not re.search(r'[A-Z]', password): raise ValidationError("Password must contain at least one uppercase letter") if not re.search(r'[a-z]', password): raise ValidationError("Password must contain at least one lowercase letter") if not re.search(r'\d', password): raise ValidationError("Password must contain at least one digit") if not re.search(r'[!@#$%^&*(),.?":{}|<>]', password): raise ValidationError("Password must contain at least one special character") class TokenManager: """Handles JWT token creation and validation"""

def test_hash_password_weak(self): hasher = PasswordHasher() with pytest.raises(ValidationError): hasher.hash_password("weak") ip_address: str) -&gt

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

Чтобы улучшить качество наших услуг, мы используем файлы cookie. Вы можете узнать больше о файлах cookies здесь. принять