Is there a way to check if the user is an admin in

2019-04-01 00:25发布

I am using AppEngine Cloud Endpoints with the Javascript client and Google+ Sign In, I am using endpoints.get_current_user(). Is there a way to check if the user is an AppEngine admin? Similar to users.is_current_user_admin() in users API.

Thanks

1条回答
祖国的老花朵
2楼-- · 2019-04-01 00:59

See Google Endpoints API + Chrome Extension returns None for endpoints.get_current_user().user_id() for a long description of the difference between ID tokens and Bearer tokens when performing auth.

If you aren't using an Android application, you can freely use Bearer tokens and not have to worry about some of the limitations of ID tokens.

Right next get_current_user(), the oauth library provides the oauth.is_current_user_admin() method. Exactly as get_current_user(), this method calls _maybe_call_get_oauth_user and then checks a simple environment variable.

As mentioned in the other answer:

The oauth.get_current_user() call is only expensive IF it makes the RPC. The _maybe_call_get_oauth_user method stores the value from the last call, so calling oauth.get_current_user() a second time will incur no network/speed overhead other than the few nanoseconds to lookup a value from a Python dict.

So if you are only using Bearer tokens, you could do the following

from google.appengine.api import oauth
from google.appengine.ext import endpoints

...

endpoints_user = endpoints.get_current_user()
if endpoints_user is None:
    raise endpoints.UnauthorizedException(...)

is_admin = oauth.is_current_user_admin(known_scope)
if not is_admin:
    # Throw a 403 FORBIDDEN
    raise endpoints.ForbiddenException(...)
查看更多
登录 后发表回答