Esempio n. 1
0
    def test_parallel_register(self):
        '''
        Adding some testing for the case when one person tries to register
        multiple times in the same second
        '''
        graph = get_facebook_graph(access_token='short_username')
        FacebookUserConverter(graph)
        action, user = connect_user(self.request, facebook_graph=graph)
        self.assertEqual(action, CONNECT_ACTIONS.REGISTER)

        self.request.user.is_authenticated = lambda: False
        with patch('django_facebook.connect.authenticate') as patched:
            return_sequence = [user, None]

            def side(*args, **kwargs):
                value = return_sequence.pop()
                return value

            patched.side_effect = side
            with patch('django_facebook.connect._register_user'
                       ) as patched_register:
                patched_register.side_effect = facebook_exceptions.AlreadyRegistered(
                    'testing parallel registers')
                action, user = connect_user(self.request, facebook_graph=graph)
                self.assertEqual(action, CONNECT_ACTIONS.LOGIN)
Esempio n. 2
0
 def test_full_connect(self):
     #going for a register, connect and login
     facebook = get_facebook_graph(access_token='short_username', persistent_token=False)
     action, user = connect_user(self.request, facebook_graph=facebook)
     assert action == CONNECT_ACTIONS.REGISTER
     action, user = connect_user(self.request, facebook_graph=facebook)
     assert action == CONNECT_ACTIONS.CONNECT
     self.request.user = AnonymousUser()
     action, user = connect_user(self.request, facebook_graph=facebook)
     assert action == CONNECT_ACTIONS.LOGIN
Esempio n. 3
0
 def test_full_connect(self):
     #going for a register, connect and login
     graph = get_facebook_graph(access_token='short_username')
     FacebookUserConverter(graph)
     action, user = connect_user(self.request, facebook_graph=graph)
     self.assertEqual(action, CONNECT_ACTIONS.REGISTER)
     action, user = connect_user(self.request, facebook_graph=graph)
     self.assertEqual(action, CONNECT_ACTIONS.CONNECT)
     self.request.user = AnonymousUser()
     action, user = connect_user(self.request, facebook_graph=graph)
     self.assertEqual(action, CONNECT_ACTIONS.LOGIN)
Esempio n. 4
0
 def test_full_connect(self):
     #going for a register, connect and login
     graph = get_facebook_graph(access_token='short_username')
     FacebookUserConverter(graph)
     action, user = connect_user(self.request, facebook_graph=graph)
     self.assertEqual(action, CONNECT_ACTIONS.REGISTER)
     action, user = connect_user(self.request, facebook_graph=graph)
     self.assertEqual(action, CONNECT_ACTIONS.CONNECT)
     self.request.user = AnonymousUser()
     action, user = connect_user(self.request, facebook_graph=graph)
     self.assertEqual(action, CONNECT_ACTIONS.LOGIN)
    def test_login_with_Facebook2(self):
        graph = get_facebook_graph(access_token='short_username')
        action, user = connect_user(self.request, facebook_graph=graph)
        user.save()
        self.request.user = AnonymousUser()
        graph = get_facebook_graph(access_token='same_username')
        action, new_user = connect_user(self.request, facebook_graph=graph)

        self.request.GET._mutable = True
        self.request.GET['testing'] = 'True'
        response = views.index(self.request)
        print response.content
Esempio n. 6
0
 def test_double_username(self):
     '''
     This used to give an error with duplicate usernames with different capitalization
     '''
     facebook = get_facebook_graph(access_token='short_username')
     action, user = connect_user(self.request, facebook_graph=facebook)
     user.username = '******'
     user.save()
     self.request.user = AnonymousUser()
     facebook = get_facebook_graph(access_token='same_username')
     action, new_user = connect_user(self.request, facebook_graph=facebook)
     assert user.username != new_user.username and user.id != new_user.id
Esempio n. 7
0
 def test_double_username(self):
     '''
     This used to give an error with duplicate usernames with different capitalization
     '''
     facebook = get_facebook_graph(access_token='short_username')
     action, user = connect_user(self.request, facebook_graph=facebook)
     user.username = '******'
     user.save()
     self.request.user = AnonymousUser()
     facebook = get_facebook_graph(access_token='same_username')
     action, new_user = connect_user(self.request, facebook_graph=facebook)
     assert user.username != new_user.username and user.id != new_user.id
    def test_login_with_Facebook2(self):
        graph = get_facebook_graph(access_token='short_username')
        action, user = connect_user(self.request, facebook_graph=graph)
        user.save()
        self.request.user = AnonymousUser()
        graph = get_facebook_graph(access_token='same_username')
        action, new_user = connect_user(self.request, facebook_graph=graph)


        self.request.GET._mutable = True
        self.request.GET['testing'] = 'True'
        response = views.index(self.request)
        print response.content
Esempio n. 9
0
 def test_double_username(self):
     """
     This used to give an error with duplicate usernames
     with different capitalization
     """
     facebook = get_facebook_graph(access_token="short_username")
     action, user = connect_user(self.request, facebook_graph=facebook)
     user.username = "******"
     user.save()
     self.request.user = AnonymousUser()
     facebook = get_facebook_graph(access_token="same_username")
     action, new_user = connect_user(self.request, facebook_graph=facebook)
     self.assertNotEqual(user.username, new_user.username)
     self.assertNotEqual(user.id, new_user.id)
Esempio n. 10
0
def fb_connect(request):
    if request.method != 'POST':
        return HttpResponseRedirect(reverse('game-login'))

    if request.user and request.user.is_authenticated():
        player = Player.get_player_for_user(request.user)
        if player.is_guest:
            # let's upgrade the guest to fb user
            if not 'connect_facebook' in request.GET:
                return HttpResponseRedirect('?connect_facebook=1')
        else:
            django_logout_method(request)

    access_token = request.POST.get('access_token')

    action, user = connect_user(request, access_token)

    player = Player.get_player_for_user(user)
    player.is_guest = False
    player.save()
    user.username = json.loads(player.raw_data)['username']
    user.save()

    return HttpResponse(
        json.dumps({
            'status': 'OK',
            'username': user.username,
            'profile': player.serialize()
        }))
