Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

So I've always found the inability of handling this error quite annoying. It occurs when the login handler attribute in app.yaml is set to admin and you try to access a page while logged in as a non-admin user. There appears no way of telling AppEngine of handling this kind of error beyond the default error message, but I wanted to be sure.
 Error
Current logged in user [email protected] is not authorized to view this page.


In the DevServer, the error originates in the appengine/tools/devappserver2/url_handler.py file at around line 143. I'm having a guess here, but the production server is most likely very similar, at least the error is.
 Python
...
elif admin_only and not admin:
logging.debug('admin required, user unauthorized')
start_response('401 Not authorized', [('Content-Type', 'text/html'),
('Cache-Control', 'no-cache')])
return ['Current logged in user %s is not '
'authorized to view this page.'
% email_addr]
...


Looking at the code confirmed it for me - there is no way of handling this scenario. However I did come up with a kind of a workaround...the workaround is to add a handler for the /logout URL on your app like this...
 app.yaml
- url: /logout
script: logout.php
secure: always
redirect_http_response_code: 301


The code for logout.php is then something like this...
 logout.php
<?php
use google\appengine\api\users\UserService;
$user = UserService::getCurrentUser();
if (isset($user)) {
echo 'Logged in as ' . $user->getEmail() . (UserService::isCurrentUserAdmin() ? ' (admin)' : '') . '.<br/><a href="' . UserService::createLogoutUrl('/') . '">Log Out</a>';
}
else {
echo 'Not logged in.';
}


This code checks if a user is logged in and displays the email address and whether it's an admin user or not. It then also displays a link to the logout URL. Simple.
 Output
Logged in as [email protected] (admin).
Log Out


Although the workaround doesn't help handle the error, it does allow to easily log out as a non-admin user and login as an admin user to access a restricted page.



-i

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.