def test_sync_where_in_facebook_missing_in_facetools(self):
        from test_project.testapp3.facebook_test_users import facebook_test_users as t3
        facebook_test_users = t3()
        self.assertTrue(not all([u['installed'] for u in facebook_test_users])) # make sure all the users aren't set to have the app installed
        self.assertEquals(0, TestUser.objects.count())
        management.call_command('sync_facebook_test_users', 'testapp3')

        # Get the test user data from facebook
        test_users_url = "https://graph.facebook.com/%s/accounts/test-users?access_token=%s" % (settings.FACEBOOK_APPLICATION_ID, _get_app_access_token())
        test_users = _merge_with_facebook_data(facebook_test_users, json.loads(requests.get(test_users_url).content)['data'], _get_app_access_token())

        # Make sure the data looks good
        self.assertEquals(3, TestUser.objects.count())
        self.assertEquals(3, len(test_users))
        self.assertEquals(3, len([u for u in test_users if 'graph_user_data' in u]))

        # Now remove the users from facetools, leaving them on facebook
        TestUser.objects.all().delete()
        self.assertEquals(0, TestUser.objects.count())
        check_users = json.loads(requests.get(test_users_url).content)['data']
        old_ids = [u['graph_user_data']['id'] for u in test_users]
        self.assertEquals(3, len([c for c in check_users if c['id'] in old_ids]))

        # After syncing again the data should be back to normal
        management.call_command('sync_facebook_test_users', 'testapp3')
        test_users = _merge_with_facebook_data(facebook_test_users, json.loads(requests.get(test_users_url).content)['data'], _get_app_access_token())
        self.assertEquals(3, TestUser.objects.count())
        self.assertEquals(3, len(test_users))
        self.assertEquals(3, len([u for u in test_users if 'graph_user_data' in u]))

        # Make sure the generated fixture is correct
        self.assertTestUserFixture(testapp3, 'testapp3', t3())
def _merge_with_facebook_data(facebook_test_users, graph_test_users, access_token):
    """
    Creates a copy of the facebook_test_users dictionary, attaching each test user's user and permission data
    from the open graph api.
    """
    # Merge open graph data with the original facebook_test_users dictionary
    facebook_test_users = copy.deepcopy(facebook_test_users)
    for graph_test_user in graph_test_users:
        if 'id' in graph_test_user:
            facebook_id = graph_test_user['id']
            test_user_url = "https://graph.facebook.com/%s?access_token=%s" % (facebook_id, access_token)
            permissions_url = "https://graph.facebook.com/%s/permissions?access_token=%s" % (facebook_id, access_token)
            user_data = json.loads(requests.get(test_user_url).content)
            permissions_data = json.loads(requests.get(permissions_url).content)

            for facebook_test_user in facebook_test_users:
                if user_data and 'name' in user_data and facebook_test_user['name'] == user_data['name']:
                    facebook_test_user['access_token'] = graph_test_user.get('access_token')
                    facebook_test_user['graph_user_data'] = user_data
                    facebook_test_user['graph_user_data']['login_url'] = graph_test_user['login_url']
                    facebook_test_user['graph_permission_data'] = permissions_data if 'data' in permissions_data else None

    # Remove any test users that didn't recieve any data from open graph
    test_users = []
    for test_user in facebook_test_users:
        if 'graph_user_data' in test_user and 'graph_permission_data' in test_user:
            test_users.append(test_user)

    return test_users
Ejemplo n.º 3
0
    def test_sync_where_in_facebook_and_in_facetools_but_data_not_synced(self):
        from test_project.testapp3.facebook_test_users import facebook_test_users as t3
        facebook_test_users = t3()
        self.assertEquals(0, TestUser.objects.count())
        management.call_command('sync_facebook_test_users', 'testapp3')

        # Get the test user data from facebook
        test_users_url = "https://graph.facebook.com/%s/accounts/test-users?access_token=%s" % (
            settings.FACEBOOK_APPLICATION_ID, _get_app_access_token())
        test_users = _merge_with_facebook_data(
            facebook_test_users,
            json.loads(requests.get(test_users_url).content)['data'],
            _get_app_access_token())

        # Make sure the data looks good
        self.assertEquals(3, TestUser.objects.count())
        self.assertEquals(3, len(test_users))
        self.assertEquals(
            3, len([u for u in test_users if 'graph_user_data' in u]))

        # Now change the user data on facetools, leaving them out of sync with the facebook data
        old_values = {}
        try:
            for test_user in TestUser.objects.all():
                old_values[test_user.name] = {
                    'facebook_id': test_user.facebook_id,
                    'access_token': test_user.access_token
                }
                test_user.facebook_id = 0
                test_user.access_token = "failbear"
                test_user.save()

            # After syncing again the data should be back to normal
            management.call_command('sync_facebook_test_users', 'testapp3')
            test_users = _merge_with_facebook_data(
                facebook_test_users,
                json.loads(requests.get(test_users_url).content)['data'],
                _get_app_access_token())
            self.assertEquals(3, TestUser.objects.count())
            self.assertEquals(3, len(test_users))
            self.assertEquals(
                3, len([u for u in test_users if 'graph_user_data' in u]))
            for test_user in TestUser.objects.all():
                self.assertNotEquals(0, test_user.facebook_id)
                self.assertNotEquals("failbear", test_user.access_token)
        finally:
            for test_user in TestUser.objects.all():
                test_user.facebook_id = old_values[
                    test_user.name]['facebook_id']
                test_user.access_token = old_values[
                    test_user.name]['access_token']
                test_user.save()

        # Make sure the generated fixture is correct
        self.assertTestUserFixture(testapp3, 'testapp3', t3())
