refactored and fixed AuthMiddleware