Esempio n. 11
0
 def test_full_connect(self):
     #going for a register, connect and login
     graph = get_facebook_graph(access_token='short_username')
     klass = get_facebook_user_converter_class()
     klass(graph)
     action, user = connect_user(self.request, facebook_graph=graph)
     self.assertEqual(action, CONNECT_ACTIONS.REGISTER)
     action, user = connect_user(self.request, facebook_graph=graph)
     self.assertEqual(action, CONNECT_ACTIONS.LOGIN)
     self.request.GET._mutable = True
     self.request.GET['connect_facebook'] = 1
     action, user = connect_user(self.request, facebook_graph=graph)
     self.assertEqual(action, CONNECT_ACTIONS.CONNECT)
     self.request.user = AnonymousUser()
     action, user = connect_user(self.request, facebook_graph=graph)
     self.assertEqual(action, CONNECT_ACTIONS.LOGIN)
Esempio n. 12
0
    def obj_create(self, bundle, request=None, **kwargs):
        bundle.obj = Obj()
        bundle.obj.id = 1
        code = bundle.data.get('code')
        redirect_uri = bundle.data.get('redirectUri', '')
        if not code:
            self.create_response(
                bundle.request, bundle,
                response_class=BadRequest('code is required'))
            logger.error('code is required')

        # TODO: Add catch errors
        token_response = FacebookAuthorization.convert_code(
            code, redirect_uri=redirect_uri)

        # TODO: Add access_token to cache
        access_token = token_response['access_token']
        action, user = connect_user(bundle.request, access_token=access_token)

        from events.tasks import store_fb_events, refresh_fb_events
        store_fb_events.delay(user)
        refresh_fb_events.delay(user)
        payload = jwt_payload_handler(user)
        payload['access_token'] = user.access_token
        bundle.obj.token = jwt_encode_handler(payload)
        # TODO: clean up response
        return bundle
    def test_anon_user_loads_index(self):
        graph = get_facebook_graph(access_token='new_user')
        action, user = connect_user(self.request, facebook_graph=graph)

        self.request.user = AnonymousUser()
        response = views.index(self.request)
        print response.cookies
Esempio n. 14
0
    def is_authenticated(self, request, **kwargs):
        """
        Authenticate with facebook, and return
        user upon success.
        
        """

        # Make sure user supplied access token in request
        try:
            access_token = request.GET['access_token']
        except KeyError:
            return self._unauthorized()

        # Authenticate with facebook
        from open_facebook import OpenFacebook
        from django_facebook.connect import connect_user

        facebook = OpenFacebook(access_token)

        try:
            if not facebook or \
                not facebook.is_authenticated():
                return self._unauthorized()
        except:
            return self._unauthorized()
        
        
        # Facebook authenticated, now associate
        # with own internal user, Creating a new user if 
        # necessary.
        action, user = connect_user(request, access_token, facebook)
        request.user = user
  
        return True
Esempio n. 15
0
def connect(request):
    '''
    Handles the view logic around connect user
    - (if authenticated) connect the user
    - login
    - register
    
    '''
    context = RequestContext(request)
    facebook_login = bool(int(request.REQUEST.get('facebook_login', 0)))
    
    if facebook_login:
        facebook = get_facebook_graph(request)
        if facebook.is_authenticated():
            facebook_data = facebook.facebook_profile_data()
            #either, login register or connect the user
            try:
                action, user = connect_user(request)
            except facebook_exceptions.IncompleteProfileError, e:
                logger.error(unicode(e))
                messages.error(request, _("Please allow the request for permission in order to log in."))
                return next_redirect(request)
                
            if action is CONNECT_ACTIONS.CONNECT:
                messages.info(request, _("You have connected your account to %s's facebook profile") % facebook_data['name'])
            elif action is CONNECT_ACTIONS.REGISTER:
                member_overview_url = user.get_profile().url['overview']
                response = HttpResponseRedirect(member_overview_url)
                response.set_cookie('fresh_registration', user.id)
                return response
        else:
            return next_redirect(request, additional_params=dict(fb_error_or_cancel=1))
            
        return next_redirect(request)
Esempio n. 16
0
def connect(request):
    '''
    Handles the view logic around connect user
    - (if authenticated) connect the user
    - login
    - register
    '''
    context = RequestContext(request)

    assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id '\
        'and ensure the context processor is enabled'
    facebook_login = bool(int(request.REQUEST.get('facebook_login', 0)))

    if facebook_login:
        logger.info('trying to connect using facebook')
        graph = get_persistent_graph(request)
        if graph:
            logger.info('found a graph object')
            facebook = FacebookUserConverter(graph)
            if facebook.is_authenticated():
                logger.info('facebook is authenticated')
                facebook_data = facebook.facebook_profile_data()
                #either, login register or connect the user
                try:
                    action, user = connect_user(request)
                    logger.info('Django facebook performed action: %s', action)
                except facebook_exceptions.IncompleteProfileError, e:
                    warn_message = u'Incomplete profile data encountered '\
                        u'with error %s' % e
                    send_warning(warn_message,
                                 e=e,
                                 facebook_data=facebook_data)

                    context['facebook_mode'] = True
                    context['form'] = e.form
                    return render_to_response(
                        facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE,
                        context_instance=context,
                    )

                if action is CONNECT_ACTIONS.CONNECT:
                    messages.info(
                        request,
                        _("You have connected your account "
                          "to %s's facebook profile") % facebook_data['name'])
                elif action is CONNECT_ACTIONS.REGISTER:
                    return user.get_profile().post_facebook_registration(
                        request)
        else:
            if 'attempt' in request.GET:
                return next_redirect(
                    request,
                    next_key=['error_next', 'next'],
                    additional_params=dict(fb_error_or_cancel=1))
            else:
                logger.info('Facebook authentication needed for connect, ' \
                            'raising an error')
                raise OpenFacebookException('please authenticate')

        return next_redirect(request)
    def test_anon_user_loads_index(self):
        graph = get_facebook_graph(access_token='new_user')
        action, user = connect_user(self.request, facebook_graph=graph)

        self.request.user = AnonymousUser()
        response = views.index(self.request)
        print response.cookies
