Move middleware functions into middleware module and create associated tests
Note: this only moves middleware functions that have associated tests.
Merge pull request #1372 from hswolff/cleanup-middleware

Move all middleware into middleware module.