def _get_existing_facebook_test_users(
        app_id=settings.FACEBOOK_APPLICATION_ID,
        app_secret=settings.FACEBOOK_APPLICATION_SECRET_KEY):
    """
    Get the facebook data for each test user defined for the app.
    """
    existing_facebook_test_users = {}
    app_access_token = '%s|%s' % (app_id, app_secret)
    test_users_url = "https://graph.facebook.com/%s/accounts/test-users?access_token=%s" % (
        app_id, app_access_token)
    for attempts in range(3, 0, -1):
        response = requests.get(test_users_url)
        try:
            users_response_data = json.loads(response.content)
        except:
            users_response_data = None
        if response.status_code != 200 or users_response_data is None or users_response_data == False or 'error' in users_response_data:
            if attempts > 0:
                continue
            try:
                raise Exception(
                    "Error retrieving facebook app's test users: %s" %
                    users_response_data['error']['message'])
            except:
                try:
                    raise Exception(
                        "Error retrieving facebook app's test users: status_code=%s, content=\"%s\""
                        % (response.status_code, response.content))
                except:
                    raise Exception(
                        "Error retrieving facebook app's test users: status_code=%s"
                        % response.status_code)
        else:
            break

    test_user_url = "https://graph.facebook.com/%s?access_token=%s"
    for test_user in users_response_data['data']:
        user_response_data = json.loads(
            requests.get(test_user_url %
                         (test_user['id'], app_access_token)).content)
        if user_response_data == False:
            # skip invalid users defined on facebook
            continue
        if 'error' in user_response_data:
            raise Exception(
                "Error retrieving data for %s: %s" %
                (test_user['id'], user_response_data['error']['message']))
        elif 'name' in user_response_data:
            user_response_data['access_token'] = test_user.get('access_token')
            user_response_data['login_url'] = test_user.get('login_url')
            existing_facebook_test_users[
                user_response_data['name']] = user_response_data

    return existing_facebook_test_users
Ejemplo n.º 5
0
    def test_fandjango_users_created_correctly(self):
        from test_project.testapp3.facebook_test_users import facebook_test_users as t3
        facebook_test_users = t3()
        self.assertTrue(not all([
            u['installed'] for u in facebook_test_users
        ]))  # make sure all the users aren't set to have the app installed
        management.call_command('sync_facebook_test_users', 'testapp3')

        # Get the test user data from facebook
        test_users_url = "https://graph.facebook.com/%s/accounts/test-users?access_token=%s" % (
            settings.FACEBOOK_APPLICATION_ID, _get_app_access_token())
        test_users = _merge_with_facebook_data(
            facebook_test_users,
            json.loads(requests.get(test_users_url).content)['data'],
            _get_app_access_token())

        # Make sure only the test users that have the app installed have correpsonding Fandjango User records
        self.assertEquals(2, User.objects.count())
        for test_user in test_users:
            if test_user['installed']:
                user = User.objects.get(
                    facebook_id=int(test_user['graph_user_data']['id']))
                self.assertEquals(test_user['access_token'],
                                  user.oauth_token.token)
            else:
                self.assertEquals(
                    0,
                    User.objects.filter(facebook_id=int(
                        test_user['graph_user_data']['id'])).count())
    def test_sync_multiple_apps(self):
        from test_project.testapp1.facebook_test_users import facebook_test_users as t1
        from test_project.testapp2.facebook_test_users import facebook_test_users as t2
        facebook_test_users = t1 + t2()
        self.assertEquals(0, TestUser.objects.count())
        management.call_command('sync_facebook_test_users', 'testapp1', 'testapp2')

        # Get the test user data from facebook
        test_users_url = "https://graph.facebook.com/%s/accounts/test-users?access_token=%s" % (settings.FACEBOOK_APPLICATION_ID, _get_app_access_token())
        test_users = _merge_with_facebook_data(facebook_test_users, json.loads(requests.get(test_users_url).content)['data'], _get_app_access_token())

        # Make sure each test user's information on facebook is correct
        self.assertEquals(4, len(test_users))
        self.assertEquals(4, len([u for u in test_users if 'graph_user_data' in u and 'graph_permission_data' in u]))
        for test_user in test_users:
            for permission in test_user['permissions']:
                self.assertTrue(permission.strip() in test_user['graph_permission_data']['data'][0])
            friends_on_facebook = _get_friends_on_facebook(test_user)
            for friend_name in test_user.get('friends', []):
                self.assertTrue(friend_name in friends_on_facebook)
                self.assertEqual(friends_on_facebook[friend_name],
                                 TestUser.objects.get(name=friend_name).facebook_id)

        # Make sure each test user's information in facetools is correct
        self.assertEquals(4, TestUser.objects.count())
        for user in TestUser.objects.all():
            test_user = [t for t in test_users if int(t['graph_user_data']['id']) == user.facebook_id][0]
            self.assertEquals(test_user['name'], user.name)
            self.assertEquals(test_user['graph_user_data']['login_url'], user.login_url)
            self.assertEquals(test_user['installed'], _has_access_code(user.access_token))

        # Make sure the generated fixture is correct
        self.assertTestUserFixture(testapp1, 'testapp1', t1)
        self.assertTestUserFixture(testapp2, 'testapp2', t2())