Esempio n. 18
0
 def post(self, request):
   serializer = self.serializer_class(data=request.DATA)
   if serializer.is_valid():
     action, user  = connect_user(self.request, serializer.data['access_token'])
     token, created = Token.objects.get_or_create(user=user)
     return Response({'token': token.key})
   return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Esempio n. 19
0
def _connect(request, facebook_login):
    '''
    Handles the view logic around connect user
    - (if authenticated) connect the user
    - login
    - register
    '''
    backend = get_registration_backend()
    context = RequestContext(request)

    if facebook_login:
        logger.info('trying to connect using Facebook')
        graph = require_persistent_graph(request)
        authenticated = False
        if graph:
            logger.info('found a graph object')
            facebook = FacebookUserConverter(graph)
            authenticated = facebook.is_authenticated()

            if authenticated:
                logger.info('Facebook is authenticated')
                facebook_data = facebook.facebook_profile_data()
                #either, login register or connect the user
                try:
                    action, user = connect_user(request)
                    logger.info('Django facebook performed action: %s', action)
                except facebook_exceptions.IncompleteProfileError, e:
                    #show them a registration form to add additional data
                    warning_format = u'Incomplete profile data encountered with error %s'
                    warn_message = warning_format % e.message
                    send_warning(warn_message, e=e,
                                 facebook_data=facebook_data)

                    context['facebook_mode'] = True
                    context['form'] = e.form
                    return render_to_response(
                        facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE,
                        context_instance=context,
                    )
                except facebook_exceptions.AlreadyConnectedError, e:
                    user_ids = [u.id for u in e.users]
                    ids_string = ','.join(map(str, user_ids))
                    return error_next_redirect(
                        request,
                        additional_params=dict(already_connected=ids_string))

                if action is CONNECT_ACTIONS.CONNECT:
                    #connect means an existing account was attached to facebook
                    messages.info(request, _("You have connected your account "
                                             "to %s's facebook profile") % facebook_data['name'])
                elif action is CONNECT_ACTIONS.REGISTER:
                    #hook for tying in specific post registration functionality
                    response = backend.post_registration_redirect(
                        request, user)
                    #compatibility for Django registration backends which return redirect tuples instead of a response
                    if not isinstance(response, HttpResponse):
                        to, args, kwargs = response
                        response = redirect(to, *args, **kwargs)
                    return response
Esempio n. 20
0
    def test_fb_update_required(self):
        def pre_update(sender, profile, facebook_data, **kwargs):
            profile.pre_update_signal = True

        Profile = get_profile_class()
        signals.facebook_pre_update.connect(pre_update, sender=Profile)
        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.get_profile(), '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.get_profile(), 'pre_update_signal'))
Esempio n. 21
0
    def test_fb_update_required(self):
        def pre_update(sender, profile, facebook_data, **kwargs):
            profile.pre_update_signal = True

        Profile = get_profile_class()
        signals.facebook_pre_update.connect(pre_update, sender=Profile)
        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.get_profile(), '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.get_profile(), 'pre_update_signal'))
Esempio n. 22
0
def connect(request):
    '''
    Handles the view logic around connect user
    - (if authenticated) connect the user
    - login
    - register
    '''
    backend = get_registration_backend()
    context = RequestContext(request)

    assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id '\
        'and ensure the context processor is enabled'
    facebook_login = bool(int(request.REQUEST.get('facebook_login', 0)))
    
    if facebook_login:
        require_persistent_graph(request)
        logger.info('trying to connect using facebook')
        graph = get_persistent_graph(request)
        if graph:
            logger.info('found a graph object')
            facebook = FacebookUserConverter(graph)
            
            if facebook.is_authenticated():
                logger.info('facebook is authenticated')
                facebook_data = facebook.facebook_profile_data()
                #either, login register or connect the user
                try:
                    action, user = connect_user(request)
                    logger.info('Django facebook performed action: %s', action)
                except facebook_exceptions.IncompleteProfileError, e:
                    warn_message = u'Incomplete profile data encountered '\
                        u'with error %s' % e.message.decode('utf-8', 'replace')
                    send_warning(warn_message, e=e,
                                 facebook_data=facebook_data)

                    context['facebook_mode'] = True
                    context['form'] = e.form
                    return render_to_response(
                        facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE,
                        context_instance=context,
                    )

                if action is CONNECT_ACTIONS.CONNECT:
                    messages.info(request, _("You have connected your account "
                        "to %s's facebook profile") % facebook_data['name'])
                elif action is CONNECT_ACTIONS.REGISTER:
                    response = backend.post_registration_redirect(request, user)
                    return response
        else:
            if 'attempt' in request.GET:
                return next_redirect(request, next_key=['error_next', 'next'],
                    additional_params=dict(fb_error_or_cancel=1))
            else:
                logger.info('Facebook authentication needed for connect, ' \
                            'raising an error')
                raise OpenFacebookException('please authenticate')

        return next_redirect(request)
