def fb_current_user(self): """Returns the logged in Facebook user, or None if unconnected.""" if not hasattr(self, "_fb_current_user"): self._fb_current_user = None user_id = facebookoauth.parse_cookie(self.request.cookies.get("fb_user")) if user_id: self._fb_current_user = FBUser.get_by_key_name(user_id) return self._fb_current_user
def UserLoginHandler(self): """ This method offers username and logout_link to MainPage(). MainPage() would see if current uesr is logged in, or needed to log in. If current user shows 'no logged in', then we would provide login links to them which handled by AuthHandler(). If current user is logged in, then here we provide logout link, and it'd being a result to template_dict['url_link'] Two kind of account authorizations support: OpenID and Oauth2.0. * OpenID 1. GAE has built-in federated support. Yahoo and Google use it. * Oauth2.0 1. Facebook user: We use unofficial facebook python API - facebookoauth.py and changed it a bit for customization. http://github.com/pythonforfacebook/facebook-sdk (version 0.3.0) This API sets cookie(fb_user) to browser, and we use foauth.parse_cookie function to get it back from user's browser resource to identify your profile info (e.g. access_token or login status) 2. Sina weibo user: Similar as Facebook python API. When your click Weibo login icon on our page, we will deliver your to weibo authentication page to get access_token by OAuth2.0. Once authentication flow successful then we set "weibo_user" cookie on user's browser. When main page loaded, we would check weibo_user cookie by parse_cookie method which would decode cookie format and pull Weibo User's ID out. More detail check: weibo_oauth_v2.py line 112: 'weistr(weibo_user_profile.id)' weibo_oauth_v2.py line 142: set_cookie(self.response, "weibo_user", str(weibo_id), About the decode, you can check weibo_oauth_v2.py line 173 base64.b64decode(parts[0]).strip() Once we got Weibo user's ID, then we use it as datastore key_name to fetch its value(aka: Weibo username) from screen_name column. Finally, we use screen_name to determine user login or not. Return: dict: {logged in username:logout URL link} """ # Check OpenID/Federated user logged in or not. openid_username = users.get_current_user() # Check Facebook user logged in or not. if not hasattr(self, "_current_user"): self._current_user = None user_id = foauth.parse_cookie(self.request.cookies.get("fb_user")) if user_id: self._current_user = foauth.FacebookUser.get_by_key_name(user_id) facebook_user = self._current_user #Returns FacebookUser db entity # Check WeiBo user logged in or not. weibo_cookie = weibo_oauth_v2.parse_cookie(self.request.cookies.get("weibo_user")) if weibo_cookie: weibo_user_id = weibo_cookie weibo_user_ancestor = weibo_oauth_v2.WeiboUser.get_by_key_name(weibo_user_id) query = db.Query(weibo_user_ancestor) for name in query.fetch(1): weibo_screen_name = name.screen_name weibo_username = weibo_user_id + ':' + weibo_screen_name + '@weibo' else: weibo_username = None if openid_username: #openid_user_id = ':' + openid_username.user_id() #1111 openid_username = openid_username.user_id() + ':' + openid_username.email() #openid_username = openid_username.email().replace('@', openid_user_id) logging.info('%s logged in.' % openid_username) logout_link = users.create_logout_url(self.request.path) return {openid_username:logout_link} elif facebook_user: facebook_user = facebook_user.id + ':' + facebook_user.name + '@facebook' logging.info("%s logged in." % facebook_user) logout_link = '/oauth/facebook_logout' return {facebook_user:logout_link} elif weibo_username: logging.info("%s logged in." % weibo_username) url_link = '/oauth/weibo_logout' return {weibo_username:url_link} else: logging.info('We cant find username, redirect to login page.') return {}
def putwall(req,message,attachment): import facebookoauth from facebookoauth import FBUser import pprint, StringIO # prid=self.request.get('id') # prid="me" # args = dict(grant_type="client_credentials", client_id=FACEBOOK_APP_ID, client_secret=FACEBOOK_APP_SECRET) # response = cgi.parse_qs(urllib.urlopen("https://graph.facebook.com/oauth/access_token?" +urllib.urlencode(args)).read()) # access_token = response["access_token"][-1] #print access_token hout = "" user_id = facebookoauth.parse_cookie(req.request.cookies.get("fb_user")) errorjson = False aaa="<h2>wall post</h2>error" profile = {'id': 0} perm_mp=False perm_pa=False permtext="" cmd=req.request.get('cmd') oid=req.request.get('oid') if user_id: fb2_current_user = FBUser.get_by_key_name(user_id) if fb2_current_user and fb2_current_user.login: try: graph = GraphAPI(fb2_current_user.access_token) profile = graph.get_object("me") permissions = graph.request("/v2.1/me/permissions") for item in permissions["data"]: if item["permission"]=="manage_pages" and item["status"] == "granted": perm_mp=True if item["permission"]=="publish_actions" and item["status"] == "granted": perm_pa=True if not perm_mp: permtext = "manage_pages" if not perm_pa: permtext = permtext + " publish_actions" s = StringIO.StringIO() # pprint.pprint(permissions, s) # message = "Zinute patalpinta per\nhttp://www.nerij.us/fbputwall" # attachment = {} # attachment['name'] = "Nerijaus Terebo turinio valdymo sistemele \"Upelis\"" # attachment['caption'] = 'www.upelis.org' # attachment['link'] = 'http://www.upelis.org/' # attachment['picture'] = 'http://www.nerij.us/static/images/upelis116.jpg' # attachment['description'] = 'Turinio valdymo sistemele \"Upelis\" - Python, AppEngine' if cmd =="delperm": # mess = graph.delete_object(oid) # mess = graph.request(oid, post_args={"method": "delete"}) post_args=dict(method = "delete", access_token = fb2_current_user.access_token) post_data = urllib.urlencode(post_args) file = urllib.urlopen("https://graph.facebook.com/me/permissions" , post_data) try: response = json.loads(file.read()) finally: file.close() json.dump(response, s, sort_keys=True, indent=1) #pprint.pprint(response, s) hout=s.getvalue() aaa="<h2>permissions delete - ok </h2><pre>%s</pre>" % (hout) elif not perm_mp or not perm_pa: aaa="<h2>wall post - error - registruodamiesi nepatvirtinot: %s </h2><br><pre>%s</pre>" % (permtext,hout) else: if cmd =="delete": # mess = graph.delete_object(oid) # mess = graph.request(oid, post_args={"method": "delete"}) post_args=dict(method = "delete", access_token = fb2_current_user.access_token) post_data = urllib.urlencode(post_args) file = urllib.urlopen("https://graph.facebook.com/" + oid , post_data) try: response = json.loads(file.read()) finally: file.close() #pprint.pprint(response, s) json.dump(response, s, sort_keys=True, indent=1) hout=s.getvalue() aaa="<h2>wall post delete - ok </h2><pre>%s</pre>" % (hout) elif cmd =="info": mess = graph.request("/me/accounts") #pprint.pprint(mess, s) json.dump(mess, s, sort_keys=True, indent=1) hout=s.getvalue() aaa="<h2>accounts info</h2><p><pre>%s</pre></p>" % (hout) else: mess = graph.put_wall_post(message, attachment=attachment) #pprint.pprint(mess, s) json.dump(mess, s, sort_keys=True, indent=1) hout=s.getvalue() aaa="<h2>wall post - ok </h2><p><a href=\"/fbputwall?cmd=delete&oid=%s\">delete</a></p><pre>%s</pre>" % (mess["id"],hout) except Exception, e: errorjson = True errtext = cgi.escape(str(sys.exc_info()[0])) + ' ' + cgi.escape(str(sys.exc_info()[1])) + ' ' + cgi.escape(str(sys.exc_info()[2])) else: aaa="<h2>wall post</h2>not loged - <a href=\"/auth/login?continue=%s\">login</a>" % (urllib.quote(req.request.uri))