def _view(request, *args, **kwargs): # Make sure we're receiving a signed_request from facebook if not request.POST.get('signed_request'): return HttpResponseBadRequest('<h1>400 Bad Request</h1>' '<p>Missing <em>signed_request</em>.</p>') # Parse the request and ensure it's valid signed_request = request.POST["signed_request"] data = facebook.parse_signed_request(signed_request, settings.FACEBOOK_SECRET_KEY) if data is False: return HttpResponseBadRequest('<h1>400 Bad Request</h1>' '<p>Malformed <em>signed_request</em>.</p>') # If the user has not authorised redirect them if not data.get('user_id'): scope = getattr(settings, 'FACEBOOK_SCOPE', None) auth_url = facebook.auth_url(settings.FACEBOOK_APP_ID, settings.FACEBOOK_CANVAS_PAGE, scope) markup = ('<script type="text/javascript">' 'top.location.href="%s"</script>' % auth_url) return HttpResponse(markup) # Success so return the view return view_func(request, *args, **kwargs)
def process_request(self, request): """ Enables ``request.facebook`` and ``request.facebook.graph`` in your views once the user authenticated the application and connected with facebook. You might want to use this if you don't feel confortable with the javascript library. """ data = facebook.get_user_from_cookie(request.COOKIES, getattr(settings, 'FACEBOOK_APP_ID', settings.FACEBOOK_API_KEY), settings.FACEBOOK_SECRET_KEY) if data is None: # maybe OAuth 2 data = facebook.parse_signed_request( request.COOKIES.get( 'fbsr_' + getattr( settings, 'FACEBOOK_APP_ID', settings.FACEBOOK_API_KEY ), '', ), settings.FACEBOOK_SECRET_KEY, ) if data: data['uid'] = data['user_id'] else: data = None request.facebook = Facebook(data) return None
def decode_signed_request(signed_request): """Take the signed request and return the id and token.""" data = facebook.parse_signed_request(signed_request, config.FACEBOOK_APP_SECRET) if data: return data.get("user_id", None), data.get("oauth_token", None) else: return None, None
def _view(request, *args, **kwargs): # Make sure we're receiving a signed_request from facebook if not request.POST.get('signed_request'): return HttpResponseBadRequest( '<h1>400 Bad Request</h1>' '<p>Missing <em>signed_request</em>.</p>') # Parse the request and ensure it's valid signed_request = request.POST["signed_request"] data = facebook.parse_signed_request(signed_request, settings.FACEBOOK_SECRET_KEY) if data is False: return HttpResponseBadRequest( '<h1>400 Bad Request</h1>' '<p>Malformed <em>signed_request</em>.</p>') # If the user has not authorised redirect them if not data.get('user_id'): scope = getattr(settings, 'FACEBOOK_PERMS', None) auth_url = facebook.auth_url(settings.FACEBOOK_APP_ID, settings.FACEBOOK_CANVAS_PAGE, scope) markup = ('<script type="text/javascript">' 'top.location.href="%s"</script>' % auth_url) return HttpResponse(markup) # Success so return the view return view_func(request, *args, **kwargs)
def get(self): # Check signed request for uid uid = self.request.GET['userID'] signedRequest = self.request.GET['signedRequest'] if not uid or not signedRequest: return self.abort(400) parsed_request = facebook.parse_signed_request(self.request.GET['signedRequest'], FACEBOOK_APP_SECRET) if not parsed_request or uid != parsed_request['user_id']: return self.abort(403) try: result = facebook.get_access_token_from_code(parsed_request["code"], "", FACEBOOK_APP_ID, FACEBOOK_APP_SECRET) profile = facebook.GraphAPI(result['access_token']).get_object("me") except facebook.GraphAPIError: return self.abort(403) # Fetch existant user or create new one user = entities.User.get_by_key_name(profile['id']) if not user: api_key = ''. join(random.choice(string.hexdigits) for x in range(64)) user = entities.User(key_name = str(profile['id']), uid = int(profile['id']), first_name = profile['first_name'], last_name = profile['last_name'], api_key = api_key, access_token = result['access_token'], active = True) else: user.access_token = result['access_token'] user.put(); profile['api_key'] = user.api_key profile['access_token'] = user.access_token self.response.out.write(json.dumps(profile))
def _view(request, *args, **kwargs): # Make sure we're receiving a signed_request from facebook if not request.POST.get("signed_request"): if hasattr(settings, "FACEBOOK_RAISE_SR_EXCEPTIONS") and settings.FACEBOOK_RAISE_SR_EXCEPTIONS: raise MissingSignedRequestException("Signed request token missing") else: return HttpResponseBadRequest("<h1>400 Bad Request</h1>" "<p>Missing <em>signed_request</em>.</p>") # Parse the request and ensure it's valid signed_request = request.POST["signed_request"] data = facebook.parse_signed_request(signed_request, settings.FACEBOOK_SECRET_KEY) if data is False: if hasattr(settings, "FACEBOOK_RAISE_SR_EXCEPTIONS") and settings.FACEBOOK_RAISE_SR_EXCEPTIONS: raise InvalidSignedRequestException("Signed request token does not parse") else: return HttpResponseBadRequest( "<h1>400 Bad Request</h1>" "<p>Malformed <em>signed_request</em>.</p>" ) # If the user has not authorised redirect them if not data.get("user_id"): scope = getattr(settings, "FACEBOOK_SCOPE", None) auth_url = facebook.auth_url(settings.FACEBOOK_APP_ID, settings.FACEBOOK_CANVAS_PAGE, scope) markup = '<script type="text/javascript">' 'top.location.href="%s"</script>' % auth_url return HttpResponse(markup) # Success so return the view return view_func(request, *args, **kwargs)
def post(self, template = post_template): """just to see what is POST ed """ #TODO: rewrite this completly # NOTE rewriting this in the canvas handler log.debug(self.request.get("signed_request")) log.debug("Passed: " + template) try: # we use the facebook lib to parse the signed request fbdata = facebook.parse_signed_request(self.request.get("signed_request"), FACEBOOK_APP_SECRET) log.debug( fbdata ) # and we try to get the data of the user from our database current_user = User.get_by_key_name(fbdata["user_id"]) if not current_user: # Not an existing user so say not implemented yet and failback # to the normal page raise NotImplementedError, u"""This feature is in beta stage, login first using the standalone app in <a href="simpleapp-test.appspot.com>simpleapp-test.appspot.com</a>""" self.render(user = current_user) except Exception as e: log.error("Pokemon exception in HomeHandler") log.exception(e) import sys self.response.out.write(template.render(data = """ Sorry, we are still working on this, so there are some errors like: <br /> {0} """.format(repr(sys.exc_info())) ))
def test_parse_signed_request_when_correct(self): result = facebook.parse_signed_request(signed_request=self.cookie, app_secret=self.secret) self.assertTrue(result) self.assertTrue("issued_at" in result) self.assertTrue("code" in result) self.assertTrue("user_id" in result) self.assertTrue("algorithm" in result)
def deauthorize_callback(): signed_request = request.form['signed_request'] data = parse_signed_request(signed_request, app_secret=FB_APP_SECRET) uid = data['user_id'] user = User.get_by_id(uid) clear_friends_cache(user) user.delete() return ''
def test_parsing_valid_request(self): payload = '{"algorithm": "HMAC-SHA256", "user_id": "1234"}' signature = hmac.new("secret", base64.urlsafe_b64encode(payload), hashlib.sha256).digest() signed = self.make_signed_req(signature, payload) parsed = facebook.parse_signed_request(signed, "secret") self.assertEquals("1234", parsed.get("user_id", None))
def get_signed_request_data(request): """ Check for signed_request argument in request and parse it """ signed_request = request.POST.get("signed_request") if signed_request: return facebook.parse_signed_request(signed_request, settings.SECRET_KEY)
def test_parse_signed_request_when_correct(self): result = facebook.parse_signed_request(signed_request=self.cookie, app_secret=self.secret) self.assertTrue(result) self.assertTrue('issued_at' in result) self.assertTrue('code' in result) self.assertTrue('user_id' in result) self.assertTrue('algorithm' in result)
def signed_request(self): if not hasattr(self, '_signed_request'): signed_request = self.values.get('signed_request', None) if signed_request: self._signed_request = parse_signed_request( signed_request, current_app.config['FACEBOOK_SECRET'] ) else: self._signed_request = None return self._signed_request
def test_valid_signed_request_parse(self): """ Construct a valid signed request token, and run it through the parser """ assert( facebook.parse_signed_request( self.generate_sr_payload(self.secret), self.secret ) == self.TEST_PAYLOAD )
def test_parse_signed_request_when_correct(self): result = facebook.parse_signed_request( signed_request=self.cookie, app_secret=self.secret) self.assertTrue(result) self.assertTrue('issued_at' in result) self.assertTrue('code' in result) self.assertTrue('user_id' in result) self.assertTrue('algorithm' in result)
def test_invalid_signed_request_parse(self): """ Construct a signed request with an invalid secret, and run it through the parser """ assert( not facebook.parse_signed_request( self.generate_sr_payload('THISISANONSENSESECRETTOgenerateAfaIlIngToken'), self.secret ) )
def _get_fb_user_canvas(self, request): fb_user = None if request.POST.get('signed_request'): signed_request = request.POST["signed_request"] data = facebook.parse_signed_request(signed_request, settings.FACEBOOK_APP_SECRET) if data and data.get('user_id'): fb_user = data['user'] fb_user['method'] = 'canvas' fb_user['uid'] = data['user_id'] fb_user['access_token'] = data['oauth_token'] return fb_user
def get_fb_user_canvas(self, request): """ Attempt to find a user using a signed_request (canvas). """ fb_user = None if request.POST.get('signed_request'): signed_request = request.POST["signed_request"] data = facebook.parse_signed_request(signed_request, settings.FACEBOOK_SECRET_KEY) if data and data.get('user_id'): fb_user = data['user'] fb_user['method'] = 'canvas' fb_user['uid'] = data['user_id'] fb_user['access_token'] = data['oauth_token'] return fb_user
def test_parsing_invalid_requests_doesnt_throw(self, log_error): self.assertEquals({}, facebook.parse_signed_request("invalid", "secret")) self.assertSafeFail("not", "encoded properly!") self.assertSafeFail("notjson", "blah") self.assertSafeFail("notdict", "null") self.assertSafeFail("notdict", "[]") self.assertSafeFail("notHMAC256", "{}") self.assertSafeFail("stillnotHMAC256", '{"algorithm": "invalid"}') self.assertSafeFail("sigmismatch", '{"algorithm": "HMAC-SHA256"}') self.assertEquals(8, log_error.call_count)
def get_fb_user_canvas(self, request): """ Attempt to find a user using a signed_request (canvas). """ fb_user = None if request.POST.get("signed_request"): signed_request = request.POST["signed_request"] data = facebook.parse_signed_request(signed_request, settings.FACEBOOK_SECRET_KEY) if data and data.get("user_id"): fb_user = data["user"] fb_user["method"] = "canvas" fb_user["uid"] = data["user_id"] fb_user["access_token"] = data["oauth_token"] return fb_user
def _get_fb_user_canvas(self, request): fb_user = None if request.POST.get('signed_request'): signed_request = request.POST["signed_request"] data = facebook.parse_signed_request( signed_request, settings.FACEBOOK_APP_SECRET) if data and data.get('user_id'): fb_user = data['user'] fb_user['method'] = 'canvas' fb_user['uid'] = data['user_id'] fb_user['access_token'] = data['oauth_token'] return fb_user
def deauthorize_view(self): ''' Pinged by Facebook when a user removes the app. ''' ## Does not play well with Unicode strings. data = facebook.parse_signed_request( str(self.request.REQUEST['signed_request']), str(self.connect['app_secret']) ) account = FacebookAccount.objects.get(facebook_id=data['user_id']) account.access_token = None account.expires = None account.save() facebook_deauthorize.send(sender=FacebookAccount, account=account) return HttpResponse('OK')
def get_logged_in_user(): "Returns the logged in user or 'None' if no user is logged in" try: user_details = facebook.parse_signed_request( request.cookies['fbsr_' + app_id], app_key ) facebook_id = user_details['user_id'] g.facebook_user_details = user_details return User.query.filter_by(facebook_id = facebook_id).first() except (KeyError, TypeError): g.facebook_user_details = True return User.query.filter_by(facebook_id = 1101575668).first() return None
def get_third_party_auth(self, auth_type): """Wrangle and return authentication data from third parties; auth_type is either 'google' or 'facebook'. Returns a dictionary of user information, which will always contain the key 'auth_id'.""" if auth_type == 'google': gae_user = app_engine_users.get_current_user() if not gae_user: raise CredentialsMissing("No google login found.") user_kwargs = { 'auth_id': 'google_' + gae_user.user_id(), 'login_email': gae_user.email(), # 'name': gae_user.nickname(), } elif auth_type == 'facebook': signed_request = self.facebook_cookie() if not signed_request: raise CredentialsMissing("No facebook login found.") parsed_request = facebook.parse_signed_request( signed_request, config.FACEBOOK_APP_SECRET) if not parsed_request: raise Exception("Invalid facebook authentication.") # beware of broken connections to facebook here try: fb_user = facebook.get_user_from_cookie( self.request.cookies, config.FACEBOOK_APP_ID, config.FACEBOOK_APP_SECRET) except IOError: fb_user = None if fb_user: graph = facebook.GraphAPI(fb_user['access_token']) profile = graph.get_object('me') user_kwargs = { 'auth_id': 'facebook_' + fb_user['uid'], 'login_email': profile[u'username'] + '@facebook.com', 'first_name': profile[u'first_name'], 'last_name': profile[u'last_name'], 'name': profile[u'first_name'], } else: # The connection between PERTS and facebook is expired or has # been used with the GraphAPI already. So just return what we # know, which is their facebook user id user_kwargs = { 'auth_id': 'facebook_' + parsed_request['user_id'], } else: raise Exception("Invalid auth_type: {}.".format(auth_type)) return user_kwargs
def get_current_user(): cookie = request.cookies.get("fbsr_" + FB_APP_ID, "") if cookie: result = parse_signed_request(signed_request=cookie, app_secret=FB_APP_SECRET) if result: uid = result["user_id"] user = models.User.get_by_id(uid) if not user: user = models.User(id=uid) user.insert() g.uid = user.id g.user = user return g.uid = None g.user = None
def _get_canvas_user(self): """Attempt to get the Facebook user from a canvas signed_request.""" signed_request = request.form.get('signed_request', None) if signed_request is not None: try: app_secret = self.app.config['FACEBOOK_APP_SECRET'] data = facebook.parse_signed_request(signed_request, app_secret) except facebook.GraphAPIError as e: self.app.logger.error("Facebook Error: %s" % e) return None if data and 'user_id' in data: return dict(uid=data['user_id'], access_token=data['oauth_token']) return None
def api_login(): """ This endpoint receives a POST request from client-side login It performs validation of the returned token, creates a new account if needed, and logs the user in """ # request.json.keys() --> [u'expiresIn', u'userID', u'signedRequest', u'accessToken'] user_id = request.json['userID'] provider = 'facebook' app.logger.debug('Received signed request from user %s' % user_id) parsed_request = parse_signed_request(request.json['signedRequest'], app.config['FB_APP_SECRET']) if parsed_request: # The request was good, is this a new user? try: user = User.objects.get(id=user_id) new_user = False signal = user_logged_in except DoesNotExist: # Create an account for the user user = User(id=user_id) new_user = True signal = user_created # Save the access token token = AccessToken( provider=provider, access_token=request.json['accessToken'], ) user.access_tokens.append(token) user.save() # Log the user in login_user(user) # Run the signal handler. If new user, this will pull their profile signal.send(current_app._get_current_object(), user_id=user_id, provider=provider) # Return success return Response(json.dumps({'new_user': new_user}), status=201, mimetype='application/json') else: # The request failed to validate: log an error and return http 400 app.logger.warning('Signed request failed to validate, user %s' % user_id) return Response(json.dumps({ 'status': 'error', 'message': 'Signed request failed to authenticate' }), status=400, mimetype='application/json')
def read_user_token(): if request.method == "POST" and request.form.get('signed_request'): fb_request = facebook.parse_signed_request(request.form['signed_request'], app.config['APP_SECRET']) if u'user_id' in fb_request: session['user_id'] = fb_request[u'user_id'] session['oauth_token'] = fb_request[u'oauth_token'] session['expires'] = fb_request[u'expires'] return True else: return False if session.get('user_id'): expires = int(session[u'expires']) now = time.time() if expires > now: return True return False
def _post_index(request): query_string = request.META["QUERY_STRING"] redirect_uri = settings.FACEBOOK_CANVAS_PAGE if query_string: redirect_uri += ("?" + query_string) signed_request = request.POST["signed_request"] data = facebook.parse_signed_request( signed_request, settings.FACEBOOK_APP_SECRET) if not data.get("user_id"): scope = ["user_birthday", "user_location", "friends_birthday," "friends_hometown", "friends_location", "email", "publish_actions", "friends_online_presence"] auth_url = facebook.auth_url(settings.FACEBOOK_APP_ID, redirect_uri, scope) markup = ('<script type="text/javascript">' 'top.location.href="%s"</script>' % auth_url) return HttpResponse(markup) return None
def process_request(self, request): """ Enables ``request.facebook`` and ``request.facebook.get_graph`` in your views once the user authenticated the application and connected with facebook. You might want to use this if you don't feel confortable with the javascript library. """ # Try get the new OAuth cookie cookie = request.COOKIES.get('fbsr_%s' % APP_ID, '') data = facebook.parse_signed_request(cookie, SECRET_KEY) if not data: # Whoopsie, no new OAuth cookie. Maybe an old one? data = facebook.get_user_from_cookie(request.COOKIES, APP_ID, SECRET_KEY) request.facebook = Facebook(data or {}) return None
def get_fb_user_canvas(request): """ Attempt to find a user using a signed_request (canvas). """ signed_request = request.REQUEST.get('signed_request') if signed_request: data = facebook.parse_signed_request(signed_request, settings.SECRET_KEY) if data: if request.method == 'POST': # If this is requset method is POST then prevent rising err 403 # from Django CSRF middleware request.META["CSRF_COOKIE"] = _get_new_csrf_key() request.csrf_processing_done = True if data.get('user_id'): fb_user = data['user'] fb_user['method'] = 'canvas' fb_user['uid'] = data['user_id'] fb_user['access_token'] = data['oauth_token'] return fb_user
def post(self, **kwargs): #logging.info(self.request) signed_request = facebook.parse_signed_request(self.request.get('signed_request'),self.get_config('facebook','app_secret')) #logging.info(signed_request) try: user_id = signed_request['user_id'] except: user_id = None page_id = signed_request['page']['id'] liked = signed_request['page']['liked'] admin = signed_request['page']['admin'] options_dict = {} status = 'True' try: page = Page.get_by_key_name(page_id) #check active account or for expired account. if page.upgraded != '1': expire_date = page.created + datetime.timedelta(days=14) min_expire_date = datetime.datetime(2011,5,1) if (expire_date < min_expire_date): expire_date = min_expire_date if expire_date < datetime.datetime.now(): status = 'False' widgets = Widget.all().filter('page =', page).filter('deleted = ', False).order('order') options = Option.all().filter('type_reference =', page) for option in options: options_dict[option.name] = {'id': str(option.key().id()), 'value': option.value} except: page=None widgets=None options_dict = None self.render("app/fb-tab.html", page=page,widgets=widgets, method="post",options=options_dict,admin=admin,status=status)
def _post_index(request): query_string = request.META["QUERY_STRING"] redirect_uri = settings.FACEBOOK_CANVAS_PAGE if query_string: redirect_uri += ("?" + query_string) signed_request = request.POST["signed_request"] data = facebook.parse_signed_request(signed_request, settings.FACEBOOK_APP_SECRET) if not data.get("user_id"): scope = [ "user_birthday", "user_location", "friends_birthday," "friends_hometown", "friends_location", "email", "publish_actions", "friends_online_presence" ] auth_url = facebook.auth_url(settings.FACEBOOK_APP_ID, redirect_uri, scope) markup = ('<script type="text/javascript">' 'top.location.href="%s"</script>' % auth_url) return HttpResponse(markup) return None
def _view(request, *args, **kwargs): # Make sure we're receiving a signed_request from facebook if not request.POST.get('signed_request'): return HttpResponseBadRequest() # Parse the request and ensure it's valid try: signed_request = request.POST["signed_request"] data = facebook.parse_signed_request(signed_request, settings.FACEBOOK_SECRET_KEY) except ValueError: return HttpResponseBadRequest() # If the user has not authorised redirect them if not data.get('user_id'): scope = getattr(settings, 'FACEBOOK_PERMS', None) auth_url = facebook.auth_url(settings.FACEBOOK_APP_ID, settings.FACEBOOK_CANVAS_PAGE, scope) markup = '<script type="text/javascript">top.location.href="%s"</script>' % auth_url return HttpResponse(markup) # Success so return the view return view_func(request, *args, **kwargs)
def process_request(self, request): """ Add 'fb_signed_request' into the request context If no signed request was found, request.fb_signed_request will be None. Otherwise it will contain a dict object containing the contents of the signed_request. if a FB user is present, create request.facebook that contains the user. """ if request.POST.get('signed_request'): signed_request = request.POST["signed_request"] data = facebook.parse_signed_request(signed_request, settings.FACEBOOK_SECRET_KEY) if data: request.fb_signed_request = data else: request.fb_signed_request = None return None
def get(self): # Check signed request for uid uid = self.request.GET["userID"] signedRequest = self.request.GET["signedRequest"] if not uid or not signedRequest: return self.abort(400) parsed_request = facebook.parse_signed_request(self.request.GET["signedRequest"], FACEBOOK_APP_SECRET) if not parsed_request or uid != parsed_request["user_id"]: return self.abort(403) try: result = facebook.get_access_token_from_code( parsed_request["code"], "", FACEBOOK_APP_ID, FACEBOOK_APP_SECRET ) profile = facebook.GraphAPI(result["access_token"]).get_object("me") except facebook.GraphAPIError: return self.abort(403) # Fetch existant user or create new one user = entities.User.get_by_key_name(profile["id"]) if not user: api_key = "".join(random.choice(string.hexdigits) for x in range(64)) user = entities.User( key_name=str(profile["id"]), uid=int(profile["id"]), first_name=profile["first_name"], last_name=profile["last_name"], api_key=api_key, access_token=result["access_token"], active=True, ) else: user.access_token = result["access_token"] user.put() profile["api_key"] = user.api_key profile["access_token"] = user.access_token self.response.out.write(json.dumps(profile))
def test_parse_signed_request_when_erroneous(self): result = facebook.parse_signed_request( signed_request='corrupted.payload', app_secret=self.secret) self.assertFalse(result)
def parse_signed_request_cached(signed_request, secret): """Similar to facebook.parse_signed_request, but using the requestcache.""" return facebook.parse_signed_request(signed_request, secret)
def parse_signed_request(self, signed_request): return facebooklib.parse_signed_request(signed_request, self._app_secret)
def assertSafeFail(self, sig, payload): actual = facebook.parse_signed_request( self.make_signed_req(sig, payload), "secret") self.assertEquals({}, actual)