Ejemplo n.º 7
0
def _parse_signed_request(signed_request, app_secret):
    """Return dictionary with signed request data."""
    try:
        l = signed_request.split('.', 2)
        encoded_sig = str(l[0])
        payload = str(l[1])
    except IndexError:
        raise ValueError("Signed request malformed")

    sig = base64.urlsafe_b64decode(encoded_sig + "=" *
                                   ((4 - len(encoded_sig) % 4) % 4))
    data = base64.urlsafe_b64decode(payload + "=" *
                                    ((4 - len(payload) % 4) % 4))

    data = json.loads(data)

    if data.get('algorithm').upper() != 'HMAC-SHA256':
        raise ValueError("Signed request is using an unknown algorithm")
    else:
        expected_sig = hmac.new(app_secret,
                                msg=payload,
                                digestmod=hashlib.sha256).digest()

    if sig != expected_sig:
        raise ValueError("Signed request signature mismatch")
    else:
        return data
    def test_overwriting_many_users_mixed_installations(self):
        from test_project.testapp3.facebook_test_users import facebook_test_users as t3
        facebook_test_users = t3()
        self.assertTrue(not all([u['installed'] for u in facebook_test_users])) # make sure all the users aren't set to have the app installed
        self.assertEquals(0, TestUser.objects.count())
        management.call_command('sync_facebook_test_users', 'testapp3')
        management.call_command('sync_facebook_test_users', 'testapp3')

        # Get the test user data from facebook
        test_users_url = "https://graph.facebook.com/%s/accounts/test-users?access_token=%s" % (settings.FACEBOOK_APPLICATION_ID, _get_app_access_token())
        test_users = _merge_with_facebook_data(facebook_test_users, json.loads(requests.get(test_users_url).content)['data'], _get_app_access_token())

        # Make sure each test user's information on facebook is correct
        self.assertEquals(3, len(test_users))
        self.assertEquals(3, len([u for u in test_users if 'graph_user_data' in u and 'graph_permission_data' in u]))
        for test_user in test_users:
            for permission in test_user['permissions']:
                self.assertTrue(permission.strip() in test_user['graph_permission_data']['data'][0])
            friends_on_facebook = _get_friends_on_facebook(test_user)
            for friend_name in test_user.get('friends', []):
                self.assertTrue(friend_name in friends_on_facebook)
                self.assertEqual(friends_on_facebook[friend_name],
                                 TestUser.objects.get(name=friend_name).facebook_id)

        # Make sure each test user's information in facetools is correct
        self.assertEquals(3, TestUser.objects.count())
        for user in TestUser.objects.all():
            test_user = [t for t in test_users if t['graph_user_data']['id'] == str(user.facebook_id)][0]
            self.assertEquals(test_user['name'], user.name)
            self.assertEquals(test_user['graph_user_data']['login_url'], user.login_url)
            self.assertEquals(test_user['installed'], _has_access_code(user.access_token))

        # Make sure the generated fixture is correct
        self.assertTestUserFixture(testapp3, 'testapp3', t3())
    def test_overwrite_one_user(self):
        from test_project.testapp1.facebook_test_users import facebook_test_users
        self.assertEquals(0, TestUser.objects.count())
        management.call_command('sync_facebook_test_users', 'testapp1')
        management.call_command('sync_facebook_test_users', 'testapp1')

        # Get the test user data from facebook
        test_users_url = "https://graph.facebook.com/%s/accounts/test-users?access_token=%s" % (
            settings.FACEBOOK_APPLICATION_ID, _get_app_access_token())
        api_test_users = json.loads(requests.get(test_users_url).content)['data']
        test_users = _merge_with_facebook_data(facebook_test_users, api_test_users, _get_app_access_token())

        # Make sure the test user's information on facebook is correct
        self.assertEquals(1, len(test_users))
        self.assertEquals(1, len([u for u in test_users if u.get('graph_user_data') and u.get('graph_permission_data')]))
        self.assertEquals(1, len([u for u in api_test_users if 'id' in u and u['id'] == test_users[0]['graph_user_data']['id']]))
        for permission in test_users[0]['permissions']:
            self.assertTrue(permission.strip() in test_users[0]['graph_permission_data']['data'][0])

        # Make sure the test user's information in facetools is correct
        self.assertEquals(1, TestUser.objects.count())
        user = TestUser.objects.get()
        self.assertEquals(int(test_users[0]['graph_user_data']['id']), user.facebook_id)
        self.assertEquals(test_users[0]['graph_user_data']['name'], user.name)
        self.assertEquals(test_users[0]['graph_user_data']['login_url'], user.login_url)
        self.assertEquals(test_users[0]['installed'], _has_access_code(user.access_token))

        # Make sure the generated fixture is correct
        self.assertTestUserFixture(testapp1, 'testapp1', facebook_test_users)
 def assertTestUserFixture(self, app, app_name, test_users):
     fixture_file_path = os.path.join(_get_app_fixture_directory(app),
                                      _get_facetools_test_fixture_name(app_name))
     fixture_test_users = json.loads(open(fixture_file_path).read())
     fixture_user_names = set([u['pk'] for u in fixture_test_users])
     expected_user_names = set([u['name'] for u in test_users])
     self.assertEquals(expected_user_names, fixture_user_names)
Ejemplo n.º 11
0
 def assertTestUserFixture(self, app, app_name, test_users):
     fixture_file_path = os.path.join(
         _get_app_fixture_directory(app),
         _get_facetools_test_fixture_name(app_name))
     fixture_test_users = json.loads(open(fixture_file_path).read())
     fixture_user_names = set([u['pk'] for u in fixture_test_users])
     expected_user_names = set([u['name'] for u in test_users])
     self.assertEquals(expected_user_names, fixture_user_names)
Ejemplo n.º 12
0
    def test_sync_where_in_facetools_missing_in_facebook(self):
        from test_project.testapp3.facebook_test_users import facebook_test_users as t3
        facebook_test_users = t3()
        self.assertTrue(not all([
            u['installed'] for u in facebook_test_users
        ]))  # make sure all the users aren't set to have the app installed
        self.assertEquals(0, TestUser.objects.count())
        management.call_command('sync_facebook_test_users', 'testapp3')

        # Get the test user data from facebook
        test_users_url = "https://graph.facebook.com/%s/accounts/test-users?access_token=%s" % (
            settings.FACEBOOK_APPLICATION_ID, _get_app_access_token())
        test_users = _merge_with_facebook_data(
            facebook_test_users,
            json.loads(requests.get(test_users_url).content)['data'],
            _get_app_access_token())

        # Make sure the data looks good
        self.assertEquals(3, TestUser.objects.count())
        self.assertEquals(3, len(test_users))
        self.assertEquals(
            3, len([u for u in test_users if 'graph_user_data' in u]))

        # Now remove the users from facebook, leaving them in facetools database
        for test_user in test_users:
            _delete_test_user_on_facebook(
                TestUser.objects.get(name=test_user['name']))
        self.assertEquals(3, TestUser.objects.count())
        check_users = json.loads(requests.get(test_users_url).content)['data']
        old_ids = [u['graph_user_data']['id'] for u in test_users]
        self.assertTrue(not any([c['id'] in old_ids for c in check_users]))

        # After syncing again the data should be back to normal
        management.call_command('sync_facebook_test_users', 'testapp3')
        test_users = _merge_with_facebook_data(
            facebook_test_users,
            json.loads(requests.get(test_users_url).content)['data'],
            _get_app_access_token())
        self.assertEquals(3, TestUser.objects.count())
        self.assertEquals(3, len(test_users))
        self.assertEquals(
            3, len([u for u in test_users if 'graph_user_data' in u]))

        # Make sure the generated fixture is correct
        self.assertTestUserFixture(testapp3, 'testapp3', t3())
def _get_friends_on_facebook(test_user):
    friends_url = "https://graph.facebook.com/%s/friends?access_token=%s" % (test_user['graph_user_data']['id'], _get_app_access_token())
    friends_data = json.loads(requests.get(friends_url).content)
    friends = {}
    if type(friends_data) is not bool and 'data' in friends_data:
        for friend in friends_data['data']:
            friends[friend['name']] = int(friend['id'])
        assert len(friends) == len(friends_data['data'])
    return friends
    def test_sync_where_in_facebook_and_in_facetools_but_data_not_synced(self):
        from test_project.testapp3.facebook_test_users import facebook_test_users as t3
        facebook_test_users = t3()
        self.assertEquals(0, TestUser.objects.count())
        management.call_command('sync_facebook_test_users', 'testapp3')

        # Get the test user data from facebook
        test_users_url = "https://graph.facebook.com/%s/accounts/test-users?access_token=%s" % (settings.FACEBOOK_APPLICATION_ID, _get_app_access_token())
        test_users = _merge_with_facebook_data(facebook_test_users, json.loads(requests.get(test_users_url).content)['data'], _get_app_access_token())

        # Make sure the data looks good
        self.assertEquals(3, TestUser.objects.count())
        self.assertEquals(3, len(test_users))
        self.assertEquals(3, len([u for u in test_users if 'graph_user_data' in u]))

        # Now change the user data on facetools, leaving them out of sync with the facebook data
        old_values = {}
        try:
            for test_user in TestUser.objects.all():
                old_values[test_user.name] = {
                    'facebook_id': test_user.facebook_id,
                    'access_token': test_user.access_token
                }
                test_user.facebook_id = 0
                test_user.access_token = "failbear"
                test_user.save()

            # After syncing again the data should be back to normal
            management.call_command('sync_facebook_test_users', 'testapp3')
            test_users = _merge_with_facebook_data(facebook_test_users, json.loads(requests.get(test_users_url).content)['data'], _get_app_access_token())
            self.assertEquals(3, TestUser.objects.count())
            self.assertEquals(3, len(test_users))
            self.assertEquals(3, len([u for u in test_users if 'graph_user_data' in u]))
            for test_user in TestUser.objects.all():
                self.assertNotEquals(0, test_user.facebook_id)
                self.assertNotEquals("failbear", test_user.access_token)
        finally:
            for test_user in TestUser.objects.all():
                test_user.facebook_id = old_values[test_user.name]['facebook_id']
                test_user.access_token = old_values[test_user.name]['access_token']
                test_user.save()

        # Make sure the generated fixture is correct
        self.assertTestUserFixture(testapp3, 'testapp3', t3())