Esempio n. 23
0
def connect(request):
    '''
    Handles the view logic around connect user
    - (if authenticated) connect the user
    - login
    - register
    '''
    backend = get_registration_backend()
    context = RequestContext(request)

    assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id '\
        'and ensure the context processor is enabled'
    facebook_login = bool(int(request.REQUEST.get('facebook_login', 0)))
    
    if facebook_login:
        logger.info('trying to connect using facebook')
        graph = require_persistent_graph(request)
        if graph:
            logger.info('found a graph object')
            facebook = FacebookUserConverter(graph)
            
            if facebook.is_authenticated():
                logger.info('facebook is authenticated')
                facebook_data = facebook.facebook_profile_data()
                #either, login register or connect the user
                try:
                    action, user = connect_user(request)
                    logger.info('Django facebook performed action: %s', action)
                except facebook_exceptions.IncompleteProfileError, e:
                    #show them a registration form to add additional data
                    warning_format = u'Incomplete profile data encountered with error %s'
                    warn_message = warning_format % e.message
                    send_warning(warn_message, e=e,
                                 facebook_data=facebook_data)

                    context['facebook_mode'] = True
                    context['form'] = e.form
                    return render_to_response(
                        facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE,
                        context_instance=context,
                    )
                except facebook_exceptions.AlreadyConnectedError, e:
                    user_ids = [u.id for u in e.users]
                    ids_string = ','.join(map(str, user_ids))
                    return next_redirect(request, next_key=['error_next', 'next'],
                        additional_params=dict(already_connected=ids_string))

                if action is CONNECT_ACTIONS.CONNECT:
                    #connect means an existing account was attached to facebook
                    messages.info(request, _("You have connected your account "
                        "to %s's facebook profile") % facebook_data['name'])
                elif action is CONNECT_ACTIONS.REGISTER:
                    #hook for tying in specific post registration functionality
                    response = backend.post_registration_redirect(request, user)
                    #compatability for django registration backends which return tuples instead of a response
                    #alternatively we could wrap django registration backends, but that would be hard to understand
                    response = response if isinstance(response, HttpResponse) else redirect(response)
                    return response
Esempio n. 24
0
 def test_full_connect(self):
     # going for a register, connect and login
     graph = get_facebook_graph(request=self.request, access_token='short_username')
     FacebookUserConverter(graph)
     action, user = connect_user(self.request, facebook_graph=graph)
     self.assertEqual(action, CONNECT_ACTIONS.REGISTER)
     # and now we do a login, not a connect
     action, user = connect_user(self.request, facebook_graph=graph)
     self.assertEqual(action, CONNECT_ACTIONS.LOGIN)
     self.request.GET._mutable = True
     self.request.GET['connect_facebook'] = 1
     action, user = connect_user(
         self.request, facebook_graph=graph, connect_facebook=True)
     self.assertEqual(action, CONNECT_ACTIONS.CONNECT)
     self.request.user = AnonymousUser()
     action, user = connect_user(
         self.request, facebook_graph=graph, connect_facebook=True)
     self.assertEqual(action, CONNECT_ACTIONS.LOGIN)
Esempio n. 25
0
 def test_registration_form(self):
     '''
     Django_facebook should use user supplied registration form if given
     '''
     facebook_settings.FACEBOOK_REGISTRATION_FORM = 'django_facebook.tests_utils.forms.SignupForm'
     facebook = get_facebook_graph(access_token='short_username')
     action, user = connect_user(self.request, facebook_graph=facebook)
     # The test form always sets username to test form
     self.assertEqual(user.username, 'Test form')
Esempio n. 26
0
 def test_full_connect(self):
     # going for a register, connect and login
     graph = get_facebook_graph(request=self.request, access_token='short_username')
     FacebookUserConverter(graph)
     action, user = connect_user(self.request, facebook_graph=graph)
     self.assertEqual(action, CONNECT_ACTIONS.REGISTER)
     # and now we do a login, not a connect
     action, user = connect_user(self.request, facebook_graph=graph)
     self.assertEqual(action, CONNECT_ACTIONS.LOGIN)
     self.request.GET._mutable = True
     self.request.GET['connect_facebook'] = 1
     action, user = connect_user(
         self.request, facebook_graph=graph, connect_facebook=True)
     self.assertEqual(action, CONNECT_ACTIONS.CONNECT)
     self.request.user = AnonymousUser()
     action, user = connect_user(
         self.request, facebook_graph=graph, connect_facebook=True)
     self.assertEqual(action, CONNECT_ACTIONS.LOGIN)
Esempio n. 27
0
    def test_persistent_graph(self):
        request = RequestMock().get('/')
        request.session = {}
        request.user = AnonymousUser()

        graph = get_facebook_graph(access_token='short_username')
        FacebookUserConverter(graph)
        action, user = connect_user(self.request, facebook_graph=graph)
        self.assertEqual(action, CONNECT_ACTIONS.REGISTER)
Esempio n. 28
0
    def test_persistent_graph(self):
        request = RequestMock().get('/')
        request.session = {}
        request.user = AnonymousUser()

        graph = get_facebook_graph(access_token='short_username')
        FacebookUserConverter(graph)
        action, user = connect_user(self.request, facebook_graph=graph)
        self.assertEqual(action, CONNECT_ACTIONS.REGISTER)
Esempio n. 29
0
def connect(request):
    '''
    Handles the view logic around connect user
    - (if authenticated) connect the user
    - login
    - register
    '''
    #test code time to remove
    uri = 'http://%s%s?facebook_login=1' % (request.META['HTTP_HOST'],
            request.path)
    if request.GET.get('redirect'):
        return facebook_login_required(uri, scope='read_stream')
    context = RequestContext(request)

    assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id '\
        'and ensure the context processor is enabled'
    facebook_login = bool(int(request.REQUEST.get('facebook_login', 0)))

    if facebook_login:
        graph = get_facebook_graph(request)
        if graph:
            facebook = FacebookUserConverter(graph)
            if facebook.is_authenticated():
                facebook_data = facebook.facebook_profile_data()
                #either, login register or connect the user
                try:
                    action, user = connect_user(request)
                except facebook_exceptions.IncompleteProfileError, e:
                    warn_message = u'Incomplete profile data encountered '\
                        'with error %s' % e
                    logger.warn(warn_message,
                        exc_info=sys.exc_info(), extra={
                        'request': request,
                        'data': {
                             'username': request.user.username,
                             'facebook_data': facebook.facebook_profile_data(),
                             'body': unicode(e),
                         }
                    })

                    context['facebook_mode'] = True
                    context['form'] = e.form
                    return render_to_response(
                        'registration/registration_form.html',
                        context_instance=context,
                    )

                if action is CONNECT_ACTIONS.CONNECT:
                    messages.info(request, _("You have connected your account "
                        "to %s's facebook profile") % facebook_data['name'])
                elif action is CONNECT_ACTIONS.REGISTER:
                    return user.get_profile().post_facebook_registration(request)
        else:
            return next_redirect(request, next_key=['error_next', 'next'],
                additional_params=dict(fb_error_or_cancel=1))

        return next_redirect(request)
Esempio n. 30
0
 def test_registration_form(self):
     '''
     Django_facebook should use user supplied registration form if given
     '''
     facebook_settings.FACEBOOK_REGISTRATION_FORM = 'django_facebook.test_utils.forms.SignupForm'
     facebook = get_facebook_graph(access_token='short_username')
     action, user = connect_user(self.request, facebook_graph=facebook)
     # The test form always sets username to test form
     self.assertEqual(user.username, 'Test form')
Esempio n. 31
0
def connect(request):
    '''
    Handles the view logic around connect user
    - (if authenticated) connect the user
    - login
    - register
    
    '''
    context = RequestContext(request)

    assert context.get(
        'FACEBOOK_APP_ID'
    ), 'Please specify a facebook app id and ensure the context processor is enabled'
    facebook_login = bool(int(request.REQUEST.get('facebook_login', 0)))

    if facebook_login:
        facebook = get_facebook_graph(request)
        if facebook.is_authenticated():
            facebook_data = facebook.facebook_profile_data()
            #either, login register or connect the user
            try:
                action, user = connect_user(request)
            except facebook_exceptions.IncompleteProfileError, e:
                logger.error(unicode(e),
                             exc_info=sys.exc_info(),
                             extra={
                                 'request': request,
                                 'data': {
                                     'username':
                                     request.user.username,
                                     'facebook_data':
                                     facebook.facebook_profile_data(),
                                     'body':
                                     unicode(e),
                                 }
                             })

                context['facebook_mode'] = True
                context['form'] = e.form
                return render_to_response(
                    'registration/registration_form.html', context)

            if action is CONNECT_ACTIONS.CONNECT:
                messages.info(
                    request,
                    _("You have connected your account to %s's facebook profile"
                      ) % facebook_data['name'])
            elif action is CONNECT_ACTIONS.REGISTER:
                response = user.get_profile().post_facebook_registration()
                return response
        else:
            return next_redirect(request,
                                 additional_params=dict(fb_error_or_cancel=1),
                                 next_key=['error_next', 'next'])

        return next_redirect(request)
Esempio n. 32
0
def connect(request):
    """
    Handles the view logic around connect user
    - (if authenticated) connect the user
    - login
    - register
    """
    context = RequestContext(request)

    assert context.get("FACEBOOK_APP_ID"), (
        "Please specify a facebook app id " "and ensure the context processor is enabled"
    )
    facebook_login = bool(int(request.REQUEST.get("facebook_login", 0)))

    if facebook_login:
        # code to redirect if we don't have adequate permissions
        from django_facebook.utils import test_permissions

        scope_list = facebook_settings.FACEBOOK_DEFAULT_SCOPE
        # standardizing the url to prevent things like attempt from being included
        redirect_uri = request.build_absolute_uri(request.path) + "?facebook_login=1"
        oauth_url, redirect_uri = get_oauth_url(request, scope_list, redirect_uri=redirect_uri)
        if not test_permissions(request, scope_list, redirect_uri):
            return HttpResponseRedirect(oauth_url)

        graph = get_persistent_graph(request)
        if graph:
            facebook = FacebookUserConverter(graph)
            if facebook.is_authenticated():
                facebook_data = facebook.facebook_profile_data()
                # either, login register or connect the user
                try:
                    action, user = connect_user(request)
                    logger.info("Django facebook, action was %s", action)
                except facebook_exceptions.IncompleteProfileError, e:
                    warn_message = u"Incomplete profile data encountered " u"with error %s" % e
                    send_warning(warn_message, e=e, facebook_data=facebook.facebook_profile_data())

                    context["facebook_mode"] = True
                    context["form"] = e.form
                    return render_to_response(
                        facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context
                    )

                if action is CONNECT_ACTIONS.CONNECT:
                    messages.info(
                        request,
                        _("You have connected your account " "to %s's facebook profile") % facebook_data["name"],
                    )
                elif action is CONNECT_ACTIONS.REGISTER:
                    return user.get_profile().post_facebook_registration(request)
        else:
            return next_redirect(request, next_key=["error_next", "next"], additional_params=dict(fb_error_or_cancel=1))

        return next_redirect(request)
Esempio n. 33
0
def _connect(request, graph):
    '''
    Handles the view logic around connect user
    - (if authenticated) connect the user
    - login
    - register

    We are already covered by the facebook_required_lazy decorator
    So we know we either have a graph and permissions, or the user denied
    the oAuth dialog
    '''
    backend = get_registration_backend()
    context = RequestContext(request)
    connect_facebook = to_bool(request.REQUEST.get('connect_facebook'))

    logger.info('trying to connect using Facebook')
    if graph:
        logger.info('found a graph object')
        converter = get_instance_for('user_conversion', graph)
        authenticated = converter.is_authenticated()
        # Defensive programming :)
        if not authenticated:
            raise ValueError('didnt expect this flow')

        logger.info('Facebook is authenticated')
        facebook_data = converter.facebook_profile_data()
        # either, login register or connect the user
        try:
            action, user = connect_user(
                request, connect_facebook=connect_facebook)
            logger.info('Django facebook performed action: %s', action)
        except facebook_exceptions.IncompleteProfileError, e:
            # show them a registration form to add additional data
            warning_format = u'Incomplete profile data encountered with error %s'
            warn_message = warning_format % unicode(e)
            send_warning(warn_message, e=e,
                         facebook_data=facebook_data)

            context['facebook_mode'] = True
            context['form'] = e.form

            #MJA modification to auto-register

            #backend.register(request, None, username='******', eamil='*****@*****.**', password1='Blahblah3')
            #return next_redirect(request)
            return render_to_response(
                facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE,
                context_instance=context,
            )
        except facebook_exceptions.AlreadyConnectedError, e:
            user_ids = [u.get_user_id() for u in e.users]
            ids_string = ','.join(map(str, user_ids))
            additional_params = dict(already_connected=ids_string)
            return backend.post_error(request, additional_params)
Esempio n. 34
0
 def test_gender_matching(self):
     request = RequestMock().get('/')
     request.session = {}
     request.user = AnonymousUser()
     graph = get_persistent_graph(request, access_token='paul')
     converter = FacebookUserConverter(graph)
     base_data = converter.facebook_profile_data()
     self.assertEqual(base_data['gender'], 'male')
     data = converter.facebook_registration_data()
     self.assertEqual(data['gender'], 'm')
     action, user = connect_user(self.request, facebook_graph=graph)
     self.assertEqual(user.get_profile().gender, 'm')
Esempio n. 35
0
 def test_long_username(self):
     request = RequestMock().get('/')
     request.session = {}
     request.user = AnonymousUser()
     graph = get_persistent_graph(request, access_token='long_username')
     converter = FacebookUserConverter(graph)
     base_data = converter.facebook_registration_data()
     action, user = connect_user(self.request, facebook_graph=graph)
     self.assertEqual(len(base_data['username']), 30)
     self.assertEqual(len(user.username), 30)
     self.assertEqual(len(user.first_name), 30)
     self.assertEqual(len(user.last_name), 30)
Esempio n. 36
0
 def test_gender_matching(self):
     request = RequestMock().get('/')
     request.session = {}
     request.user = AnonymousUser()
     graph = get_persistent_graph(request, access_token='paul')
     converter = FacebookUserConverter(graph)
     base_data = converter.facebook_profile_data()
     self.assertEqual(base_data['gender'], 'male')
     data = converter.facebook_registration_data()
     self.assertEqual(data['gender'], 'm')
     action, user = connect_user(self.request, facebook_graph=graph)
     self.assertEqual(user.get_profile().gender, 'm')
Esempio n. 37
0
 def test_long_username(self):
     request = RequestMock().get('/')
     request.session = {}
     request.user = AnonymousUser()
     graph = get_persistent_graph(request, access_token='long_username')
     converter = FacebookUserConverter(graph)
     base_data = converter.facebook_registration_data()
     action, user = connect_user(self.request, facebook_graph=graph)
     self.assertEqual(len(base_data['username']), 30)
     self.assertEqual(len(user.username), 30)
     self.assertEqual(len(user.first_name), 30)
     self.assertEqual(len(user.last_name), 30)
Esempio n. 38
0
 def is_authenticated(self, request, **kwargs):
     auth_params = request.META.get("HTTP_AUTHORIZATION", '')
     if auth_params:
         parts = auth_params.split()
         if len(parts) == 2:
             if parts[0] == 'Facebook':
                 access_token = parts[1]
                 try:
                     action, user = connect_user(request, access_token=access_token)
                     return True
                 except Exception, err:
                     logger.error('ERROR {0}: {1}'.format(self.__class__.__name__, str(err)))
Esempio n. 39
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)
Esempio n. 40
0
    def test_parallel_register(self):
        '''
        Adding some testing for the case when one person tries to register
        multiple times in the same second
        '''
        graph = get_facebook_graph(access_token='short_username')
        FacebookUserConverter(graph)
        action, user = connect_user(self.request, facebook_graph=graph)
        self.assertEqual(action, CONNECT_ACTIONS.REGISTER)

        self.request.user.is_authenticated = lambda: False
        with patch('django_facebook.connect.authenticate') as patched:
            return_sequence = [user, None]

            def side(*args, **kwargs):
                value = return_sequence.pop()
                return value

            patched.side_effect = side
            with patch('django_facebook.connect._register_user') as patched_register:
                patched_register.side_effect = facebook_exceptions.AlreadyRegistered('testing parallel registers')
                action, user = connect_user(self.request, facebook_graph=graph)
                self.assertEqual(action, CONNECT_ACTIONS.LOGIN)
Esempio n. 41
0
 def is_authenticated(self, request, **kwargs):
     auth_params = request.META.get("HTTP_AUTHORIZATION", '')
     if auth_params:
         parts = auth_params.split()
         if len(parts) == 2:
             if parts[0] == 'Facebook':
                 access_token = parts[1]
                 try:
                     action, user = connect_user(request,
                                                 access_token=access_token)
                     return True
                 except Exception, err:
                     logger.error('ERROR {0}: {1}'.format(
                         self.__class__.__name__, str(err)))
Esempio n. 42
0
 def post(self, request):
     serializer = self.serializer_class(data=request.DATA)
     if serializer.is_valid():
         action, user  = connect_user(self.request, serializer.data['access_token'])
         token, created = Token.objects.get_or_create(user=user)
         if created:
             create_default_categories(user=user)
         else:
             t = threading.Thread(target=update_user_profile,
                          args=[user])
             t.setDaemon(True)
             t.start()
         return Response({'token': token.key})
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Esempio n. 43
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)
Esempio n. 44
0
def fb_home(request):
    logging.debug('GM: fb_home request %s' % (request))
    #assumes they have been through enhanced fb auth and granted permissions, so just connect them
    from django_facebook.connect import connect_user
    #either, login register or connect the user
    action, user = connect_user(request)
    logging.debug('GM: fb_home user returned %s  with action %s' % (user, action))

    if user:
        #TODO: could check for the request ID and check everything is legit but at the moment assume it is
        #fb_request_ids = request.GET.get('request_ids', None)
        #we have AUTO_ACCEPT set true so no need to accept the invite here just go through
        return welcome(request)

    #somthing has gone wrong authenticating them go to homepage
    return render_to_response('home.html', context_instance=RequestContext(request))
Esempio n. 45
0
 def test_auth_backend(self):
     backend = FacebookBackend()
     facebook = get_facebook_graph(access_token='new_user')
     action, user = connect_user(self.request, facebook_graph=facebook)
     facebook_email = user.email
     facebook_id = user.get_profile().facebook_id
     auth_user = backend.authenticate(facebook_email=facebook_email)
     assert auth_user == user
     
     auth_user = backend.authenticate(facebook_id=facebook_id)
     assert auth_user == user
     
     auth_user = backend.authenticate(facebook_id=facebook_id, facebook_email=facebook_email)
     assert auth_user == user
     
     auth_user = backend.authenticate()
     assert not auth_user
