Facebook在AppEngine Python上“登录”(OAuth2)

时间:2012-05-04 09:13:03

标签: python facebook google-app-engine oauth-2.0

我有以下处理程序

首先,用户调用此Handler并重定向到Facebook:

class LoginFacebookHandler(BasicHandler):
    def get(self):
        user = self.auth.get_user_by_session()
        if not user:
            h = hashlib.new('sha512')
            h.update(str(datetime.now())+"abc")
            nonce = h.hexdigest()
            logging.info("hash "+str(nonce))
            memcache.set(str(nonce), True, 8600)
            #facebook_uri = "https://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=%s&state=%s&scope=%s" % ("20773", "http://upstrackapp.appspot.com/f", str(nonce), "email")
            data = {"client_id": 20773, "redirect_uri": "http://***.appspot.com/f", "state": str(nonce), "scope": "email"}
            facebook_uri = "https://www.facebook.com/dialog/oauth?%s" % (urllib.urlencode(data))
            self.redirect(facebook_uri)

在他授权我的应用facebook后重定向到重定向URI(处理程序):

class CreateUserFacebookHandler(BasicHandler):
    def get(self):
        state = self.request.get('state')
        code = self.request.get('code')
        logging.info("state "+state)
        logging.info("code "+code)
        if len(code) > 3 and len(state) > 3:
            cached_state = memcache.get(str(state))
            logging.info("cached_state "+str(cached_state))
            if cached_state:
                #memcache.delete(str(state))
                data = { "client_id": 20773, "redirect_uri": "http://***.appspot.com/f", "client_secret": "7f587", "code": str(code)}
                graph_url = "https://graph.facebook.com/oauth/access_token?%s" % (urllib.urlencode(data))
                logging.info("grph url "+graph_url)

                result = urlfetch.fetch(url=graph_url, method=urlfetch.GET)
                if result.status_code == 200:
                    fb_response = urlparse.parse_qs(result.content)
                    access_token = fb_response["access_token"][0]
                    token_expires = fb_response["expires"][0]
                    logging.info("access token "+str(access_token))
                    logging.info("token expires "+str(token_expires))
                    if access_token:
                        api_data = { "access_token": str(access_token)}
                        api_url = "https://graph.facebook.com/me?%s" % (urllib.urlencode(api_data))
                        logging.info("api url "+api_url)
                        api_result = urlfetch.fetch(url=api_url, method=urlfetch.GET)
                        if api_result.status_code == 200:
                            api_content = json.loads(api_result.content)
                            user_id = str(api_content["id"])
                            email = str(api_content["email"])
                            logging.info("user id "+str(user_id))
                            logging.info("email "+str(email))
                            h = hashlib.new('sha512')
                            h.update(str(user_id)+"abc")
                            password = h.hexdigest()
                            expire_data = datetime.now() + timedelta(seconds=int(token_expires))
                            user = self.auth.store.user_model.create_user(email, password_raw=password, access_token=access_token, token_expires=expire_data, fb_id=user_id)
                        else:
                            self.response.write.out.write("error contacting the graph api")
                    else:
                        self.response.out.write("access token not long enough")
                else:
                    self.response.out.write("error while contacting facebook server")
            else:
                self.response.out.write("error no cached state")
        else:
            self.response.out.write("error too short")

大多数情况下,这会一直有效,直到代码尝试检索access_token,我最终收到“联系时出错......”。 有趣的是,我记录了所有的URL,状态等等。所以我进入我的日志,复制并粘贴urlfetch试图打开的URL(fb api> access_token)将其粘贴到我的浏览器中,然后我得到了access_token +到期。 当代码尝试从图形中获取用户信息时,有时会发生同样的事情(graph / me)。

1 个答案:

答案 0 :(得分:1)

关键问题不是Facebook。 这是AppEngine部署过程。 我总是测试代码中的更改,而不是本地,因为OAuth无法正常工作。 因此deployment -> flush casche -> flush database进程似乎有一定的延迟导致工件保留,这使代码混乱。

因此,如果您必须测试OAuth live之类的内容,我建议将更改部署为应用程序的新版本,并在部署之后删除所有可能在新版本中充当工件的数据。