Ejemplo n.º 15
0
def _get_friends_on_facebook(test_user):
    friends_url = "https://graph.facebook.com/%s/friends?access_token=%s" % (
        test_user['graph_user_data']['id'], _get_app_access_token())
    friends_data = json.loads(requests.get(friends_url).content)
    friends = {}
    if type(friends_data) is not bool and 'data' in friends_data:
        for friend in friends_data['data']:
            friends[friend['name']] = int(friend['id'])
        assert len(friends) == len(friends_data['data'])
    return friends
Ejemplo n.º 16
0
def _create_test_user_on_facebook(app_installed=True,
                                  name=None,
                                  permissions=None,
                                  access_token=None):
    """
    Creates a test user on facebook.  Returns a dict of the json response from facebook.
    """
    test_user_template = "https://graph.facebook.com/%s/accounts/test-users?installed=%s&permissions=%s&method=post&access_token=%s"

    # Generate the request URL
    if app_installed == True:
        app_installed = "true"
    else:
        app_installed = "false"
    if permissions is None:
        permissions = settings.FACEBOOK_APPLICATION_INITIAL_PERMISSIONS
    permissions = _create_permissions_string(permissions)
    if access_token is None:
        access_token = _get_app_access_token()
    test_user_url = test_user_template % (settings.FACEBOOK_APPLICATION_ID,
                                          app_installed, permissions,
                                          access_token)
    if name:
        test_user_url = '%s&name=%s' % (test_user_url, urllib.quote(name))

    # Request a new test user from facebook
    for attempts in range(3, 0, -1):
        r = requests.get(test_user_url)
        try:
            data = json.loads(r.content)
        except:
            data = None
        if r.status_code != 200 or data is None or data == False or 'error' in data:
            continue
        return data
    else:
        try:
            raise CreateTestUserError(data['error']['message'])
        except CreateTestUserError:
            raise
        except:
            try:
                raise CreateTestUserError(
                    "Request to create test user failed (status_code=%s and content=\"%s\")"
                    % (r.status_code, r.content))
            except CreateTestUserError:
                raise
            except:
                raise CreateTestUserError(
                    "Request to create test user failed (status_code=%s)" %
                    r.status_code)
    raise CreateTestUserError("Request to create test user failed")
Ejemplo n.º 17
0
    def test_sync_all_apps(self):
        from test_project.testapp1.facebook_test_users import facebook_test_users as t1
        from test_project.testapp2.facebook_test_users import facebook_test_users as t2
        from test_project.testapp3.facebook_test_users import facebook_test_users as t3
        facebook_test_users = t1 + t2() + t3()
        self.assertEquals(0, TestUser.objects.count())
        management.call_command('sync_facebook_test_users')

        # Get the test user data from facebook
        test_users_url = "https://graph.facebook.com/%s/accounts/test-users?access_token=%s" % (
            settings.FACEBOOK_APPLICATION_ID, _get_app_access_token())
        test_users = _merge_with_facebook_data(
            facebook_test_users,
            json.loads(requests.get(test_users_url).content)['data'],
            _get_app_access_token())

        # Make sure each test user's information on facebook is correct
        self.assertEquals(7, len(test_users))
        self.assertEquals(
            7,
            len([
                u for u in test_users
                if 'graph_user_data' in u and 'graph_permission_data' in u
            ]))
        for test_user in test_users:
            for permission in test_user['permissions']:
                self.assertTrue(permission.strip() in
                                test_user['graph_permission_data']['data'][0])
            friends_on_facebook = _get_friends_on_facebook(test_user)
            for friend_name in test_user.get('friends', []):
                self.assertTrue(friend_name in friends_on_facebook)
                self.assertEqual(
                    friends_on_facebook[friend_name],
                    TestUser.objects.get(name=friend_name).facebook_id)

        # Make sure each test user's information in facetools is correct
        self.assertEquals(7, TestUser.objects.count())
        for user in TestUser.objects.all():
            test_user = [
                t for t in test_users
                if int(t['graph_user_data']['id']) == user.facebook_id
            ][0]
            self.assertEquals(test_user['name'], user.name)
            self.assertEquals(test_user['graph_user_data']['login_url'],
                              user.login_url)
            self.assertEquals(test_user['installed'],
                              _has_access_code(user.access_token))

        # Make sure the generated fixture is correct
        self.assertTestUserFixture(testapp1, 'testapp1', t1)
        self.assertTestUserFixture(testapp2, 'testapp2', t2())
        self.assertTestUserFixture(testapp3, 'testapp3', t3())
def _get_existing_facebook_test_users(app_id=settings.FACEBOOK_APPLICATION_ID, app_secret=settings.FACEBOOK_APPLICATION_SECRET_KEY):
    """
    Get the facebook data for each test user defined for the app.
    """
    existing_facebook_test_users = {}
    app_access_token = '%s|%s' % (app_id, app_secret)
    test_users_url = "https://graph.facebook.com/%s/accounts/test-users?access_token=%s" % (app_id, app_access_token)
    for attempts in range(3, 0, -1):
        response = requests.get(test_users_url)
        try: users_response_data = json.loads(response.content)
        except: users_response_data = None
        if response.status_code != 200 or users_response_data is None or users_response_data == False or 'error' in users_response_data:
            if attempts > 0:
                continue
            try:
                raise Exception("Error retrieving facebook app's test users: %s" % users_response_data['error']['message'])
            except:
                try:
                    raise Exception("Error retrieving facebook app's test users: status_code=%s, content=\"%s\"" % (response.status_code, response.content))
                except:
                    raise Exception("Error retrieving facebook app's test users: status_code=%s" % response.status_code)
        else:
            break

    test_user_url = "https://graph.facebook.com/%s?access_token=%s"
    for test_user in users_response_data['data']:
        user_response_data = json.loads(requests.get(test_user_url % (test_user['id'], app_access_token)).content)
        if user_response_data == False:
            # skip invalid users defined on facebook
            continue
        if 'error' in user_response_data:
            raise Exception("Error retrieving data for %s: %s" % (test_user['id'], user_response_data['error']['message']))
        elif 'name' in user_response_data:
            user_response_data['access_token'] = test_user.get('access_token')
            user_response_data['login_url'] = test_user.get('login_url')
            existing_facebook_test_users[user_response_data['name']] = user_response_data

    return existing_facebook_test_users
Ejemplo n.º 19
0
def _merge_with_facebook_data(facebook_test_users, graph_test_users,
                              access_token):
    """
    Creates a copy of the facebook_test_users dictionary, attaching each test user's user and permission data
    from the open graph api.
    """
    # Merge open graph data with the original facebook_test_users dictionary
    facebook_test_users = copy.deepcopy(facebook_test_users)
    for graph_test_user in graph_test_users:
        if 'id' in graph_test_user:
            facebook_id = graph_test_user['id']
            test_user_url = "https://graph.facebook.com/%s?access_token=%s" % (
                facebook_id, access_token)
            permissions_url = "https://graph.facebook.com/%s/permissions?access_token=%s" % (
                facebook_id, access_token)
            user_data = json.loads(requests.get(test_user_url).content)
            permissions_data = json.loads(
                requests.get(permissions_url).content)

            for facebook_test_user in facebook_test_users:
                if user_data and 'name' in user_data and facebook_test_user[
                        'name'] == user_data['name']:
                    facebook_test_user['access_token'] = graph_test_user.get(
                        'access_token')
                    facebook_test_user['graph_user_data'] = user_data
                    facebook_test_user['graph_user_data'][
                        'login_url'] = graph_test_user['login_url']
                    facebook_test_user[
                        'graph_permission_data'] = permissions_data if 'data' in permissions_data else None

    # Remove any test users that didn't recieve any data from open graph
    test_users = []
    for test_user in facebook_test_users:
        if 'graph_user_data' in test_user and 'graph_permission_data' in test_user:
            test_users.append(test_user)

    return test_users
Ejemplo n.º 20
0
def __handle_friend_test_users_error(user, friend, response):
    error_message = "Failed to friend %s with %s" % (user.name, friend.name)
    try: rdata = json.loads(response.content)
    except: rdata = False

    if rdata == False:
        raise CreateTestUserError(error_message)
    elif type(rdata) is not bool and 'error' in rdata:
        if not __already_friends(rdata):
            try:
                error_message += " (%s)" % rdata['error']['message']
            finally:
                raise CreateTestUserError(error_message)
    elif response.status_code != 200:
        raise CreateTestUserError(error_message)
Ejemplo n.º 21
0
def __handle_friend_test_users_error(user, friend, response):
    error_message = "Failed to friend %s with %s" % (user.name, friend.name)
    try:
        rdata = json.loads(response.content)
    except:
        rdata = False

    if rdata == False:
        raise CreateTestUserError(error_message)
    elif type(rdata) is not bool and 'error' in rdata:
        if not __already_friends(rdata):
            try:
                error_message += " (%s)" % rdata['error']['message']
            finally:
                raise CreateTestUserError(error_message)
    elif response.status_code != 200:
        raise CreateTestUserError(error_message)
