def _add_current_user_id(graph, user): ''' set the current user id, convenient if you want to make sure you fb session and user belong together ''' if graph: graph.current_user_id = None if user.is_authenticated(): profile = try_get_profile(user) facebook_id = get_user_attribute(user, profile, 'facebook_id') if facebook_id: graph.current_user_id = facebook_id
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)
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) profile = try_get_profile(user) gender = get_user_attribute(user, profile, 'gender') self.assertEqual(gender, 'm')
def test_send(error, expected_error_message, expected_new_token, has_permissions=False): user, profile, share = self.share_details update_user_attributes(user, profile, dict(new_token_required=False), save=True) with mock.patch('open_facebook.api.OpenFacebook') as mocked: instance = mocked.return_value instance.set = Mock(side_effect=error) instance.has_permissions = Mock(return_value=has_permissions) instance.access_token = get_user_attribute( user, profile, 'access_token') share.send(graph=instance) self.assertEqual(share.error_message, expected_error_message) self.assertFalse(share.completed_at) user = get_user_model().objects.get(id=user.id) if profile: profile = get_profile_model().objects.get(id=profile.id) new_token_required = get_user_attribute( user, profile, 'new_token_required') self.assertEqual(new_token_required, expected_new_token)
def get_facebook_graph(request=None, access_token=None, redirect_uri=None, raise_=False): ''' given a request from one of these - js authentication flow (signed cookie) - facebook app authentication flow (signed cookie) - facebook oauth redirect (code param in url) - mobile authentication flow (direct access_token) - offline access token stored in user profile returns a graph object redirect path is the path from which you requested the token for some reason facebook needs exactly this uri when converting the code to a token falls back to the current page without code in the request params specify redirect_uri if you are not posting and recieving the code on the same page ''' # this is not a production flow, but very handy for testing if not access_token and request.REQUEST.get('access_token'): access_token = request.REQUEST['access_token'] # should drop query params be included in the open facebook api, # maybe, weird this... from open_facebook import OpenFacebook, FacebookAuthorization from django.core.cache import cache expires = None if hasattr(request, 'facebook') and request.facebook: graph = request.facebook _add_current_user_id(graph, request.user) return graph # parse the signed request if we have it signed_data = None if request: signed_request_string = request.REQUEST.get('signed_data') if signed_request_string: logger.info('Got signed data from facebook') signed_data = parse_signed_request(signed_request_string) if signed_data: logger.info('We were able to parse the signed data') # the easy case, we have an access token in the signed data if signed_data and 'oauth_token' in signed_data: access_token = signed_data['oauth_token'] if not access_token: # easy case, code is in the get code = request.REQUEST.get('code') if code: logger.info('Got code from the request data') if not code: # signed request or cookie leading, base 64 decoding needed cookie_name = 'fbsr_%s' % facebook_settings.FACEBOOK_APP_ID cookie_data = request.COOKIES.get(cookie_name) if cookie_data: signed_request_string = cookie_data if signed_request_string: logger.info('Got signed data from cookie') signed_data = parse_signed_request(signed_request_string) if signed_data: logger.info('Parsed the cookie data') # the javascript api assumes a redirect uri of '' redirect_uri = '' if signed_data: # parsed data can fail because of signing issues if 'oauth_token' in signed_data: logger.info('Got access_token from parsed data') # we already have an active access token in the data access_token = signed_data['oauth_token'] else: logger.info('Got code from parsed data') # no access token, need to use this code to get one code = signed_data.get('code', None) if not access_token: if code: cache_key = hash_key('convert_code_%s' % code) access_token = cache.get(cache_key) if not access_token: # exchange the code for an access token # based on the php api # https://github.com/facebook/php-sdk/blob/master/src/base_facebook.php # create a default for the redirect_uri # when using the javascript sdk the default # should be '' an empty string # for other pages it should be the url if not redirect_uri: redirect_uri = '' # we need to drop signed_data, code and state redirect_uri = cleanup_oauth_url(redirect_uri) try: logger.info( 'trying to convert the code with redirect uri: %s', redirect_uri) # This is realy slow, that's why it's cached token_response = FacebookAuthorization.convert_code( code, redirect_uri=redirect_uri) expires = token_response.get('expires') access_token = token_response['access_token'] # would use cookies instead, but django's cookie setting # is a bit of a mess cache.set(cache_key, access_token, 60 * 60 * 2) except (open_facebook_exceptions.OAuthException, open_facebook_exceptions.ParameterException), e: # this sometimes fails, but it shouldnt raise because # it happens when users remove your # permissions and then try to reauthenticate logger.warn('Error when trying to convert code %s', unicode(e)) if raise_: raise else: return None elif request.user.is_authenticated(): # support for offline access tokens stored in the users profile profile = try_get_profile(request.user) access_token = get_user_attribute( request.user, profile, 'access_token') if not access_token: if raise_: message = 'Couldnt find an access token in the request or the users profile' raise open_facebook_exceptions.OAuthException(message) else: return None else: if raise_: message = 'Couldnt find an access token in the request or cookies' raise open_facebook_exceptions.OAuthException(message) else: return None
def connect_user(request, access_token=None, facebook_graph=None, connect_facebook=False): ''' 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') 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 # default behaviour is not to overwrite old data user = _connect_user(request, converter, overwrite=True) 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) profile = try_get_profile(auth_user) current_facebook_id = get_user_attribute(auth_user, profile, 'facebook_id') if not current_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 _update_user(user, facebook, overwrite=True): ''' Updates the user and his/her profile with the data from facebook ''' # if you want to add fields to ur user model instead of the # profile thats fine # partial support (everything except raw_data and facebook_id is included) facebook_data = facebook.facebook_registration_data(username=False) facebook_fields = [ 'facebook_name', 'facebook_profile_url', 'gender', 'date_of_birth', 'about_me', 'website_url', 'first_name', 'last_name' ] profile = try_get_profile(user) # which attributes to update attributes_dict = {} # send the signal that we're updating signals.facebook_pre_update.send(sender=get_user_model(), user=user, profile=profile, facebook_data=facebook_data) # set the facebook id and make sure we are the only user with this id current_facebook_id = get_user_attribute(user, profile, 'facebook_id') facebook_id_changed = facebook_data['facebook_id'] != current_facebook_id overwrite_allowed = overwrite or not current_facebook_id # update the facebook id and access token facebook_id_overwritten = False if facebook_id_changed and overwrite_allowed: # when not overwriting we only update if there is no # profile.facebook_id logger.info('profile facebook id changed from %s to %s', repr(facebook_data['facebook_id']), repr(current_facebook_id)) attributes_dict['facebook_id'] = facebook_data['facebook_id'] facebook_id_overwritten = True if facebook_id_overwritten: _remove_old_connections(facebook_data['facebook_id'], user.id) # update all fields on both user and profile for f in facebook_fields: facebook_value = facebook_data.get(f, False) current_value = get_user_attribute(user, profile, f, None) if facebook_value and not current_value: attributes_dict[f] = facebook_value # write the raw data in case we missed something serialized_fb_data = json.dumps(facebook.facebook_profile_data()) current_raw_data = get_user_attribute(user, profile, 'raw_data') if current_raw_data != serialized_fb_data: attributes_dict['raw_data'] = serialized_fb_data image_url = facebook_data['image'] # update the image if we are allowed and have to if facebook_settings.FACEBOOK_STORE_LOCAL_IMAGE: image_field = get_user_attribute(user, profile, 'image', True) if not image_field: image_name, image_file = _update_image(profile, image_url) image_field.save(image_name, image_file) # save both models if they changed update_user_attributes(user, profile, attributes_dict) if getattr(user, '_fb_is_dirty', False): user.save() if getattr(profile, '_fb_is_dirty', False): profile.save() signals.facebook_post_update.send(sender=get_user_model(), user=user, profile=profile, facebook_data=facebook_data) return user