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
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)
def home(request): if (not request.user.pk is None ) and request.user.userprofile.terms_conditions: # Get the graph from the FB API if not 'num_friends' in request.session or not 'friends' in request.session: graph = get_facebook_graph(request=request) friends = graph.get('me/friends', fields='')['data'] friends = [f['name'] for f in friends] request.session['friends'] = friends request.session['num_friends'] = len(friends) user_list = UserProfile.objects.exclude( pk=-1).order_by('-score_global') count = 0 for u in user_list: count += 1 if u.user.id == request.user.id: rank = count break context = RequestContext(request) context_dict = {'user': request.user, 'rank': rank} return render_to_response('home.html', context_dict, context_instance=context) else: return HttpResponseRedirect('/canvas/terms/')
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
def test_check_connect_facebook(self): graph = get_facebook_graph(access_token='new_user') facebook = FacebookUserConverter(graph) data = facebook.facebook_registration_data() self.assertEqual(data['gender'], 'm') response = self.client.get(reverse('login:index'))
def test_graph_fql(self): from django_facebook.api import get_app_access_token token = get_app_access_token() facebook = get_facebook_graph(access_token=token, persistent_token=False) query = 'SELECT name FROM user WHERE uid = me()' result = facebook.fql(query) assert result == []
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)
def get_facebook_friends(request): open_graph = get_facebook_graph(request) converter = FacebookUserConverter(open_graph) friends = converter.open_facebook.fql( u"SELECT uid, name, birthday, sex FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())" ) return friends
def downsize(request): user = request.user saving_category_list = SavingCategory.objects.all() ds_saving_types_list = Saving.objects.filter(ds_suggested=True) ds_saving_points_list = [] for saving in ds_saving_types_list: try: ds_saving_points_list.append(SavingRelationship.objects.get(userprofile=user.userprofile, saving=saving).saving_points) except: ds_saving_points_list.append(0) ds_zipped = zip(ds_saving_types_list, ds_saving_points_list) crowd_saving_types_list = Saving.objects.filter(ds_suggested=False) crowd_saving_points_list = [] for saving in crowd_saving_types_list: try: crowd_saving_points_list.append(SavingRelationship.objects.get(userprofile=user.userprofile, saving=saving).saving_points) except: crowd_saving_points_list.append(0) crowd_zipped = zip(crowd_saving_types_list, crowd_saving_points_list) if request.method == 'POST': form = DownsizeForm(user, request.POST) downsize = form.save() downsize = CreateDownsize(downsize, user) #facebook_user = get_user_from_cookie(request.COOKIES, FACEBOOK_API_KEY, FACEBOOK_APP_SECRET) graph = get_facebook_graph(request=request) downsize_amount = str(downsize.downsize_amount) saving = str(downsize.saving) post_string = "I downsized $" + downsize_amount + " by " + saving graph.put_wall_post(post_string) return HttpResponseRedirect('../dashboard') else: form = DownsizeForm(user) return render_to_response('goals/downsize.html', {'form': form, 'user': user, 'ds_zipped': ds_zipped, 'crowd_zipped': crowd_zipped, 'saving_category_list': saving_category_list}, context_instance=RequestContext(request))
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)
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)
def stats(request): if (not request.user.pk is None ) and request.user.facebookprofile.facebook_id: # Get the graph from the FB API graph = get_facebook_graph(request=request) request.user.facebookprofile.facebook_id = graph.get('me', fields='id')['id'] request.user.facebookprofile.save() if (not request.user.pk is None ) and request.user.facebookprofile.facebook_id in SUPERUSER_ID: context = RequestContext(request) static_stats_path = Base.STATICFILES_DIRS[0] + '/static/stats/' # Get Data Base usr = list(UserProfile.objects.all().order_by('user__date_joined')) img = list(Picture.objects.all().order_by('date')) vte = list(Votes.objects.all().order_by('date')) rpt = list(Report.objects.all().order_by('date')) plot_stats(usr, img, vte, rpt, static_stats_path) context_dict = { 'num_usr': len(usr), 'num_img': len(img), 'num_vte': len(vte), 'num_rpt': len(rpt), } return render_to_response('stats.html', context_dict, context_instance=context) else: return HttpResponseRedirect('/canvas/terms/')
def connect_user(request, access_token=None, facebook_graph=None): ''' Given a request either - (if authenticated) connect the user - login - register ''' #TODO, instead of using access_token this should probably accept a facebook_graph as well user = None facebook = facebook_graph or get_facebook_graph(request, access_token) assert facebook.is_authenticated() facebook_data = facebook.facebook_profile_data() force_registration = request.REQUEST.get('force_registration') or request.REQUEST.get('force_registration_hard') logger.debug('force registration is set to %s', force_registration) if request.user.is_authenticated() and not force_registration: action = CONNECT_ACTIONS.CONNECT user = _connect_user(request, facebook) else: email = facebook_data.get('email', False) email_verified = facebook_data.get('verified', False) kwargs = {} if email and email_verified: kwargs = {'facebook_email': email} authenticated_user = authenticate(facebook_id=facebook_data['id'], **kwargs) if authenticated_user and not force_registration: action = CONNECT_ACTIONS.LOGIN ## Has the user registered without Facebook, using the verified FB email address? # It is after all quite common to use email addresses for usernames if not authenticated_user.get_profile().facebook_id: update = True else: update = getattr(authenticated_user, 'fb_update_required', False) user = _login_user(request, facebook, authenticated_user, update=update) else: action = CONNECT_ACTIONS.REGISTER user = _register_user(request, facebook) #store likes and friends if configured sid = transaction.savepoint() try: if facebook_settings.FACEBOOK_STORE_LIKES: likes = facebook.get_likes() facebook.store_likes(user, likes) if facebook_settings.FACEBOOK_STORE_FRIENDS: friends = facebook.get_friends() facebook.store_friends(user, friends) transaction.savepoint_commit(sid) except IntegrityError, e: logger.warn(u'Integrity error encountered during registration, probably a double submission %s' % e, exc_info=sys.exc_info(), extra={ 'request': request, 'data': { 'body': unicode(e), } }) transaction.savepoint_rollback(sid)
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)
def connect_user(request, access_token=None): ''' Given a request either - (if authenticated) connect the user - login - register ''' user = None facebook = get_facebook_graph(request, access_token) assert facebook.is_authenticated() facebook_data = facebook.facebook_profile_data() force_registration = request.REQUEST.get('force_registration') or request.REQUEST.get('force_registration_hard') logger.debug('force registration is set to %s', force_registration) if request.user.is_authenticated() and not force_registration: action = CONNECT_ACTIONS.CONNECT user = _connect_user(request, facebook) else: email = facebook_data.get('email', False) email_verified = facebook_data.get('verified', False) kwargs = {} if email and email_verified: kwargs = {'facebook_email': email} authenticated_user = authenticate(facebook_id=facebook_data['id'], **kwargs) if authenticated_user and not force_registration: action = CONNECT_ACTIONS.LOGIN user = _login_user(request, facebook, authenticated_user, update=getattr(authenticated_user, 'fb_update_required', False)) else: action = CONNECT_ACTIONS.REGISTER user = _register_user(request, facebook) return action, user
def login_success(request): graph = get_facebook_graph(request) facebook_me = graph.get("me") print facebook_me name = facebook_me["name"] email = facebook_me["email"] facebook_id = facebook_me["id"] try: curUser = DogeUser.objects.get(facebook_id=facebook_id) except ObjectDoesNotExist: curUser = DogeUser.objects.create_user(email,name,facebook_id) primary_id = curUser.id user_info = { "name" : name, "email" : email, "facebook_id" : facebook_id, "primary_id" : primary_id } request.session["user_info"] = user_info return HttpResponseRedirect(reverse("index"))
def my_style(request): context = RequestContext(request) context['auth_url'] = generate_oauth_url() context['facebook'] = fb = get_facebook_graph(request) return render_to_response('django_facebook/my_style.html', context)
def run(self): try: access_token = UserSocialAuth.objects.get(user=self.user, provider='facebook').extra_data['access_token'] self.graph = get_facebook_graph(access_token=access_token) if self.graph: for n in range(0, 5): try: url = None try: if u'class' in self.params: url = self.params[u'class'] elif u'link' in self.params: url = self.params[u'link'] if url: self.graph.set(u'/', {'ids' : url, 'scrape' : 'true'}) except OAuthException: LoggingHelper.getDebugLogger().debug(u'Error while scraping {0}'.format(url), exc_info=1) return self.graph.set(u'{0}/{1}'.format(self.facebook_id, self.action), self.params) except PermissionException: LoggingHelper.getDebugLogger().debug(u'Permission not granted (facebook_id : {0}, action {1}, params {2})'.format(self.facebook_id, self.action, self.params), exc_info=1) except OAuthException: LoggingHelper.getDebugLogger().debug(u'Refreshing token (facebook_id : {0}, action {1}, params {2})'.format(self.facebook_id, self.action, self.params), exc_info=1) self.refresh_token() except OpenFacebookException: LoggingHelper.getErrorLogger().error(u'Error while posting on Facebook (facebook_id : {0}, action {1}, params {2})'.format(self.facebook_id, self.action, self.params), exc_info=1) time.sleep((2 ** n) + (random.randint(0, 1000) / 1000)) except UserSocialAuth.DoesNotExist: LoggingHelper.getDebugLogger().debug('No access token')
def facebook_task(user, facebook_id, action, params): try: user_social = UserSocialAuth.objects.get(user=user, provider='facebook') access_token = user_social.extra_data['access_token'] graph = get_facebook_graph(access_token=access_token) if graph: for n in range(0, 5): try: url = None try: if u'class' in params: url = params[u'class'] elif u'link' in params: url = params[u'link'] if url: graph.set(u'/', {'ids': url, 'scrape': 'true'}) except OAuthException: LoggingHelper.getDebugLogger().debug( u'Error while scraping {0}'.format(url), exc_info=1) return graph.set(u'{0}/{1}'.format(facebook_id, action), params) except PermissionException: LoggingHelper.getDebugLogger().debug( u'Permission not granted (facebook_id : {0}, action {1}, params {2})' .format(facebook_id, action, params), exc_info=1) except OAuthException: LoggingHelper.getDebugLogger().debug( u'Refreshing token (facebook_id : {0}, action {1}, params {2})' .format(facebook_id, action, params), exc_info=1) try: user_social.refresh_token() except Exception: pass except OpenFacebookException: LoggingHelper.getErrorLogger().error( u'Error while posting on Facebook (facebook_id : {0}, action {1}, params {2})' .format(facebook_id, action, params), exc_info=1) time.sleep((2**n) + (random.randint(0, 1000) / 1000)) if action in [ '{0}:invite_participate'.format( settings.FACEBOOK_OPEN_GRAPH_ROOT_NAME), '{0}:invite_cowrite'.format( settings.FACEBOOK_OPEN_GRAPH_ROOT_NAME) ]: facebook_task.apply_async([ user, facebook_id, '{0}:{1}'.format( settings.FACEBOOK_OPEN_GRAPH_ROOT_NAME, 'cowrite'), params ]) break except UserSocialAuth.DoesNotExist: LoggingHelper.getDebugLogger().debug('No access token')
def connect_user(request, access_token=None, facebook_graph=None): """ Given a request either - (if authenticated) connect the user - login - register """ user = None graph = facebook_graph or get_facebook_graph(request, access_token) facebook = FacebookUserConverter(graph) assert facebook.is_authenticated() facebook_data = facebook.facebook_profile_data() force_registration = request.REQUEST.get("force_registration") or request.REQUEST.get("force_registration_hard") logger.debug("force registration is set to %s", force_registration) if request.user.is_authenticated() and not force_registration: action = CONNECT_ACTIONS.CONNECT user = _connect_user(request, facebook) else: email = facebook_data.get("email", False) email_verified = facebook_data.get("verified", False) kwargs = {} if email and email_verified: kwargs = {"facebook_email": email} auth_user = authenticate(facebook_id=facebook_data["id"], **kwargs) if auth_user and not force_registration: action = CONNECT_ACTIONS.LOGIN # Has the user registered without Facebook, using the verified FB # email address? # It is after all quite common to use email addresses for usernames if not auth_user.get_profile().facebook_id: update = True else: update = getattr(auth_user, "fb_update_required", False) user = _login_user(request, facebook, auth_user, update=update) else: action = CONNECT_ACTIONS.REGISTER user = _register_user(request, facebook) # store likes and friends if configured sid = transaction.savepoint() try: if facebook_settings.FACEBOOK_STORE_LIKES: likes = facebook.get_likes() facebook.store_likes(user, likes) if facebook_settings.FACEBOOK_STORE_FRIENDS: friends = facebook.get_friends() facebook.store_friends(user, friends) transaction.savepoint_commit(sid) except IntegrityError, e: logger.warn( u"Integrity error encountered during registration, " "probably a double submission %s" % e, exc_info=sys.exc_info(), extra={"request": request, "data": {"body": unicode(e)}}, ) transaction.savepoint_rollback(sid)
def connect_user(request, access_token=None, facebook_graph=None): ''' Given a request either - (if authenticated) connect the user - login - register ''' user = None graph = facebook_graph or get_facebook_graph(request, access_token) converter = get_instance_for('user_conversion', graph) assert converter.is_authenticated() facebook_data = converter.facebook_profile_data() force_registration = request.REQUEST.get('force_registration') or\ request.REQUEST.get('force_registration_hard') connect_facebook = to_bool(request.REQUEST.get('connect_facebook')) logger.debug('force registration is set to %s', force_registration) if connect_facebook and request.user.is_authenticated() and not force_registration: # we should only allow connect if users indicate they really want to connect # only when the request.CONNECT_FACEBOOK = 1 # if this isn't present we just do a login action = CONNECT_ACTIONS.CONNECT user = _connect_user(request, converter) else: email = facebook_data.get('email', False) email_verified = facebook_data.get('verified', False) kwargs = {} if email and email_verified: kwargs = {'facebook_email': email} auth_user = authenticate(facebook_id=facebook_data['id'], **kwargs) if auth_user and not force_registration: action = CONNECT_ACTIONS.LOGIN # Has the user registered without Facebook, using the verified FB # email address? # It is after all quite common to use email addresses for usernames update = getattr(auth_user, 'fb_update_required', False) if not auth_user.get_profile().facebook_id: update = True # login the user user = _login_user(request, converter, auth_user, update=update) else: action = CONNECT_ACTIONS.REGISTER # when force registration is active we should remove the old profile try: user = _register_user(request, converter, remove_old_connections=force_registration) except facebook_exceptions.AlreadyRegistered, e: # in Multithreaded environments it's possible someone beats us to # the punch, in that case just login logger.info('parallel register encountered, slower thread is doing a login') auth_user = authenticate( facebook_id=facebook_data['id'], **kwargs) action = CONNECT_ACTIONS.LOGIN user = _login_user(request, converter, auth_user, update=False)
def connect_user(request, access_token=None, facebook_graph=None): ''' Given a request either - (if authenticated) connect the user - login - register ''' user = None graph = facebook_graph or get_facebook_graph(request, access_token) facebook = FacebookUserConverter(graph) assert facebook.is_authenticated() facebook_data = facebook.facebook_profile_data() force_registration = request.REQUEST.get('force_registration') or\ request.REQUEST.get('force_registration_hard') connect_facebook = bool(int(request.REQUEST.get('connect_facebook', 0))) logger.debug('force registration is set to %s', force_registration) if connect_facebook and request.user.is_authenticated( ) and not force_registration: #we should only allow connect if users indicate they really want to connect #only when the request.CONNECT_FACEBOOK = 1 #if this isn't present we just do a login action = CONNECT_ACTIONS.CONNECT user = _connect_user(request, facebook) else: email = facebook_data.get('email', False) email_verified = facebook_data.get('verified', False) kwargs = {} if email and email_verified: kwargs = {'facebook_email': email} auth_user = authenticate(facebook_id=facebook_data['id'], **kwargs) if auth_user and not force_registration: action = CONNECT_ACTIONS.LOGIN # Has the user registered without Facebook, using the verified FB # email address? # It is after all quite common to use email addresses for usernames if not auth_user.get_profile().facebook_id: update = True else: update = getattr(auth_user, 'fb_update_required', False) user = _login_user(request, facebook, auth_user, update=update) else: action = CONNECT_ACTIONS.REGISTER # when force registration is active we should clearout # the old profile user = _register_user(request, facebook, remove_old_connections=force_registration) _update_likes_and_friends(request, user, facebook) _update_access_token(user, graph) return action, user
def connect_user(request, access_token=None, facebook_graph=None): ''' Given a request either - (if authenticated) connect the user - login - register ''' user = None graph = facebook_graph or get_facebook_graph(request, access_token) facebook = FacebookUserConverter(graph) assert facebook.is_authenticated() facebook_data = facebook.facebook_profile_data() force_registration = request.REQUEST.get('force_registration') or\ request.REQUEST.get('force_registration_hard') connect_facebook = to_bool(request.REQUEST.get('connect_facebook')) logger.debug('force registration is set to %s', force_registration) if connect_facebook and request.user.is_authenticated() and not force_registration: #we should only allow connect if users indicate they really want to connect #only when the request.CONNECT_FACEBOOK = 1 #if this isn't present we just do a login action = CONNECT_ACTIONS.CONNECT user = _connect_user(request, facebook) else: email = facebook_data.get('email', False) email_verified = facebook_data.get('verified', False) kwargs = {} if email and email_verified: kwargs = {'facebook_email': email} auth_user = authenticate(facebook_id=facebook_data['id'], **kwargs) if auth_user and not force_registration: action = CONNECT_ACTIONS.LOGIN # Has the user registered without Facebook, using the verified FB # email address? # It is after all quite common to use email addresses for usernames update = getattr(auth_user, 'fb_update_required', False) if not auth_user.get_profile().facebook_id: update = True #login the user user = _login_user(request, facebook, auth_user, update=update) else: action = CONNECT_ACTIONS.REGISTER # when force registration is active we should remove the old profile try: user = _register_user(request, facebook, remove_old_connections=force_registration) except facebook_exceptions.AlreadyRegistered, e: #in Multithreaded environments it's possible someone beats us to #the punch, in that case just login logger.info('parallel register encountered, slower thread is doing a login') auth_user = authenticate( facebook_id=facebook_data['id'], **kwargs) action = CONNECT_ACTIONS.LOGIN user = _login_user(request, facebook, auth_user, update=False)
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')
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)
def connect_user(request, access_token=None, facebook_graph=None): ''' Given a request either - (if authenticated) connect the user - login - register ''' user = None graph = facebook_graph or get_facebook_graph(request, access_token) facebook = FacebookUserConverter(graph) assert facebook.is_authenticated() facebook_data = facebook.facebook_profile_data() force_registration = request.REQUEST.get('force_registration') or\ request.REQUEST.get('force_registration_hard') connect_facebook = bool(int(request.REQUEST.get('connect_facebook', 0))) logger.debug('force registration is set to %s', force_registration) if connect_facebook and request.user.is_authenticated() and not force_registration: #we should only allow connect if users indicate they really want to connect #only when the request.CONNECT_FACEBOOK = 1 #if this isn't present we just do a login action = CONNECT_ACTIONS.CONNECT user = _connect_user(request, facebook) else: email = facebook_data.get('email', False) email_verified = facebook_data.get('verified', False) kwargs = {} if email and email_verified: kwargs = {'facebook_email': email} auth_user = authenticate(facebook_id=facebook_data['id'], **kwargs) if auth_user and not force_registration: action = CONNECT_ACTIONS.LOGIN # Has the user registered without Facebook, using the verified FB # email address? # It is after all quite common to use email addresses for usernames if not auth_user.get_profile().facebook_id: update = True else: update = getattr(auth_user, 'fb_update_required', False) user = _login_user(request, facebook, auth_user, update=update) else: action = CONNECT_ACTIONS.REGISTER # when force registration is active we should clearout # the old profile user = _register_user(request, facebook, remove_old_connections=force_registration) _update_likes_and_friends(request, user, facebook) _update_access_token(user, graph) return action, user
def refresh_facebook_graph(request): request.facebook, success = None, False access_token = request.POST.get('access_token', None) graph = get_facebook_graph(request, access_token=access_token) if graph is not None and graph.access_token: request.session['graph_dict'] = graph.__getstate__() success = True return HttpResponse(json.dumps({'success': success}), mimetype='application/json')
def test_photo_put(self): from django_facebook.api import get_app_access_token token = get_app_access_token() graph = get_facebook_graph(access_token=token, persistent_token=False) tags = simplejson.dumps([{'x':50, 'y':50, 'tag_uid':12345}, {'x':10, 'y':60, 'tag_text':'a turtle'}]) try: graph.put_photo('img.jpg', 'Look at this cool photo!', None, tags=tags) except GraphAPIError, e: assert 'An active access token must be used to query information' in unicode(e)
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')
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)
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)
def create(self, request, **kwargs): user = None access_token = request.DATA.get('access_token', None) graph = get_facebook_graph(request, access_token) facebook = FacebookUserConverter(graph) try: assert facebook.is_authenticated() except OAuthException, ex: return Response({"error": ex.message}, status=status.HTTP_401_UNAUTHORIZED)
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
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 canvas(request): context = RequestContext(request) context['auth_url'] = generate_oauth_url() context['facebook'] = fb = get_facebook_graph(request) if fb.is_authenticated(): likes = context['facebook'].get_connections("me", "likes", limit=3) logger.info('found these likes %s', likes) return render_to_response('django_facebook/canvas.html', context)
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_graphapi(request): graph = get_facebook_graph(request) friends = graph.get("/me/friends") friends = friends['data'] flikes = {} i = 0 for fr in friends: fr_id = str(fr['id']) t = Thread(target=myfunc, args=((fr_id, graph, i), )) t.start() i += 1 return HttpResponse("Done")
def test_graphapi(request): graph = get_facebook_graph(request) friends = graph.get("/me/friends") friends = friends['data'] flikes = {} i=0 for fr in friends: fr_id = str(fr['id']) t = Thread(target=myfunc, args=((fr_id,graph,i),)) t.start() i += 1 return HttpResponse("Done")
def get_friends_pics(request): from core.tasks import make_mosaic Mosaic.objects.filter(user=request.user).delete() open_graph = get_facebook_graph(request) converter = FacebookUserConverter(open_graph) pics_raw = converter.open_facebook.fql( u"SELECT pic FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())" ) pics = [x["pic"] for x in pics_raw] make_mosaic.apply_async(kwargs=dict(user=request.user, pics_urls=pics)) return
def setupFBUpdates(request): graph = get_facebook_graph(request) #get app's access token access_token = FacebookAuthorization.get_app_access_token() params = {'access_token': access_token} postdata = {'object': 'user', 'fields': "friends,music,books,movies,tv,likes", 'callback_url':"http://www.popcore.me/realtime/receive_fb_updates", 'verify_token':VERIFY_TOKEN } url = '%s%s?%s' % ("https://graph.facebook.com/", FACEBOOK_APP_ID + "/subscriptions", urllib.urlencode(params)) res= graph._request(url, post_data=postdata) #now check the new update configuration #import pprint response = graph._request(url) return HttpResponse(pprint.pformat(response))
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 ranking(request): if (not request.user.pk is None ) and request.user.userprofile.terms_conditions: context = RequestContext(request) # Get the graph from the FB API if not 'friends' in request.session: graph = get_facebook_graph(request=request) friends = graph.get('me/friends', fields='')['data'] friends = [f['name'] for f in friends] request.session['friends'] = friends friends = request.session['friends'] # Load users ordered by global score user_list = UserProfile.objects.exclude( pk=-1).order_by('-score_global') count = 0 rank = -1 for u in user_list: count += 1 if u.user.id == request.user.id: rank = count break user_list = user_list[:50] user_rank = rank if rank > 50 else -1 friends_user_list = UserProfile.objects.filter( user__facebookprofile__facebook_name__in=friends) friends_user_list = friends_user_list | UserProfile.objects.filter( user=request.user) friends_user_list = friends_user_list.order_by('-score_global') context_dict = { 'users': user_list, 'user': request.user, 'rank': user_rank, 'friends': friends_user_list } return render_to_response('ranking.html', context_dict, context_instance=context) else: return HttpResponseRedirect('/canvas/terms/')
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
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'))
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