kartu

GoogleClientLogin

Apr 26th, 2014
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.64 KB | None | 0 0
  1. import urllib
  2. import httplib2
  3. from google.appengine.api import users
  4. import webapp2
  5. import json
  6. import logging
  7. import gdata.contacts.service
  8. #~ import gdata.calendar.service
  9. import os
  10. import urllib2
  11. import cookielib
  12. import logging, md5, urllib, urllib2
  13. from gdata import gauth
  14.  
  15. #~ from google.appengine.tools import appengine_rpc
  16.  
  17. email = "myemailaddress"
  18. password ="password"
  19. appname = "myapp"
  20.  
  21. target_authenticated_google_app_engine_uri = 'http://myapp.appspot.com/secured'
  22. my_app_name = "myapp"
  23.  
  24. def do_auth(appname, user, password, dev=False, admin=False):
  25.     "This is taken from bits of appcfg, specifically: "
  26.     " google/appengine/tools/appengine_rpc.py "
  27.     "It returns the cookie send by the App Engine Login "
  28.     "front-end after authenticating with Google Accounts. "
  29.  
  30.     if dev:
  31.         return do_auth_dev_appserver(user, admin)
  32.  
  33.     # get the token
  34.     try:
  35.         auth_token = get_google_authtoken(appname, user, password)
  36.     except AuthError, e:
  37.         if e.reason == "BadAuthentication":
  38.             logging.error( "Invalid username or password." )
  39.         if e.reason == "CaptchaRequired":
  40.             logging.error(
  41.                 "Please go to\n"
  42.                 "https://www.google.com/accounts/DisplayUnlockCaptcha\n"
  43.                 "and verify you are a human.  Then try again.")
  44.         if e.reason == "NotVerified":
  45.             logging.error( "Account not verified.")
  46.         if e.reason == "TermsNotAgreed":
  47.             logging.error( "User has not agreed to TOS.")
  48.         if e.reason == "AccountDeleted":
  49.             logging.error( "The user account has been deleted.")
  50.         if e.reason == "AccountDisabled":
  51.             logging.error( "The user account has been disabled.")
  52.         if e.reason == "ServiceDisabled":
  53.             logging.error( "The user's access to the service has been "
  54.                                  "disabled.")
  55.         if e.reason == "ServiceUnavailable":
  56.             logging.error( "The service is not available; try again later.")
  57.         raise
  58.  
  59.     # now get the cookie
  60.     cookie = get_gae_cookie(appname, auth_token)
  61.     assert str(cookie)
  62.     return cookie
  63.  
  64. def do_auth_dev_appserver(email, admin):
  65.     """Creates cookie payload data.
  66.  
  67.    Args:
  68.    email, admin: Parameters to incorporate into the cookie.
  69.  
  70.    Returns:
  71.    String containing the cookie payload.
  72.    """
  73.     admin_string = 'False'
  74.     if admin:
  75.         admin_string = 'True'
  76.     if email:
  77.         user_id_digest = md5.new(email.lower()).digest()
  78.         user_id = '1' + ''.join(['%02d' % ord(x) for x in user_id_digest])[:20]
  79.     else:
  80.         user_id = ''
  81.     return 'dev_appserver_login="%s:%s:%s"; Path=/;' % (email, admin_string, user_id)
  82.  
  83. def get_gae_cookie(appname, auth_token):
  84.     """
  85.    Send a token to the App Engine login, again stating the name of the
  86.    application to gain authentication for. Returned is a cookie that may be used
  87.    to authenticate HTTP traffic to the application at App Engine.
  88.    """
  89.  
  90.     continue_location = "http://myapp.appspot.com/secured"
  91.     args = {"continue": continue_location, "auth": auth_token}
  92.     host = "%s.appspot.com" % appname
  93.     url = "http://%s/_ah/login?%s" % (host,
  94.                                urllib.urlencode(args))
  95.  
  96.     opener = get_opener() # no redirect handler!
  97.     req = urllib2.Request(url)
  98.     try:
  99.         response = opener.open(req)
  100.      
  101.     except urllib2.HTTPError, e:
  102.         response = e
  103.     logging.info(response.headers)
  104.     if (response.code != 302 or
  105.             response.info()["location"] != continue_location):
  106.         raise urllib2.HTTPError(req.get_full_url(), response.code,
  107.                 response.msg, response.headers, response.fp)
  108.  
  109.     cookie = response.headers.get('set-cookie')
  110.     logging.info(response.headers)
  111.     logging.info("cookie string = %s",cookie)
  112.     assert cookie and cookie.startswith('ACSID')
  113.     #~ return cookie.replace('; HttpOnly', '')
  114.     return cookie, auth_token
  115.  
  116. def get_google_authtoken(appname, email_address, password):
  117.     """
  118.    Make secure connection to Google Accounts and retrieve an authorisation
  119.    token for the stated appname.
  120.  
  121.    The token can be send to the login front-end at appengine using
  122.    get_gae_cookie(), which will return a cookie to use for the user session.
  123.    """
  124.     opener = get_opener()
  125.  
  126.     # get an AuthToken from Google accounts
  127.     auth_uri = 'https://www.google.com/accounts/ClientLogin'
  128.     authreq_data = urllib.urlencode({ "Email":   email_address,
  129.                                       "Passwd":  password,
  130.                                       "service": "ah",
  131.                                       "source":  appname,
  132.                                       "accountType": "HOSTED_OR_GOOGLE" })
  133.     req = urllib2.Request(auth_uri, data=authreq_data)
  134.    
  135.     try:
  136.         response = opener.open(req)
  137.         response_body = response.read()
  138.         response_dict = dict(x.split("=")
  139.                              for x in response_body.split("\n") if x)
  140.         return response_dict["Auth"]
  141.     except urllib2.HTTPError, e:
  142.         if e.code == 403:
  143.             body = e.read()
  144.             response_dict = dict(x.split("=", 1) for x in body.split("\n") if x)
  145.             raise AuthError(req.get_full_url(), e.code, e.msg,
  146.                                    e.headers, response_dict)
  147.         else:
  148.             raise
  149.     """
  150.     auth_req = urllib2.Request(auth_uri, data=authreq_data)
  151.     auth_resp = urllib2.urlopen(auth_req)
  152.     auth_resp_body = auth_resp.read()
  153.     logging.info("authreq %s",auth_req)
  154.     logging.info("auth_resp %s",auth_resp)
  155.     logging.info("auth_resp_body %s",auth_resp_body)
  156.     auth_resp_dict = dict(x.split("=")for x in auth_resp_body.split("\n") if x)
  157.     authtoken = auth_resp_dict["Auth"]
  158.     return authtoken
  159.    """
  160. class AuthError(urllib2.HTTPError):
  161.     """Raised to indicate there was an error authenticating."""
  162.  
  163.     def __init__(self, url, code, msg, headers, args):
  164.         urllib2.HTTPError.__init__(self, url, code, msg, headers, None)
  165.         self.args = args
  166.         self.reason = args["Error"]
  167.  
  168. def get_opener(cookiejar=None):
  169.     opener = urllib2.OpenerDirector()
  170.     opener.add_handler(urllib2.ProxyHandler())
  171.     opener.add_handler(urllib2.UnknownHandler())
  172.     opener.add_handler(urllib2.HTTPHandler())
  173.     opener.add_handler(urllib2.HTTPDefaultErrorHandler())
  174.     opener.add_handler(urllib2.HTTPErrorProcessor())
  175.     opener.add_handler(urllib2.HTTPSHandler())
  176.     if cookiejar:
  177.         opener.add_handler(urllib2.HTTPCookieProcessor(cookiejar))
  178.     return opener
  179.  
  180.  
  181. def passwdFunc():
  182.   return (email, password)
  183.  
  184.    
  185. class TestSsoHandler(webapp2.RequestHandler):
  186.     def get(self):
  187.        
  188.         cookieString = do_auth(appname, email, password)
  189.         self.response.set_status(302, 'Use Cookie')
  190.        
  191.         self.response.headers['Cookie'] = cookieString[0]
  192.         self.response.headers['Location'] =  "/secured"
  193.        
  194.        
  195.              if users.get_current_user():
  196.             userEmail = users.get_current_user().email()
  197.             self.response.out.write("current user userEmail = "+userEmail)
  198.         else:
  199.             self.response.out.write("current user not found")
  200.            
  201. class OpenIDHandler(webapp2.RequestHandler):
  202.     def get(self):
  203.        
  204.         if users.get_current_user():
  205.             userEmail = users.get_current_user().email()
  206.             logging.info("current user userEmail = %s", userEmail)
  207.         else:
  208.             logging.info("current user : not found")
  209.            
  210.         self.redirect(users.create_login_url(self.request.uri))
  211.  
  212.  
  213. app.yaml
  214.  
  215. - url: /_ah/login_required
  216.   script: urlmapper.py
  217.  
  218. - url: /api\/.*\/?([a-z]*)
  219.   script: urlmapper.py  # TestSsoHandler
  220.  
  221. - url: /secured
  222.   static_files: index.html
  223.   upload: index.html
  224.   login: required
Advertisement
Add Comment
Please, Sign In to add comment