Advertisement
egarg4ul

Google App Engine Python

May 31st, 2012
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.54 KB | None | 0 0
  1. """
  2. Created By Egar Rizki Santuso
  3. Concact: http://www.facebook.com/egar.isthecrime
  4. """
  5. import logging, md5, urllib, urllib2
  6.  
  7.  
  8. def do_auth(appname, user, password, dev=False, admin=False):
  9.     "This is taken from bits of appcfg, specifically: "
  10.     " google/appengine/tools/appengine_rpc.py "
  11.     "It returns the cookie send by the App Engine Login "
  12.     "front-end after authenticating with Google Accounts. "
  13.  
  14.     if dev:
  15.         return do_auth_dev_appserver(user, admin)
  16.  
  17.     # get the token
  18.     try:
  19.         auth_token = get_google_authtoken(appname, user, password)
  20.     except AuthError, e:
  21.         if e.reason == "BadAuthentication":
  22.             logging.error( "Invalid username or password." )
  23.         if e.reason == "CaptchaRequired":
  24.             logging.error(
  25.                 "Please go to\n"
  26.                 "https://www.google.com/accounts/DisplayUnlockCaptcha\n"
  27.                 "and verify you are a human.  Then try again.")
  28.         if e.reason == "NotVerified":
  29.             logging.error( "Account not verified.")
  30.         if e.reason == "TermsNotAgreed":
  31.             logging.error( "User has not agreed to TOS.")
  32.         if e.reason == "AccountDeleted":
  33.             logging.error( "The user account has been deleted.")
  34.         if e.reason == "AccountDisabled":
  35.             logging.error( "The user account has been disabled.")
  36.         if e.reason == "ServiceDisabled":
  37.             logging.error( "The user's access to the service has been "
  38.                                  "disabled.")
  39.         if e.reason == "ServiceUnavailable":
  40.             logging.error( "The service is not available; try again later.")
  41.         raise
  42.  
  43.     # now get the cookie
  44.     cookie = get_gae_cookie(appname, auth_token)
  45.     assert cookie
  46.     return cookie
  47.  
  48. def do_auth_dev_appserver(email, admin):
  49.     """Creates cookie payload data.
  50.  
  51.    Args:
  52.    email, admin: Parameters to incorporate into the cookie.
  53.  
  54.    Returns:
  55.    String containing the cookie payload.
  56.    """
  57.     admin_string = 'False'
  58.     if admin:
  59.         admin_string = 'True'
  60.     if email:
  61.         user_id_digest = md5.new(email.lower()).digest()
  62.         user_id = '1' + ''.join(['%02d' % ord(x) for x in user_id_digest])[:20]
  63.     else:
  64.         user_id = ''
  65.     return 'dev_appserver_login="%s:%s:%s"; Path=/;' % (email, admin_string, user_id)
  66.  
  67. def get_gae_cookie(appname, auth_token):
  68.     """
  69.    Send a token to the App Engine login, again stating the name of the
  70.    application to gain authentication for. Returned is a cookie that may be used
  71.    to authenticate HTTP traffic to the application at App Engine.
  72.    """
  73.  
  74.     continue_location = "http://localhost/"
  75.     args = {"continue": continue_location, "auth": auth_token}
  76.     host = "%s.appspot.com" % appname
  77.     url = "https://%s/_ah/login?%s" % (host,
  78.                                urllib.urlencode(args))
  79.  
  80.     opener = get_opener() # no redirect handler!
  81.     req = urllib2.Request(url)
  82.     try:
  83.         response = opener.open(req)
  84.     except urllib2.HTTPError, e:
  85.         response = e
  86.  
  87.     if (response.code != 302 or
  88.             response.info()["location"] != continue_location):
  89.         raise urllib2.HTTPError(req.get_full_url(), response.code,
  90.                 response.msg, response.headers, response.fp)
  91.  
  92.     cookie = response.headers.get('set-cookie')
  93.     assert cookie and cookie.startswith('ACSID')
  94.     return cookie.replace('; HttpOnly', '')
  95.  
  96. def get_google_authtoken(appname, email_address, password):
  97.     """
  98.    Make secure connection to Google Accounts and retrieve an authorisation
  99.    token for the stated appname.
  100.  
  101.    The token can be send to the login front-end at appengine using
  102.    get_gae_cookie(), which will return a cookie to use for the user session.
  103.    """
  104.     opener = get_opener()
  105.  
  106.     # get an AuthToken from Google accounts
  107.     auth_uri = 'https://www.google.com/accounts/ClientLogin'
  108.     authreq_data = urllib.urlencode({ "Email":   email_address,
  109.                                       "Passwd":  password,
  110.                                       "service": "ah",
  111.                                       "source":  appname,
  112.                                       "accountType": "HOSTED_OR_GOOGLE" })
  113.     req = urllib2.Request(auth_uri, data=authreq_data)
  114.     try:
  115.         response = opener.open(req)
  116.         response_body = response.read()
  117.         response_dict = dict(x.split("=")
  118.                              for x in response_body.split("\n") if x)
  119.         return response_dict["Auth"]
  120.     except urllib2.HTTPError, e:
  121.         if e.code == 403:
  122.             body = e.read()
  123.             response_dict = dict(x.split("=", 1) for x in body.split("\n") if x)
  124.             raise AuthError(req.get_full_url(), e.code, e.msg,
  125.                                    e.headers, response_dict)
  126.         else:
  127.             raise
  128.  
  129. class AuthError(urllib2.HTTPError):
  130.     """Raised to indicate there was an error authenticating."""
  131.  
  132.     def __init__(self, url, code, msg, headers, args):
  133.         urllib2.HTTPError.__init__(self, url, code, msg, headers, None)
  134.         self.args = args
  135.         self.reason = args["Error"]
  136.  
  137. def get_opener(cookiejar=None):
  138.     opener = urllib2.OpenerDirector()
  139.     opener.add_handler(urllib2.ProxyHandler())
  140.     opener.add_handler(urllib2.UnknownHandler())
  141.     opener.add_handler(urllib2.HTTPHandler())
  142.     opener.add_handler(urllib2.HTTPDefaultErrorHandler())
  143.     opener.add_handler(urllib2.HTTPErrorProcessor())
  144.     opener.add_handler(urllib2.HTTPSHandler())
  145.     if cookiejar:
  146.         opener.add_handler(urllib2.HTTPCookieProcessor(cookiejar))
  147.     return opener
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement