Ejemplo n.º 1
0
    def test_user_registered_signal(self):
        # Ensure user registered, pre update and post update signals fire

        def user_registered(sender, user, facebook_data, **kwargs):
            user.registered_signal = True

        def pre_update(sender, user, profile, facebook_data, **kwargs):
            user.pre_update_signal = True

        def post_update(sender, user, profile, facebook_data, **kwargs):
            user.post_update_signal = True

        Profile = get_profile_model()
        user_model = get_user_model()
        signals.facebook_user_registered.connect(user_registered,
                                                 sender=user_model)
        signals.facebook_pre_update.connect(pre_update, sender=user_model)
        signals.facebook_post_update.connect(post_update, sender=user_model)

        graph = get_facebook_graph(access_token='short_username')
        facebook = FacebookUserConverter(graph)
        user = _register_user(self.request, facebook)
        self.assertEqual(hasattr(user, 'registered_signal'), True)
        self.assertEqual(hasattr(user, 'pre_update_signal'), True)
        self.assertEqual(hasattr(user, 'post_update_signal'), True)
Ejemplo n.º 2
0
    def test_update_access_token(self):
        request = RequestMock().get('/')
        request.session = {}
        request.user = AnonymousUser()
        graph = get_persistent_graph(request, access_token='paul')
        action, user = connect_user(self.request, facebook_graph=graph)
        first_user_id = user.id

        # new token required should start out as False
        profile = try_get_profile(user)
        new_token_required = get_user_attribute(user, profile,
                                                'new_token_required')
        self.assertEqual(new_token_required, False)

        # we manually set it to true
        update_user_attributes(user,
                               profile,
                               dict(new_token_required=True),
                               save=True)
        if profile:
            profile = get_profile_model().objects.get(id=profile.id)
        user = get_user_model().objects.get(id=user.id)
        new_token_required = get_user_attribute(user, profile,
                                                'new_token_required')
        self.assertEqual(new_token_required, True)

        # another update should however set it back to False
        request.facebook = None
        graph = get_facebook_graph(request, access_token='paul2')
        logger.info('and the token is %s', graph.access_token)
        action, user = connect_user(self.request, facebook_graph=graph)
        user = get_user_model().objects.get(id=user.id)
        self.assertEqual(user.id, first_user_id)
        if profile:
            profile = get_profile_model().objects.get(id=profile.id)
        user = get_user_model().objects.get(id=user.id)
        new_token_required = get_user_attribute(user, profile,
                                                'new_token_required')
        self.assertEqual(new_token_required, False)
Ejemplo n.º 3
0
 def _create_unique_username(cls, base_username):
     '''
     Check the database and add numbers to the username to ensure its unique
     '''
     usernames = list(
         get_user_model().objects.filter(
             username__istartswith=base_username
         ).values_list('username', flat=True))
     usernames_lower = [str(u).lower() for u in usernames]
     username = str(base_username)
     i = 1
     while base_username.lower() in usernames_lower:
         base_username = username + str(i)
         i += 1
     return base_username
Ejemplo n.º 4
0
 def test_follow_og_share(self):
     user_url = 'http://www.fashiolista.com/style/neni/'
     kwargs = dict(item=user_url)
     user = get_user_model().objects.all()[:1][0]
     from django.contrib.contenttypes.models import ContentType
     some_content_type = ContentType.objects.all()[:1][0]
     share = OpenGraphShare.objects.create(
         user_id=user.id,
         facebook_user_id=13123123,
         action_domain='fashiolista:follow',
         content_type=some_content_type,
         object_id=user.id,
     )
     share.set_share_dict(kwargs)
     share.save()
     share.send()
Ejemplo n.º 5
0
    def test_fb_update_required(self):
        def pre_update(sender, user, profile, facebook_data, **kwargs):
            user.pre_update_signal = True

        Profile = get_profile_model()
        user_model = get_user_model()
        signals.facebook_pre_update.connect(pre_update, sender=user_model)
        facebook = get_facebook_graph(access_token='tschellenbach')

        facebook_settings.FACEBOOK_FORCE_PROFILE_UPDATE_ON_LOGIN = True
        action, user = connect_user(self.request, facebook_graph=facebook)
        self.assertEqual(action, CONNECT_ACTIONS.LOGIN)
        self.assertTrue(hasattr(user, 'pre_update_signal'))

        facebook_settings.FACEBOOK_FORCE_PROFILE_UPDATE_ON_LOGIN = False
        action, user = connect_user(self.request, facebook_graph=facebook)
        self.assertEqual(action, CONNECT_ACTIONS.LOGIN)
        self.assertFalse(hasattr(user, 'pre_update_signal'))
Ejemplo n.º 6
0
def _get_old_connections(facebook_id, current_user_id=None):
    '''
    Gets other accounts connected to this facebook id, which are not
    attached to the current user
    '''
    user_or_profile_model = get_model_for_attribute('facebook_id')
    other_facebook_accounts = user_or_profile_model.objects.filter(
        facebook_id=facebook_id)
    kwargs = {}

    if current_user_id:
        # if statement since we need to support both
        user_model = get_user_model()
        if user_or_profile_model == user_model:
            kwargs['id'] = current_user_id
        else:
            kwargs['user'] = current_user_id
        other_facebook_accounts = other_facebook_accounts.exclude(**kwargs)
    return other_facebook_accounts
Ejemplo n.º 7
0
    def setUp(self):
        FacebookTest.setUp(self)
        user_url = 'http://www.fashiolista.com/style/neni/'
        kwargs = dict(item=user_url)
        user = get_user_model().objects.all()[:1][0]
        profile = try_get_profile(user)
        user_or_profile = get_instance_for_attribute(user, profile,
                                                     'facebook_open_graph')
        user_or_profile.facebook_open_graph = True
        user_or_profile.save()

        some_content_type = ContentType.objects.all()[:1][0]
        share = OpenGraphShare.objects.create(
            user_id=user.id,
            facebook_user_id=13123123,
            action_domain='fashiolista:follow',
            content_type=some_content_type,
            object_id=user.id,
        )
        share.set_share_dict(kwargs)
        share.save()
        self.share = share
        self.share_details = user, profile, share
Ejemplo n.º 8
0
 def test_send(error,
               expected_error_message,
               expected_new_token,
               has_permissions=False):
     user, profile, share = self.share_details
     update_user_attributes(user,
                            profile,
                            dict(new_token_required=False),
                            save=True)
     with mock.patch('open_facebook.api.OpenFacebook') as mocked:
         instance = mocked.return_value
         instance.set = Mock(side_effect=error)
         instance.has_permissions = Mock(return_value=has_permissions)
         instance.access_token = get_user_attribute(
             user, profile, 'access_token')
         share.send(graph=instance)
         self.assertEqual(share.error_message, expected_error_message)
         self.assertFalse(share.completed_at)
         user = get_user_model().objects.get(id=user.id)
         if profile:
             profile = get_profile_model().objects.get(id=profile.id)
         new_token_required = get_user_attribute(
             user, profile, 'new_token_required')
         self.assertEqual(new_token_required, expected_new_token)
Ejemplo n.º 9
0
    def test_connect(self):
        '''
        Test if we can do logins
        django_facebook.connect.connect_user
        '''
        user = get_user_model().objects.all()[:1][0]
        url = self.url
        example_url = reverse('facebook_example')

        # test registration flow
        with patch('django_facebook.views.connect_user',
                   return_value=(CONNECT_ACTIONS.REGISTER,
                                 user)) as wrapped_connect:
            post_data = dict(
                access_token='short_username',
                next='%s?register=1' % example_url,
            )
            response = self.client.post(url, post_data, follow=True)
            self.assertEqual(wrapped_connect.call_count, 1)
            self.assertIn('register', response.redirect_chain[0][0])
            self.assertEqual(response.status_code, 200)

        # user register next instead of next
        with patch('django_facebook.views.connect_user',
                   return_value=(CONNECT_ACTIONS.REGISTER,
                                 user)) as wrapped_connect:
            post_data = dict(access_token='short_username',
                             register_next='%s?register=1' % example_url)
            response = self.client.post(url, post_data, follow=True)
            self.assertEqual(wrapped_connect.call_count, 1)
            self.assertIn('register', response.redirect_chain[0][0])
            self.assertEqual(response.status_code, 200)

        # test login
        with patch('django_facebook.views.connect_user',
                   return_value=(CONNECT_ACTIONS.LOGIN,
                                 user)) as wrapped_connect:
            post_data = dict(
                access_token='short_username',
                next='%s?loggggg=1' % example_url,
            )
            response = self.client.post(url, post_data, follow=True)
            self.assertEqual(wrapped_connect.call_count, 1)
            self.assertIn('?loggggg=1', response.redirect_chain[0][0])
            self.assertEqual(response.status_code, 200)

        # test connect
        with patch('django_facebook.views.connect_user',
                   return_value=(CONNECT_ACTIONS.CONNECT,
                                 user)) as wrapped_connect:
            post_data = dict(access_token='short_username',
                             next='%s?loggggg=1' % example_url)
            response = self.client.post(url, post_data, follow=True)
            self.assertEqual(wrapped_connect.call_count, 1)
            assert '?loggggg=1' in response.redirect_chain[0][0]
            self.assertEqual(response.status_code, 200)

        # test connect
        from django_facebook import exceptions as facebook_exceptions
        profile_error = facebook_exceptions.IncompleteProfileError()
        profile_error.form = None
        with patch('django_facebook.views.connect_user',
                   return_value=(CONNECT_ACTIONS.REGISTER, user),
                   side_effect=profile_error) as wrapped_connect:
            post_data = dict(access_token='short_username',
                             next='%s?loggggg=1' % example_url)
            response = self.client.post(url, post_data, follow=True)
            self.assertEqual(wrapped_connect.call_count, 1)
            self.assertEqual(response.status_code, 200)
            self.assertTrue(response.context)
            template = self.get_response_template(response)
            assert template.name in facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE or template.name == facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE
Ejemplo n.º 10
0
 def test_get_persistent(self):
     graph = get_persistent_graph(self.request)
     # fake that we are authenticated and have a facebook graph
     with patch.object(self.request, 'facebook'):
         self.request.user = get_user_model().objects.all()[:1][0]
         graph = get_persistent_graph(self.request)
Ejemplo n.º 11
0
def _update_user(user, facebook, overwrite=True):
    '''
    Updates the user and his/her profile with the data from facebook
    '''
    # if you want to add fields to ur user model instead of the
    # profile thats fine
    # partial support (everything except raw_data and facebook_id is included)
    facebook_data = facebook.facebook_registration_data(username=False)
    facebook_fields = [
        'facebook_name', 'facebook_profile_url', 'gender', 'date_of_birth',
        'about_me', 'website_url', 'first_name', 'last_name'
    ]

    profile = try_get_profile(user)
    # which attributes to update
    attributes_dict = {}

    # send the signal that we're updating
    signals.facebook_pre_update.send(sender=get_user_model(),
                                     user=user,
                                     profile=profile,
                                     facebook_data=facebook_data)

    # set the facebook id and make sure we are the only user with this id
    current_facebook_id = get_user_attribute(user, profile, 'facebook_id')
    facebook_id_changed = facebook_data['facebook_id'] != current_facebook_id
    overwrite_allowed = overwrite or not current_facebook_id

    # update the facebook id and access token
    facebook_id_overwritten = False
    if facebook_id_changed and overwrite_allowed:
        # when not overwriting we only update if there is no
        # profile.facebook_id
        logger.info('profile facebook id changed from %s to %s',
                    repr(facebook_data['facebook_id']),
                    repr(current_facebook_id))
        attributes_dict['facebook_id'] = facebook_data['facebook_id']
        facebook_id_overwritten = True

    if facebook_id_overwritten:
        _remove_old_connections(facebook_data['facebook_id'], user.id)

    # update all fields on both user and profile
    for f in facebook_fields:
        facebook_value = facebook_data.get(f, False)
        current_value = get_user_attribute(user, profile, f, None)
        if facebook_value and not current_value:
            attributes_dict[f] = facebook_value

    # write the raw data in case we missed something
    serialized_fb_data = json.dumps(facebook.facebook_profile_data())
    current_raw_data = get_user_attribute(user, profile, 'raw_data')
    if current_raw_data != serialized_fb_data:
        attributes_dict['raw_data'] = serialized_fb_data

    image_url = facebook_data['image']
    # update the image if we are allowed and have to
    if facebook_settings.FACEBOOK_STORE_LOCAL_IMAGE:
        image_field = get_user_attribute(user, profile, 'image', True)
        if not image_field:
            image_name, image_file = _update_image(profile, image_url)
            image_field.save(image_name, image_file)

    # save both models if they changed
    update_user_attributes(user, profile, attributes_dict)
    if getattr(user, '_fb_is_dirty', False):
        user.save()
    if getattr(profile, '_fb_is_dirty', False):
        profile.save()

    signals.facebook_post_update.send(sender=get_user_model(),
                                      user=user,
                                      profile=profile,
                                      facebook_data=facebook_data)

    return user
Ejemplo n.º 12
0
        new_user = None
        if backend:
            new_user = backend.register(request,
                                        form=form,
                                        **form.cleaned_data)
        # fall back to the form approach
        if new_user is None:
            raise ValueError(
                'new_user is None, note that backward compatability for the older versions of django registration has been dropped.'
            )
    except IntegrityError, e:
        # this happens when users click multiple times, the first request registers
        # the second one raises an error
        raise facebook_exceptions.AlreadyRegistered(e)

    signals.facebook_user_registered.send(sender=get_user_model(),
                                          user=new_user,
                                          facebook_data=facebook_data,
                                          request=request)

    # update some extra data not yet done by the form
    new_user = _update_user(new_user, facebook)

    # IS this the correct way for django 1.3? seems to require the backend
    # attribute for some reason
    new_user.backend = 'django_facebook.auth_backends.FacebookBackend'
    auth.login(request, new_user)

    return new_user