def _clean_test_user_fixture(fixture_content, test_users):
    """
    Removes any test users in a fixture that aren't defined in the app's test users
    """
    fixture_names = set([u['pk'] for u in json.loads(fixture_content)])
    actual_names = set([u['name'] for u in test_users])
    names_to_remove = fixture_names - actual_names
    for name_to_remove in names_to_remove:
        name_index = fixture_content.index(name_to_remove)
        start = fixture_content.rindex('{', 0, name_index)      # starting bracket for json entry
        end_fields = fixture_content.index('}', name_index) + 1 # ending bracket for 'fields' dict in json entry
        end = fixture_content.find('{', end_fields)             # starting bracket for next json entry
        if end == -1:
            end = fixture_content.find('}', end_fields) + 1     # ending bracket for json entry
            start = fixture_content.rindex(',', 0, start)       # comma of previous json entry (i.e. { ... }, )
        fixture_content = fixture_content[:start] + fixture_content[end:]
    return fixture_content
Ejemplo n.º 23
0
    def test_overwrite_one_user(self):
        from test_project.testapp1.facebook_test_users import facebook_test_users
        self.assertEquals(0, TestUser.objects.count())
        management.call_command('sync_facebook_test_users', 'testapp1')
        management.call_command('sync_facebook_test_users', 'testapp1')

        # Get the test user data from facebook
        test_users_url = "https://graph.facebook.com/%s/accounts/test-users?access_token=%s" % (
            settings.FACEBOOK_APPLICATION_ID, _get_app_access_token())
        api_test_users = json.loads(
            requests.get(test_users_url).content)['data']
        test_users = _merge_with_facebook_data(facebook_test_users,
                                               api_test_users,
                                               _get_app_access_token())

        # Make sure the test user's information on facebook is correct
        self.assertEquals(1, len(test_users))
        self.assertEquals(
            1,
            len([
                u for u in test_users
                if u.get('graph_user_data') and u.get('graph_permission_data')
            ]))
        self.assertEquals(
            1,
            len([
                u for u in api_test_users if 'id' in u
                and u['id'] == test_users[0]['graph_user_data']['id']
            ]))
        for permission in test_users[0]['permissions']:
            self.assertTrue(permission.strip() in test_users[0]
                            ['graph_permission_data']['data'][0])

        # Make sure the test user's information in facetools is correct
        self.assertEquals(1, TestUser.objects.count())
        user = TestUser.objects.get()
        self.assertEquals(int(test_users[0]['graph_user_data']['id']),
                          user.facebook_id)
        self.assertEquals(test_users[0]['graph_user_data']['name'], user.name)
        self.assertEquals(test_users[0]['graph_user_data']['login_url'],
                          user.login_url)
        self.assertEquals(test_users[0]['installed'],
                          _has_access_code(user.access_token))

        # Make sure the generated fixture is correct
        self.assertTestUserFixture(testapp1, 'testapp1', facebook_test_users)
    def test_fandjango_users_created_correctly(self):
        from test_project.testapp3.facebook_test_users import facebook_test_users as t3
        facebook_test_users = t3()
        self.assertTrue(not all([u['installed'] for u in facebook_test_users])) # make sure all the users aren't set to have the app installed
        management.call_command('sync_facebook_test_users', 'testapp3')

        # Get the test user data from facebook
        test_users_url = "https://graph.facebook.com/%s/accounts/test-users?access_token=%s" % (settings.FACEBOOK_APPLICATION_ID, _get_app_access_token())
        test_users = _merge_with_facebook_data(facebook_test_users, json.loads(requests.get(test_users_url).content)['data'], _get_app_access_token())

        # Make sure only the test users that have the app installed have correpsonding Fandjango User records
        self.assertEquals(2, User.objects.count())
        for test_user in test_users:
            if test_user['installed']:
                user = User.objects.get(facebook_id=int(test_user['graph_user_data']['id']))
                self.assertEquals(test_user['access_token'], user.oauth_token.token)
            else:
                self.assertEquals(0, User.objects.filter(facebook_id=int(test_user['graph_user_data']['id'])).count())