Esempio n. 46
0
    def test_auth_backend(self):
        backend = FacebookBackend()
        facebook = get_facebook_graph(access_token="new_user")
        action, user = connect_user(self.request, facebook_graph=facebook)
        facebook_email = user.email
        facebook_id = user.get_profile().facebook_id
        auth_user = backend.authenticate(facebook_email=facebook_email)
        self.assertEqual(auth_user, user)

        auth_user = backend.authenticate(facebook_id=facebook_id)
        self.assertEqual(auth_user, user)

        auth_user = backend.authenticate(facebook_id=facebook_id, facebook_email=facebook_email)
        self.assertEqual(auth_user, user)

        auth_user = backend.authenticate()
        self.assertIsNone(auth_user)
Esempio n. 47
0
 def is_authenticated(self, request, **kwargs):
   auth_params = request.META.get('HTTP_X_FACEBOOK_AUTHENTICATION')
   if auth_params:
     parts = auth_params.split()
     if len(parts) == 2:
       if parts[0] == 'OAuth':
         access_token = parts[1]
         facebook = OpenFacebook(access_token)
         try:
           if facebook == None or not facebook.is_authenticated():
             return self._unauthorized()
               
           action, user = connect_user(request, access_token, facebook)
           request.user = user
           return True
         except Exception, err:
           logger.error('ERROR %s: %s' % (self.__class__.__name__, unicode(err)))
Esempio n. 48
0
 def test_auth_backend(self):
     backend = FacebookBackend()
     facebook = get_facebook_graph(access_token='new_user')
     action, user = connect_user(self.request, facebook_graph=facebook)
     facebook_email = user.email
     facebook_id = user.get_profile().facebook_id
     auth_user = backend.authenticate(facebook_email=facebook_email)
     assert auth_user == user
     
     auth_user = backend.authenticate(facebook_id=facebook_id)
     assert auth_user == user
     
     auth_user = backend.authenticate(facebook_id=facebook_id, facebook_email=facebook_email)
     assert auth_user == user
     
     auth_user = backend.authenticate()
     assert not auth_user
Esempio n. 49
0
    def test_registration_form(self):
        '''
        Django_facebook should use user supplied registration form if given
        '''
        from django.conf import settings
        if settings.MODE == 'userena':
            return

        test_form = 'django_facebook.test_utils.forms.SignupForm'
        old_setting = facebook_settings.FACEBOOK_REGISTRATION_FORM
        facebook_settings.FACEBOOK_REGISTRATION_FORM = test_form
        try:
            facebook = get_facebook_graph(access_token='short_username')
            action, user = connect_user(self.request, facebook_graph=facebook)
            # The test form always sets username to test form
            self.assertEqual(user.username, 'Test form')
        finally:
            facebook_settings.FACEBOOK_REGISTRATION_FORM = old_setting
Esempio n. 50
0
def connect(request):
    '''
    Handles the view logic around connect user
    - (if authenticated) connect the user
    - login
    - register
    
    '''
    context = RequestContext(request)
    facebook_login = bool(int(request.REQUEST.get('facebook_login', 0)))

    if facebook_login:
        facebook = get_facebook_graph(request)
        if facebook.is_authenticated():
            facebook_data = facebook.facebook_profile_data()
            #either, login register or connect the user
            try:
                action, user = connect_user(request)
            except facebook_exceptions.IncompleteProfileError, e:
                logger.error(unicode(e))
                messages.error(
                    request,
                    _("Please allow the request for permission in order to log in."
                      ))
                return next_redirect(request)

            if action is CONNECT_ACTIONS.CONNECT:
                messages.info(
                    request,
                    _("You have connected your account to %s's facebook profile"
                      ) % facebook_data['name'])
            elif action is CONNECT_ACTIONS.REGISTER:
                member_overview_url = user.get_profile().url['overview']
                response = HttpResponseRedirect(member_overview_url)
                response.set_cookie('fresh_registration', user.id)
                return response
        else:
            return next_redirect(request,
                                 additional_params=dict(fb_error_or_cancel=1))

        return next_redirect(request)
Esempio n. 51
0
    def test_auth_backend(self):
        # the auth backend
        backend = FacebookBackend()
        facebook = get_facebook_graph(access_token='new_user')
        action, user = connect_user(self.request, facebook_graph=facebook)
        facebook_email = user.email
        profile = try_get_profile(user)
        user_or_profile = get_instance_for_attribute(user, profile,
                                                     'facebook_id')
        facebook_id = user_or_profile.facebook_id
        auth_user = backend.authenticate(facebook_email=facebook_email)
        logger.info('%s %s %s', auth_user.email, user.email, facebook_email)
        self.assertEqual(auth_user, user)

        auth_user = backend.authenticate(facebook_id=facebook_id)
        self.assertEqual(auth_user, user)

        auth_user = backend.authenticate(facebook_id=facebook_id,
                                         facebook_email=facebook_email)
        self.assertEqual(auth_user, user)

        auth_user = backend.authenticate()
        self.assertIsNone(auth_user)
Esempio n. 52
0
def fblogin(request):
    # we store the place to redirct to in state

    graph = get_facebook_graph(request,
                               redirect_uri=settings.FACEBOOOK_REDIRECT_URI)
    action, user = connect_user(request, facebook_graph=graph)
    user.save()
    LinkedInProfile.objects.get_or_create(user=user)
    graph = get_facebook_graph(access_token=user.get_profile().access_token)
    graph_data = graph.get('/me')
    t = loader.get_template("profile.html")
    liApi = linkedin.LinkedIn('d4sg4uq23heb', 'CECqmTcwYr9GZod5',
                              'http://creeply.dev:8000/linkedin/login')
    result = liApi.request_token()
    if result:
        graph_data['liUrl'] = liApi.get_authorize_url()
        user.liProfile.request_token = liApi._request_token
        user.liProfile.request_token_secret = liApi._request_token_secret
        user.liProfile.save()
    graph_data[
        'img'] = 'https://graph.facebook.com/%s/picture?type=large' % user.get_profile(
        ).facebook_id
    c = Context(graph_data)
    return HttpResponse(t.render(c))
    def test_auth_backend(self):
        # the auth backend
        backend = FacebookBackend()
        facebook = get_facebook_graph(access_token='new_user')
        action, user = connect_user(self.request, facebook_graph=facebook)
        facebook_email = user.email
        profile = try_get_profile(user)
        user_or_profile = get_instance_for_attribute(user, profile,
                                                     'facebook_id')
        facebook_id = user_or_profile.facebook_id
        auth_user = backend.authenticate(facebook_email=facebook_email)

        #I GOT IT WORKING!!!!!!!!!!
        self.client.login(facebook_email=facebook_email)

        # response = self.client.get('/login/?testing=True')
        response = self.client.get('/login/')

        self.assertTemplateUsed(response, )
        template_names = []
        for template in response.templates:
            template_names.append(template.name)
        print template_names

        # logger.info('%s %s %s', auth_user.email, user.email, facebook_email)
        self.assertEqual(auth_user, user)

        auth_user = backend.authenticate(facebook_id=facebook_id)
        self.assertEqual(auth_user, user)

        auth_user = backend.authenticate(facebook_id=facebook_id,
                                         facebook_email=facebook_email)
        self.assertEqual(auth_user, user)

        auth_user = backend.authenticate()
        self.assertIsNone(auth_user)
Esempio n. 54
0
    def process_request(self, request):
        """
        This middleware authenticates the facebook user when
        he/she is accessing the app from facebook (not an internal page)
        The flow is show below:

        if referer is facebook:
            it's a canvas app and the first hit on the app
            If error:
                attempt to reauthenticate using authorization dialog
            if signed_request not sent or does not have the user_id and the access_token:
                user has not authorized app
                redirect to authorization dialog
            else:
                check permissions
                if user is authenticated (in django):
                    check if current facebook user is the same that is authenticated
                    if not: logout authenticated user
                if user is not authenticated:
                    connect_user (django_facebook.connect module)
                changed method to GET. Facebook always sends a POST first.
        else:
            It's an internal page.
            No signed_request is sent.
            Return
        """

        # This call cannot be global'ized or Django will return an empty response
        # after the first one
        redirect_login_oauth = ScriptRedirect(redirect_to=generate_oauth_url(),
                                              show_body=False)
        # check referer to see if this is the first access
        # or it's part of navigation in app
        # facebook always sends a POST reuqest
        referer = request.META.get('HTTP_REFERER', None)
        if referer:
            urlparsed = urlparse(referer)
            if not urlparsed.netloc.endswith('facebook.com'):
                return
            # when there is an error, we attempt to allow user to
            # reauthenticate
            if 'error' in request.GET:
                return redirect_login_oauth
        else:
            return

        # get signed_request
        signed_request = request.POST.get('signed_request', None)
        try:
            # get signed_request
            parsed_signed_request = FacebookAuthorization.parse_signed_data(
                signed_request)
            access_token = parsed_signed_request['oauth_token']
            facebook_id = int(parsed_signed_request['user_id'])
        except:
            # redirect to authorization dialog
            # if app not authorized by user
            return redirect_login_oauth
        # check for permissions
        try:
            graph = self.check_permissions(access_token)
        except MissingPermissionsError:
            return redirect_login_oauth
        # check if user authenticated and if it's the same
        if request.user.is_authenticated():
            self.check_django_facebook_user(request, facebook_id, access_token)
        request.facebook = graph
        if not request.user.is_authenticated():
            _action, _user = connect_user(request, access_token, graph)
        # override http method, since this actually is a GET
        if request.method == 'POST':
            request.method = 'GET'
        return
Esempio n. 55
0
def _connect(request, facebook_login):
    '''
    Handles the view logic around connect user
    - (if authenticated) connect the user
    - login
    - register
    '''
    backend = get_registration_backend()
    context = RequestContext(request)

    if True:
        logger.info('trying to connect using Facebook')
        graph = require_persistent_graph(request)
        authenticated = False
        if graph:
            logger.info('found a graph object')
            facebook = FacebookUserConverter(graph)
            authenticated = facebook.is_authenticated()

            if authenticated:
                logger.info('Facebook is authenticated')
                facebook_data = facebook.facebook_profile_data()
                #either, login register or connect the user : This is where it interfaces with Django
                try:
                    action, user = connect_user(request)
                    logger.info('Django facebook performed action: %s', action)
                    print user
                    print request.user
                except facebook_exceptions.IncompleteProfileError, e:
                    #show them a registration form to add additional data
                    warning_format = u'Incomplete profile data encountered with error %s'
                    warn_message = warning_format % e.message
                    send_warning(warn_message, e=e,
                                 facebook_data=facebook_data)

                    context['facebook_mode'] = True
                    context['form'] = e.form
                    return render_to_response(
                        facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE,
                        context_instance=context,
                    )
                except facebook_exceptions.AlreadyConnectedError, e:
                    user_ids = [u.user_id for u in e.users]
                    ids_string = ','.join(map(str, user_ids))
                    return error_next_redirect(
                        request,
                        additional_params=dict(already_connected=ids_string))

                if action is CONNECT_ACTIONS.CONNECT:
                    #connect means an existing account was attached to facebook
                    messages.info(request, _("You have connected your account "
                                             "to %s's facebook profile") % facebook_data['name'])
                elif action is CONNECT_ACTIONS.REGISTER:
                    #hook for tying in specific post registration functionality
                    #response = backend.post_registration_redirect(
                    #    request, user)
                    return HttpResponseRedirect(reverse('home_logged_home'))
                    #compatibility for Django registration backends which return redirect tuples instead of a response
                    if not isinstance(response, HttpResponse):
                        to, args, kwargs = response
                        response = redirect(to, *args, **kwargs)
                    return response
Esempio n. 56
0
 def test_short_username(self):
     facebook = get_facebook_graph(access_token='short_username')
     action, user = connect_user(self.request, facebook_graph=facebook)
     self.assertTrue(len(user.username) > 4)
     self.assertEqual(action, CONNECT_ACTIONS.REGISTER)