get_current_user是如何工作的

时间:2015-12-10 00:50:30

标签: google-app-engine authentication gae-userservice

我真的很困惑Google App Engine的用户get_current_user()如何运作。我在互联网上浏览了许多关于登录和身份验证的不同指南和教程,其中许多都提到了类似的方法。

如果有一百万用户同时登录我的应用程序,该方法怎么可能有效呢?每个用户都有自己的服务器实例吗?服务器如何知道它正在与哪个客户端通信?

对我来说根本没有意义。

1 个答案:

答案 0 :(得分:1)

When logging in (by clicking on the URL generated by create_login_url()) a cookie containing user identifying information is prepared and pushed on the client side, then used in subsequent requests until the user logs out or the cookie expires. Calling get_current_user() simply checks the cookie existance/information and responds accordingly.

On the development server the cookie is named dev_appserver_login. I can no longer check the cookie name on GAE as I switched away from the Users API.

The actual handling of the cookie seems to happen somewhere on the Users service backend, for example, by looking at the google/appengine/api/users.py file in the python SDK:

def create_login_url(dest_url=None, _auth_domain=None,
                     federated_identity=None):
...
  req = user_service_pb.CreateLoginURLRequest()
  resp = user_service_pb.CreateLoginURLResponse()

  try:
    apiproxy_stub_map.MakeSyncCall('user', 'CreateLoginURL', req, resp)
...

The end point (at least for the development server) seems to somehow land somewhere in google/appengine/tools/appengine_rpc.py, for example:

  @staticmethod
  def _CreateDevAppServerCookieData(email, admin):
    """Creates cookie payload data.

    Args:
      email: The user's email address.
      admin: True if the user is an admin; False otherwise.

    Returns:
      String containing the cookie payload.
    """
    if email:
      user_id_digest = hashlib.md5(email.lower()).digest()
      user_id = "1" + "".join(["%02d" % ord(x) for x in user_id_digest])[:20]
    else:
      user_id = ""
    return "%s:%s:%s" % (email, bool(admin), user_id)

  def _DevAppServerAuthenticate(self):
    """Authenticates the user on the dev_appserver."""
    credentials = self.auth_function()
    value = self._CreateDevAppServerCookieData(credentials[0], True)
    self.extra_headers["Cookie"] = ('dev_appserver_login="%s"; Path=/;' % value)