def test_registration(): """ Verify that authorizing the application will register a new user. """ client = Client() client.post( path = reverse('home'), data = { 'signed_request': TEST_SIGNED_REQUEST } ) user = User.objects.get(id=1) assert user.first_name == user.graph.get('me')['first_name'] assert user.middle_name == user.graph.get('me')['middle_name'] assert user.last_name == user.graph.get('me')['last_name'] assert user.url == user.graph.get('me')['link'] token = OAuthToken.objects.get(id=1) signed_request = SignedRequest.parse(TEST_SIGNED_REQUEST, TEST_APPLICATION_SECRET) assert token.token == signed_request.oauth_token.token assert token.issued_at == signed_request.oauth_token.issued_at assert token.expires_at == signed_request.oauth_token.expires_at
def teardown_module(module): """ Delete the Facebook test user. """ GraphAPI('%s|%s' % (TEST_APPLICATION_ID, TEST_APPLICATION_SECRET)).delete( path = SignedRequest.parse(TEST_SIGNED_REQUEST, TEST_APPLICATION_SECRET).user.id )
def teardown_module(module): """ Delete the Facebook test user. """ GraphAPI('%s|%s' % (TEST_APPLICATION_ID, TEST_APPLICATION_SECRET)).delete( path=SignedRequest.parse(TEST_SIGNED_REQUEST, TEST_APPLICATION_SECRET).user.id)
def facebook_show(request, app_id): try: fb_Access = Facebook_access.objects.get(facebook_app_id=app_id) except: hitting(request, 1501) # Stats return redirect('/error/1501') if 'signed_request' in request.REQUEST: signed_request = SignedRequest.parse(request.REQUEST.get('signed_request'), str(fb_Access.facebook_app_secret_key)) ################ Get Structure try: app = App.objects.get(facebook_access=fb_Access.id, campaign__facebook_page_id=signed_request['page']['id']) campaign = Campaign.objects.get(id=app.campaign_id) except: hitting(request, 1502) # Stats return redirect('/error/1502') liked = signed_request['page']['liked'] if not liked: if app.like_page == 1 and campaign.membership.like_page: return redirect(reverse('clients:app_show', args=[app.id, 'facebook', -1, -1])) return redirect(reverse('clients:app_show', args=[app.id, 'facebook'])) else: hitting(request, 1504) # Stats return redirect('/error/1504')
def test_generate_signed_request(): signed_request = SignedRequest.parse( signed_request=TEST_SIGNED_REQUEST, application_secret_key=TEST_FACEBOOK_APPLICATION_SECRET_KEY ) assert ( signed_request.user.oauth_token.token == "181259711925270|1570a553ad6605705d1b7a5f.1-499729129|8XqMRhCWDKtpG-i_zRkHBDSsqqk" ) assert signed_request.user.oauth_token.expires_at == None assert signed_request.user.oauth_token.issued_at assert signed_request.user.locale == "en_US" assert signed_request.user.country == "no" assert signed_request.user.age == range(21, 100) assert signed_request.user.id == "499729129" signed_request = signed_request.generate(TEST_FACEBOOK_APPLICATION_SECRET_KEY) assert ( signed_request == "_BI1k2IFKMlIqbUdtr85034LlIZxMu7iS1xF-K8pYkE=." "eyJ1c2VyX2lkIjoiNDk5NzI5MTI5IiwiYWxnb3JpdGhtI" "joiSE1BQy1TSEEyNTYiLCJleHBpcmVzIjowLCJvYXV0aF" "90b2tlbiI6IjE4MTI1OTcxMTkyNTI3MHwxNTcwYTU1M2F" "kNjYwNTcwNWQxYjdhNWYuMS00OTk3MjkxMjl8OFhxTVJo" "Q1dES3RwRy1pX3pSa0hCRFNzcXFrIiwidXNlciI6eyJsb" "2NhbGUiOiJlbl9VUyIsImNvdW50cnkiOiJubyIsImFnZS" "I6eyJtYXgiOjk5LCJtaW4iOjIxfX0sImlzc3VlZF9hdCI" "6MTMwNjE3OTkwNH0=" ) signed_request = SignedRequest.parse( signed_request=signed_request, application_secret_key=TEST_FACEBOOK_APPLICATION_SECRET_KEY ) assert ( signed_request.user.oauth_token.token == "181259711925270|1570a553ad6605705d1b7a5f.1-499729129|8XqMRhCWDKtpG-i_zRkHBDSsqqk" ) assert signed_request.user.oauth_token.expires_at == None assert signed_request.user.oauth_token.has_expired == False assert signed_request.user.oauth_token.issued_at assert signed_request.user.locale == "en_US" assert signed_request.user.country == "no" assert signed_request.user.age == range(21, 100) assert signed_request.user.id == "499729129" assert signed_request.user.has_authorized_application == True
def test_parse_signed_request(): signed_request = SignedRequest.parse( signed_request=TEST_SIGNED_REQUEST, application_secret_key=TEST_FACEBOOK_APPLICATION_SECRET_KEY ) assert signed_request.user.id == "499729129" assert signed_request.user.oauth_token.token == TEST_ACCESS_TOKEN assert signed_request.user.oauth_token.expires_at == None assert signed_request.user.oauth_token.issued_at
def test_parse_signed_request(): from facepy import SignedRequest from datetime import datetime signed_request = SignedRequest.parse(TEST_SIGNED_REQUEST, TEST_FACEBOOK_APPLICATION_SECRET_KEY) assert signed_request.user.id == '499729129' assert signed_request.oauth_token.token == TEST_ACCESS_TOKEN assert signed_request.oauth_token.expires_at == None assert signed_request.oauth_token.issued_at == datetime(2011, 5, 23, 21, 45, 4)
def post(self, request, *args, **kwargs): signed_request = request.POST.get("signed_request") signed_request = SignedRequest.parse(signed_request, FACEBOOK_APP_SECRET) self.data["fb"] = signed_request if "oauth_token" not in signed_request: self.data["oauth_url"] = get_auth_url() else: self.data["page_install_url"] = get_page_install_url() oauth_token = signed_request["oauth_token"] graph = GraphAPI(oauth_token) self.data["fb"]["user"] = graph.get("me") return self.render_to_response(self.data)
def test_create_signed_request(): from facepy import SignedRequest from datetime import datetime parsed_signed_request = SignedRequest.parse(TEST_SIGNED_REQUEST, TEST_FACEBOOK_APPLICATION_SECRET_KEY) assert parsed_signed_request.oauth_token.token == '181259711925270|1570a553ad6605705d1b7a5f.1-499729129|8XqMRhCWDKtpG-i_zRkHBDSsqqk' assert parsed_signed_request.oauth_token.expires_at == None assert parsed_signed_request.oauth_token.issued_at == datetime(2011, 5, 23, 21, 45, 4) assert parsed_signed_request.user.locale == 'en_US' assert parsed_signed_request.user.country == 'no' assert parsed_signed_request.user.age == range(21, 100) assert parsed_signed_request.user.id == '499729129' reverse_engineered_signed_request = parsed_signed_request.generate(TEST_FACEBOOK_APPLICATION_SECRET_KEY) assert reverse_engineered_signed_request == '_BI1k2IFKMlIqbUdtr85034LlIZxMu7iS1xF-K8pYkE=.' \ 'eyJ1c2VyX2lkIjoiNDk5NzI5MTI5IiwiYWxnb3JpdGhtI' \ 'joiSE1BQy1TSEEyNTYiLCJleHBpcmVzIjowLCJvYXV0aF' \ '90b2tlbiI6IjE4MTI1OTcxMTkyNTI3MHwxNTcwYTU1M2F' \ 'kNjYwNTcwNWQxYjdhNWYuMS00OTk3MjkxMjl8OFhxTVJo' \ 'Q1dES3RwRy1pX3pSa0hCRFNzcXFrIiwidXNlciI6eyJsb' \ '2NhbGUiOiJlbl9VUyIsImNvdW50cnkiOiJubyIsImFnZS' \ 'I6eyJtYXgiOjk5LCJtaW4iOjIxfX0sImlzc3VlZF9hdCI' \ '6MTMwNjE3OTkwNH0=' parsed_reverse_engineered_signed_request = SignedRequest.parse( signed_request = reverse_engineered_signed_request, application_secret_key = TEST_FACEBOOK_APPLICATION_SECRET_KEY ) assert parsed_reverse_engineered_signed_request.oauth_token.token == '181259711925270|1570a553ad6605705d1b7a5f.1-499729129|8XqMRhCWDKtpG-i_zRkHBDSsqqk' assert parsed_reverse_engineered_signed_request.oauth_token.expires_at == None assert parsed_reverse_engineered_signed_request.oauth_token.has_expired == False assert parsed_reverse_engineered_signed_request.oauth_token.issued_at == datetime(2011, 5, 23, 21, 45, 4) assert parsed_reverse_engineered_signed_request.user.locale == 'en_US' assert parsed_reverse_engineered_signed_request.user.country == 'no' assert parsed_reverse_engineered_signed_request.user.age == range(21, 100) assert parsed_reverse_engineered_signed_request.user.id == '499729129' assert parsed_reverse_engineered_signed_request.user.has_authorized_application == True
def post(self, request, *args, **kwargs): signed_request = request.POST.get("signed_request") signed_request = SignedRequest.parse(signed_request, FACEBOOK_APP_SECRET) self.data["fb"] = signed_request self.data["sig_rec"] = signed_request if "oauth_token" not in signed_request: self.data["oauth_url"] = get_auth_url() else: oauth_token = signed_request["oauth_token"] graph = GraphAPI(oauth_token) self.data["fb"]["user"] = graph.get(signed_request.get("page").get("id", 0)) request.session["admin"] = True request.session["token"] = oauth_token request.session["page_id"] = signed_request.get("page").get("id", 0) return self.render_to_response(self.data)
def test_parse_signed_request(): signed_request = SignedRequest.parse( signed_request = TEST_SIGNED_REQUEST, application_secret_key = TEST_FACEBOOK_APPLICATION_SECRET_KEY ) assert signed_request == { 'user_id': '499729129', 'algorithm': 'HMAC-SHA256', 'expires': 0, 'oauth_token': '181259711925270|1570a553ad6605705d1b7a5f.1-499729129|8XqMRhCWDKtpG-i_zRkHBDSsqqk', 'user': { 'locale': 'en_US', 'country': 'no', 'age': { 'min': 21 } }, 'issued_at': 1306179904 }
def post(self, request, *args, **kwargs): try: signed_request = request.POST['signed_request'] except (KeyError): return HttpResponse(status=400, content='Invalid request') try: signed_request_data = SignedRequest.parse( signed_request, settings.SOCIAL_AUTH_FACEBOOK_SECRET) except (SignedRequestError): return HttpResponse(status=400, content='Invalid request') user_id = signed_request_data['user_id'] try: user = UserSocialAuth.objects.get(uid=user_id, provider=facebook).user except (UserSocialAuth.DoesNotExist): return HttpResponse(status=400, content='Invalid request') user.update(is_active=False) return HttpResponse(status=201)
def compartilhar(request): dados = request.POST token = request.POST['token'] nome_time = request.POST['nome_time'] imagem = montar_imagem(dados, nome_time) if imagem == False: return HttpResponse("Nome de time invalido") tags = montar_marcacao(dados) tags = json.dumps(tags) signed_request = SignedRequest.parse(token, settings.FACEBOOK_APPLICATION_SECRET_KEY) graph = GraphAPI(signed_request['oauth_token']) post = graph.post(path="me/photos", tags=tags, message="Monte seu time de futebol com seus amigos!!! acesse: http://apps.facebook.com/maketeam", source=open(imagem)) return HttpResponse(json.dumps(post))
def _message_from_sr(self, token: Text, payload: Any) \ -> Optional[BaseMessage]: """ Tries to verify the signed request """ page = self.settings() secret = page['app_secret'] try: sr_data = SignedRequest.parse(token, secret) except (TypeError, ValueError, SignedRequestError) as e: return return self._make_fake_message( sr_data['psid'], page['page_id'], payload, )
def test_signed_request_renewal(): """ Verify that users are redirected to renew their signed requests once they expire. """ client = Client() signed_request = SignedRequest.parse(TEST_SIGNED_REQUEST, TEST_APPLICATION_SECRET) signed_request.oauth_token.expires_at = datetime.now() - timedelta(days=1) response = client.get(path=reverse('home'), data={ 'signed_request': signed_request.generate(TEST_APPLICATION_SECRET) }) # There's no way to derive the view the response originated from in Django, # so verifying its status code will have to suffice. assert response.status_code == 401
def test_parse_signed_request(): signed_request = SignedRequest.parse( signed_request=TEST_SIGNED_REQUEST, application_secret_key=TEST_FACEBOOK_APPLICATION_SECRET_KEY) assert signed_request == { 'user_id': '499729129', 'algorithm': 'HMAC-SHA256', 'expires': 0, 'oauth_token': '181259711925270|1570a553ad6605705d1b7a5f.1-499729129|8XqMRhCWDKtpG-i_zRkHBDSsqqk', 'user': { 'locale': 'en_US', 'country': 'no', 'age': { 'min': 21 } }, 'issued_at': 1306179904 }
def test_signed_request_renewal(): """ Verify that users are redirected to renew their signed requests once they expire. """ client = Client() signed_request = SignedRequest.parse(TEST_SIGNED_REQUEST, TEST_APPLICATION_SECRET) signed_request.oauth_token.expires_at = datetime.now() - timedelta(days=1) response = client.get( path = reverse('home'), data = { 'signed_request': signed_request.generate(TEST_APPLICATION_SECRET) } ) # There's no way to derive the view the response originated from in Django, # so verifying its status code will have to suffice. assert response.status_code == 303
def post(self, request, format=None): try: signed_request = json.loads(request.body)['signed_request'] signed_request_data = SignedRequest.parse(signed_request, settings.FB_APP_SECRET) except: return Response(status=status.HTTP_401_UNAUTHORIZED) try: user = models.User.objects.get( username=signed_request_data['psid']) except models.User.DoesNotExist: return Response(status=status.HTTP_401_UNAUTHORIZED) jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) token = {'token': token} return Response(data=token, status=status.HTTP_200_OK)
def loginExternal(self, externalType): ret = {} ret["status"] = "error" ret["errors"] = [] users = self.db['user'] progress = self.db['progress'] if externalType == "facebook": signedRequestToken = request.json.get("signedRequest") data = SignedRequest.parse(signedRequestToken, FACEBOOK_APP["secret"]) if not data or not "user_id" in data: ret["errors"].append({ "code": "ErrInvalidCredentials", "target": False }) if ret["errors"]: return ret externalId = request.json.get("externalId") if externalId != data['user_id']: ret["errors"].append({ "code": "ErrInvalidCredentials", "target": False }) if ret["errors"]: return ret accessToken = request.json.get("accessToken") if not accessToken: ret["errors"].append({ "code": "ErrInvalidCredentials", "target": False }) if ret["errors"]: return ret graph = GraphAPI(accessToken) if not graph: ret["errors"].append({ "code": "ErrInvalidCredentials", "target": False }) if ret["errors"]: return ret facebookUser = graph.get("me?fields=id,name,email") if not facebookUser or not "id" in facebookUser or not "name" in facebookUser or not "email" in facebookUser: ret["errors"].append({ "code": "ErrInvalidCredentials", "target": False }) if ret["errors"]: return ret if facebookUser['id'] != externalId: ret["errors"].append({ "code": "ErrInvalidCredentials", "target": False }) if ret["errors"]: return ret # okay, validation successful! user = users.find_one({ "$and": [{ "externalType": externalType }, { "externalId": externalId }] }) if not user: exists = users.find_one({"email": email}) if exists: ret["errors"].append({ "code": "ErrExistsEmailDifferentMethod", "target": False }) if ret["errors"]: return ret penName = facebookUser['name'] user = { "email": email, "penName": penName, "externalType": externalType, "externalId": externalId, "confirmed": True, "confirmDate": datetime.utcnow(), "subscribed": True, "insertDate": datetime.utcnow() } userId = users.insert_one(user).inserted_id if not userId: ret["errors"].append({ "code": "ErrInsertFailed", "target": False }) if ret["errors"]: return ret user = users.find_one({"_id": ObjectId(userId)}) else: ret["errors"].append({ "code": "ErrInvalidCredentials", "target": False }) return ret
def process_request(self, request): """Process the signed request.""" if ENABLED_PATHS and DISABLED_PATHS: raise ImproperlyConfigured('You may configure either FANDJANGO_ENABLED_PATHS or FANDJANGO_DISABLED_PATHS, but not both.') if DISABLED_PATHS and is_disabled_path(request.path): return if ENABLED_PATHS and not is_enabled_path(request.path): return # An error occured during authorization... if 'error' in request.GET: error = request.GET['error'] # The user refused to authorize the application... if error == 'access_denied': return authorization_denied_view(request) # Signed request found in either GET, POST or COOKIES... if 'signed_request' in request.REQUEST or 'signed_request' in request.COOKIES: request.facebook = Facebook() # If the request method is POST and its body only contains the signed request, # chances are it's a request from the Facebook platform and we'll override # the request method to HTTP GET to rectify their misinterpretation # of the HTTP standard. # # References: # "POST for Canvas" migration at http://developers.facebook.com/docs/canvas/post/ # "Incorrect use of the HTTP protocol" discussion at http://forum.developers.facebook.net/viewtopic.php?id=93554 if request.method == 'POST' and 'signed_request' in request.POST: request.POST = QueryDict('') request.method = 'GET' request.facebook.signed_request = SignedRequest.parse( signed_request = request.REQUEST.get('signed_request') or request.COOKIES.get('signed_request'), application_secret_key = FACEBOOK_APPLICATION_SECRET_KEY ) # User has authorized the application... if request.facebook.signed_request.user.has_authorized_application: # Redirect to Facebook Authorization if the OAuth token has expired if request.facebook.signed_request.oauth_token.has_expired: return authorize_application( request = request, redirect_uri = get_post_authorization_redirect_url(request) ) # Initialize a User object and its corresponding OAuth token try: user = User.objects.get(facebook_id=request.facebook.signed_request.user.id) except User.DoesNotExist: oauth_token = OAuthToken.objects.create( token = request.facebook.signed_request.oauth_token.token, issued_at = request.facebook.signed_request.oauth_token.issued_at, expires_at = request.facebook.signed_request.oauth_token.expires_at ) user = User.objects.create( facebook_id = request.facebook.signed_request.user.id, oauth_token = oauth_token ) user.synchronize() # Update the user's details and OAuth token else: user.last_seen_at = datetime.now() user.authorized = True if request.facebook.signed_request.oauth_token: user.oauth_token.token = request.facebook.signed_request.oauth_token.token user.oauth_token.issued_at = request.facebook.signed_request.oauth_token.issued_at user.oauth_token.expires_at = request.facebook.signed_request.oauth_token.expires_at user.oauth_token.save() user.save() # Attempt to extend the OAuth token, but ignore exceptions raised by # bug #102727766518358 in the Facebook Platform. # # http://developers.facebook.com/bugs/102727766518358/ try: user.oauth_token.extend() except: pass request.facebook.user = user # ... no signed request found. else: request.facebook = False
def process_request(self, request): """Process the signed request.""" from fandjango.views import authorize_application, authorization_denied from fandjango.models import Facebook, User, OAuthToken if ENABLED_PATHS and DISABLED_PATHS: raise ImproperlyConfigured('You may configure either FANDJANGO_ENABLED_PATHS or FANDJANGO_DISABLED_PATHS, but not both.') if DISABLED_PATHS and is_disabled_path(request.path): return if ENABLED_PATHS and not is_enabled_path(request.path): return # An error occured during authorization... if 'error' in request.GET: error = request.GET['error'] # The user refused to authorize the application... if error == 'access_denied': return authorization_denied_view(request) # Signed request found in either GET, POST or COOKIES... if 'signed_request' in request.REQUEST or 'signed_request' in request.COOKIES: request.facebook = Facebook() # If the request method is POST and its body only contains the signed request, # chances are it's a request from the Facebook platform and we'll override # the request method to HTTP GET to rectify their misinterpretation # of the HTTP standard. # # References: # "POST for Canvas" migration at http://developers.facebook.com/docs/canvas/post/ # "Incorrect use of the HTTP protocol" discussion at http://forum.developers.facebook.net/viewtopic.php?id=93554 if request.method == 'POST' and 'signed_request' in request.POST: request.POST = QueryDict('') request.method = 'GET' try: request.facebook.signed_request = SignedRequest.parse( signed_request = request.REQUEST.get('signed_request') or request.COOKIES.get('signed_request'), application_secret_key = FACEBOOK_APPLICATION_SECRET_KEY ) except: # Malformed or manipulated signed request request.facebook = False # Valid signed request and user has authorized the application if request.facebook and request.facebook.signed_request.user.has_authorized_application: # Redirect to Facebook Authorization if the OAuth token has expired if request.facebook.signed_request.oauth_token.has_expired: return authorize_application( request = request, redirect_uri = get_post_authorization_redirect_url(request) ) # Initialize a User object and its corresponding OAuth token try: user = User.objects.get(facebook_id=request.facebook.signed_request.user.id) except User.DoesNotExist: oauth_token = OAuthToken.objects.create( token = request.facebook.signed_request.oauth_token.token, issued_at = request.facebook.signed_request.oauth_token.issued_at, expires_at = request.facebook.signed_request.oauth_token.expires_at ) user = User.objects.create( facebook_id = request.facebook.signed_request.user.id, oauth_token = oauth_token ) user.synchronize() # Update the user's details and OAuth token else: user.last_seen_at = datetime.now() user.authorized = True if request.facebook.signed_request.oauth_token: user.oauth_token.token = request.facebook.signed_request.oauth_token.token user.oauth_token.issued_at = request.facebook.signed_request.oauth_token.issued_at user.oauth_token.expires_at = request.facebook.signed_request.oauth_token.expires_at user.oauth_token.save() user.save() if not user.oauth_token.extended: # Attempt to extend the OAuth token, but ignore exceptions raised by # bug #102727766518358 in the Facebook Platform. # # http://developers.facebook.com/bugs/102727766518358/ try: user.oauth_token.extend() except: pass request.facebook.user = user # ... no signed request found. else: request.facebook = False