Ejemplo n.º 25
0
def _create_test_user_on_facebook(app_installed=True, name=None, permissions=None, access_token=None):
    """
    Creates a test user on facebook.  Returns a dict of the json response from facebook.
    """
    test_user_template = "https://graph.facebook.com/%s/accounts/test-users?installed=%s&permissions=%s&method=post&access_token=%s"

    # Generate the request URL
    if app_installed == True:
        app_installed = "true"
    else:
        app_installed = "false"
    if permissions is None:
        permissions = settings.FACEBOOK_APPLICATION_INITIAL_PERMISSIONS
    permissions = _create_permissions_string(permissions)
    if access_token is None:
        access_token = _get_app_access_token()
    test_user_url = test_user_template % (settings.FACEBOOK_APPLICATION_ID, app_installed, permissions, access_token)
    if name:
        test_user_url = '%s&name=%s' % (test_user_url,urllib.quote(name))

    # Request a new test user from facebook
    for attempts in range(3, 0, -1):
        r = requests.get(test_user_url)
        try: data = json.loads(r.content)
        except: data = None
        if r.status_code != 200 or data is None or data == False or 'error' in data:
            continue
        return data
    else:
        try:
            raise CreateTestUserError(data['error']['message'])
        except CreateTestUserError: raise
        except:
            try:
                raise CreateTestUserError("Request to create test user failed (status_code=%s and content=\"%s\")" % (r.status_code, r.content))
            except CreateTestUserError: raise
            except:
                raise CreateTestUserError("Request to create test user failed (status_code=%s)" % r.status_code)
    raise CreateTestUserError("Request to create test user failed")
def _clean_test_user_fixture(fixture_content, test_users):
    """
    Removes any test users in a fixture that aren't defined in the app's test users
    """
    fixture_names = set([u['pk'] for u in json.loads(fixture_content)])
    actual_names = set([u['name'] for u in test_users])
    names_to_remove = fixture_names - actual_names
    for name_to_remove in names_to_remove:
        name_index = fixture_content.index(name_to_remove)
        start = fixture_content.rindex(
            '{', 0, name_index)  # starting bracket for json entry
        end_fields = fixture_content.index(
            '}',
            name_index) + 1  # ending bracket for 'fields' dict in json entry
        end = fixture_content.find(
            '{', end_fields)  # starting bracket for next json entry
        if end == -1:
            end = fixture_content.find(
                '}', end_fields) + 1  # ending bracket for json entry
            start = fixture_content.rindex(
                ',', 0, start)  # comma of previous json entry (i.e. { ... }, )
        fixture_content = fixture_content[:start] + fixture_content[end:]
    return fixture_content
Ejemplo n.º 27
0
def _parse_signed_request(signed_request, app_secret):
    """Return dictionary with signed request data."""
    try:
        l = signed_request.split('.', 2)
        encoded_sig = str(l[0])
        payload = str(l[1])
    except IndexError:
        raise ValueError("Signed request malformed")

    sig = base64.urlsafe_b64decode(encoded_sig + "=" * ((4 - len(encoded_sig) % 4) % 4))
    data = base64.urlsafe_b64decode(payload + "=" * ((4 - len(payload) % 4) % 4))

    data = json.loads(data)

    if data.get('algorithm').upper() != 'HMAC-SHA256':
        raise ValueError("Signed request is using an unknown algorithm")
    else:
        expected_sig = hmac.new(app_secret, msg=payload, digestmod=hashlib.sha256).digest()

    if sig != expected_sig:
        raise ValueError("Signed request signature mismatch")
    else:
        return data
Ejemplo n.º 28
0
def _delete_test_user_on_facebook(test_user):
    delete_url_template = "https://graph.facebook.com/%s?method=delete&access_token=%s"
    delete_user_url = delete_url_template % (test_user.facebook_id,
                                             _get_app_access_token())
    r = requests.delete(delete_user_url)
    if not isinstance(r.content, basestring):
        raise DeleteTestUserError(
            "Error deleting user %s (%s) from facebook: Facebook returned invalid response"
            % (test_user.name, test_user.facebook_id, r.content))
    if r.content.strip().lower() != "true":
        if r.content.strip().lower() == "false":
            raise DeleteTestUserError(
                "Error deleting user %s (%s) from facebook: Facebook returned false"
                % (test_user.name, test_user.facebook_id, r.content))
        else:
            try:
                raise DeleteTestUserError(
                    "Error deleting user %s (%s) from facebook: %s" %
                    (test_user.name, test_user.facebook_id,
                     json.loads(r.content)['error']['message']))
            except:
                raise DeleteTestUserError(
                    "Error deleting user %s (%s) from facebook: %s" %
                    (test_user.name, test_user.facebook_id, r.content))
Ejemplo n.º 29
0
def _delete_test_user_on_facebook(test_user):
    delete_url_template = "https://graph.facebook.com/%s?method=delete&access_token=%s"
    delete_user_url = delete_url_template % (test_user.facebook_id, _get_app_access_token())
    r = requests.delete(delete_user_url)
    if not isinstance(r.content, basestring):
        raise DeleteTestUserError("Error deleting user %s (%s) from facebook: Facebook returned invalid response" % (test_user.name, test_user.facebook_id, r.content))
    if r.content.strip().lower() != "true":
        if r.content.strip().lower() == "false":
            raise DeleteTestUserError("Error deleting user %s (%s) from facebook: Facebook returned false" % (test_user.name, test_user.facebook_id, r.content))
        else:
            try:
                raise DeleteTestUserError("Error deleting user %s (%s) from facebook: %s" % (test_user.name, test_user.facebook_id, json.loads(r.content)['error']['message']))
            except:
                raise DeleteTestUserError("Error deleting user %s (%s) from facebook: %s" % (test_user.name, test_user.facebook_id, r.content))