refactored middleware.py