return 401 error to API for unauthorised pages

Uses content detection to work out if it's an API call or a browser so
we return a message in the appropriate format. Add in templates and
error handler for 401 errors.

Fixes #661
return JSON for token auth fails as well as permission issues

Use a custom callback to handle authentication failures so that we can
make sure that we return a JSON object to API calls rather than a plain
text string or an HTML page. This handles the case of a failed login
rather than succesful login but failed permissions.