def _exchange_oauth_code_for_access_token(code, redirect_uri=None): """Try to exchange an OAuth `code` for a proper access_token. Following code is based on the PHP API: https://github.com/facebook/php-sdk/blob/master/src/base_facebook.php """ if not code: return None ## Create a default for the redirect_uri: ## - when using the JavaScript SDK the default should be '' ## - for other pages it should be the URL of the current page. if not redirect_uri: redirect_uri = '' ## We need to remove ``signed_request``, ``code`` and ``state`` ## GET parameters from the current URL. redirect_uri = cleanup_oauth_url(redirect_uri) try: logger.info('Trying to exchange the code for an access_token. redirect_uri=%r', redirect_uri) token_response = FacebookAuthorization.convert_code(code, redirect_uri=redirect_uri) expires = token_response.get('expires') access_token = token_response['access_token'] except open_facebook_exceptions.OAuthException, e: ## This sometimes fails, but it shouldn't raise exceptions ## because this happens when an user deauthorizes your ## application and then tries to re-authenticate. logger.warn('Exchange of code %r failed.', unicode(e))
def _get_access_token_from_signed_request(request, redirect_uri=None): """Try to retrieve an access_token from a signed request""" ## Check whether we got any signed request _signed_data = None signed_data = request.REQUEST.get('signed_request') if signed_data: logger.info('Got signed data from Facebook') _signed_data = signed_data else: cookie_name = 'fbsr_%s' % facebook_settings.FACEBOOK_APP_ID cookie_data = request.COOKIES.get(cookie_name) if cookie_data: logger.info('Got signed cookie from Facebook') _signed_data = cookie_data if _signed_data: parsed_data = FacebookAuthorization.parse_signed_data(signed_data) if parsed_data: logger.debug('Parsing of signed data was successful') ## Parsed data can fail because of signing issues if 'oauth_token' in parsed_data: logger.info('The signed data contains a valid oauth_token') ## We already have an active access token in the data access_token = parsed_data['oauth_token'] return dict(access_token=access_token) else: logger.info('Got code from parsed data') ## no access token, need to use this code to get one code = parsed_data.get('code', None) return _exchange_oauth_code_for_access_token(code, redirect_uri)
def notify_bidders_thread(**kwargs): auction = kwargs['auction'] text = '' if kwargs['signal'] == 'auction_started': text = u'The auction for a {item} has started. Hurry and go win it!.'.format( item=auction.item.name) if kwargs['signal'] == 'precap_finishing': text = u'The auction for a {item} is about to start. Go play for it!.'.format( item=auction.item.name) for member in auction.bidders.all(): of = OpenFacebook(member.access_token) args = { 'template': text, 'access_token': FacebookAuthorization.get_app_access_token() } destination = '{facebook_id}/notifications'.format( facebook_id=member.facebook_id) response = of.set(destination, **args)
def get_facebook_access_token(request): me = [] if request.method == 'GET': code = request.GET.get('code',None) redirect_uri = "http://localhost:8000%s" % reverse('facebook-access') response=FacebookAuthorization.convert_code(code,redirect_uri =redirect_uri) access_token=response.get('access_token',None) expire = response.get('expires',None) expiration = datetime.datetime.now() + datetime.timedelta(seconds=int(expire)) try: stored_token = FaceBookAcessToken.objects.all()[0] stored_token.access_token=access_token stored_token.expiration=expiration except: stored_token = FaceBookAcessToken(access_token=access_token,expiration=expiration) stored_token.save() facebook=OpenFacebook(access_token) me =facebook.get('me') return render(request,"facebook_access/facebook_access.html", {"me":me,})
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) as 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 graph = OpenFacebook(access_token, signed_data, expires=expires) # add user specific identifiers if request: _add_current_user_id(graph, request.user) return graph
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 parsed_data = None expires = None if hasattr(request, "facebook"): graph = request.facebook _add_current_user_id(graph, request.user) return graph 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 signed_data = request.REQUEST.get("signed_request") cookie_name = "fbsr_%s" % facebook_settings.FACEBOOK_APP_ID cookie_data = request.COOKIES.get(cookie_name) if cookie_data: signed_data = cookie_data # the javascript api assumes a redirect uri of '' redirect_uri = "" if signed_data: logger.info("Got signed data from facebook") parsed_data = FacebookAuthorization.parse_signed_data(signed_data) if parsed_data: logger.info("Got parsed data from facebook") # parsed data can fail because of signing issues if "oauth_token" in parsed_data: logger.info("Got access_token from parsed data") # we already have an active access token in the data access_token = parsed_data["oauth_token"] else: logger.info("Got code from parsed data") # no access token, need to use this code to get one code = parsed_data.get("code", None) if not access_token: if code: cache_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_request, 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, 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 = request.user.get_profile() access_token = getattr(profile, "access_token", None) 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 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 parsed_data = None expires = None if hasattr(request, 'facebook'): graph = request.facebook _add_current_user_id(graph, request.user) return graph 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 signed_data = request.REQUEST.get('signed_request') cookie_name = 'fbsr_%s' % facebook_settings.FACEBOOK_APP_ID cookie_data = request.COOKIES.get(cookie_name) if cookie_data: signed_data = cookie_data #the javascript api assumes a redirect uri of '' redirect_uri = '' if signed_data: logger.info('Got signed data from facebook') parsed_data = FacebookAuthorization.parse_signed_data( signed_data) if parsed_data: logger.info('Got parsed data from facebook') #parsed data can fail because of signing issues if 'oauth_token' in parsed_data: logger.info('Got access_token from parsed data') # we already have an active access token in the data access_token = parsed_data['oauth_token'] else: logger.info('Got code from parsed data') # no access token, need to use this code to get one code = parsed_data.get('code', None) if not access_token: if code: cache_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_request, 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, 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 = request.user.get_profile() access_token = getattr(profile, 'access_token', None) 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 registered_facebook(request): global token social_account = None username = '' try: token = request.POST.get('access_token') long_access_token = FacebookAuthorization.extend_access_token(token)['access_token'] print 'long is generated' print long_access_token except Exception as e: print e print "register 1" long_access_token = token print long_access_token try: graph = OpenFacebook(long_access_token) profile = graph.get('me') profile_id = profile['id'] # profile_email = profile['email'] profile_first_name = profile['first_name'] profile_last_name = profile['last_name'] profile_gender = profile['gender'] if profile_gender == 'male': sex = True else: sex = False except Exception as e: print '%s (%s)' % (e.message, type(e)) return HttpResponseRedirect('/sorry/') try: print "1212122asas" social_account = SocialData.objects.filter(account_id=str(profile_id)).all() print social_account print "1" except Exception as e: print "HATA" + e try: print "sss" print "r4" if social_account: print "hesap var" user = User.objects.get(id=social_account[0].user.id) social_network = SocialData.objects.get(user=user.id) username = str(user.username) password = str(user.password) social_network.account_token = long_access_token print username print password print "sss" else: print "Hesap yok" user_auth = User.objects.create_user(profile_id, 'sss', profile_id) user_auth.first_name = profile_first_name user_auth.last_name = profile_last_name print "sss" user_auth.email = "" user_auth.is_staff = False user_auth.is_active = True user_auth.save() print "user kayit oldu" au = Audience.objects.get(id=1) users = Users.objects.create(user_id=user_auth.id, gender=sex, been_id=1, lives_in_id=1) users.save() print "users kayit oldu" social_network = SocialData(user=user_auth, account_type=0, account_id=profile_id, account_token=long_access_token) username = profile_id social_network.save() dada = authenticate(username=username, password=username) if dada is not None: print "ac" if dada.is_active: print "ba" auth_login(request, dada) print "you are login !!!" + "hello " + request.user.username return HttpResponse("true", content_type='application/json') else: print "b" print "a" print "social_network kayıt oldu" return "false" except Exception as e: print e print "register4" return HttpResponseRedirect('/login/')
def get_facebook_graph(request=None, access_token=None, redirect_uri=None): """ 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) 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 """ # should drop query params be included in the open facebook api, maybe, weird this... DROP_QUERY_PARAMS = ["code", "signed_request", "state"] from open_facebook import OpenFacebook, FacebookAuthorization parsed_data = None if not access_token: # easy case, code is in the get code = request.REQUEST.get("code") if not code: # signed request or cookie leading, base 64 decoding needed signed_data = request.REQUEST.get("signed_request") cookie_name = "fbsr_%s" % facebook_settings.FACEBOOK_APP_ID cookie_data = request.COOKIES.get(cookie_name) if cookie_data: signed_data = cookie_data # the javascript api assumes a redirect uri of '' redirect_uri = "" if signed_data: parsed_data = FacebookAuthorization.parse_signed_data(signed_data) if "oauth_token" in parsed_data: # we already have an active access token in the data access_token = parsed_data["oauth_token"] else: # no access token, need to use this code to get one code = parsed_data["code"] if not access_token: if code: # exchange the code for an access token # based on the php api # https://github.com/facebook/php-sdk/blob/master/src/base_facebook.php # we need to drop signed_request, code and state if redirect_uri is None: query_dict_items = [(k, v) for k, v in request.GET.items() if k not in DROP_QUERY_PARAMS] new_query_dict = QueryDict("", True) new_query_dict.update(dict(query_dict_items)) # TODO support http and https redirect_uri = "http://" + request.META["HTTP_HOST"] + request.path if new_query_dict: redirect_uri += "?%s" % new_query_dict.urlencode() token_response = FacebookAuthorization.convert_code(code, redirect_uri=redirect_uri) access_token = token_response["access_token"] else: from open_facebook import exceptions return None # raise exceptions.MissingParameter('Cant find code or access token') facebook_open_graph = OpenFacebook(access_token, parsed_data) return facebook_open_graph
def get_facebook_graph(request=None, access_token=None, redirect_uri=None): ''' 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 ''' #should drop query params be included in the open facebook api, maybe, weird this... from open_facebook import OpenFacebook, FacebookAuthorization parsed_data = None expires = None if hasattr(request, 'facebook'): graph = request.facebook _add_current_user_id(graph, request.user) return graph if not access_token: #easy case, code is in the get code = request.REQUEST.get('code') if not code: #signed request or cookie leading, base 64 decoding needed signed_data = request.REQUEST.get('signed_request') cookie_name = 'fbsr_%s' % facebook_settings.FACEBOOK_APP_ID cookie_data = request.COOKIES.get(cookie_name) if cookie_data: signed_data = cookie_data #the javascript api assumes a redirect uri of '' redirect_uri = '' if signed_data: parsed_data = FacebookAuthorization.parse_signed_data(signed_data) if 'oauth_token' in parsed_data: # we already have an active access token in the data access_token = parsed_data['oauth_token'] else: # no access token, need to use this code to get one code = parsed_data.get('code', None) if not access_token: if code: #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 if not redirect_uri: redirect_uri = '' #we need to drop signed_request, code and state redirect_uri = cleanup_oauth_url(redirect_uri) try: logger.info('trying to convert the code with redirect uri: %s', redirect_uri) token_response = FacebookAuthorization.convert_code(code, redirect_uri=redirect_uri) expires = token_response.get('expires') access_token = token_response['access_token'] except open_facebook_exceptions.OAuthException, 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)) return None elif request.user.is_authenticated(): #support for offline access tokens stored in the users profile profile = request.user.get_profile() access_token = getattr(profile, 'access_token', None) if not access_token: return None else: return None
def get_facebook_graph(request=None, access_token=None, redirect_uri=None): ''' 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) 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 ''' #should drop query params be included in the open facebook api, maybe, weird this... DROP_QUERY_PARAMS = ['code','signed_request','state'] from open_facebook import OpenFacebook, FacebookAuthorization parsed_data = None if not access_token: #easy case, code is in the get code = request.REQUEST.get('code') if not code: #signed request or cookie leading, base 64 decoding needed signed_data = request.REQUEST.get('signed_request') cookie_name = 'fbsr_%s' % facebook_settings.FACEBOOK_APP_ID cookie_data = request.COOKIES.get(cookie_name) if cookie_data: signed_data = cookie_data #the javascript api assumes a redirect uri of '' redirect_uri = '' if signed_data: parsed_data = FacebookAuthorization.parse_signed_data(signed_data) if 'oauth_token' in parsed_data: # we already have an active access token in the data access_token = parsed_data['oauth_token'] else: # no access token, need to use this code to get one code = parsed_data.get('code', None) if not access_token: if code: #exchange the code for an access token #based on the php api #https://github.com/facebook/php-sdk/blob/master/src/base_facebook.php #we need to drop signed_request, code and state if redirect_uri is None: query_dict_items = [(k,v) for k, v in request.GET.items() if k not in DROP_QUERY_PARAMS] new_query_dict = QueryDict('', True) new_query_dict.update(dict(query_dict_items)) #TODO support http and https # redirect_uri = 'http://' + request.META['HTTP_HOST'] + request.path redirect_uri = facebook_settings.FACEBOOK_CANVAS_PAGE if new_query_dict: redirect_uri += '?%s' % new_query_dict.urlencode() try: token_response = FacebookAuthorization.convert_code(code, redirect_uri=redirect_uri) except open_facebook_exceptions.OAuthException, e: return None access_token = token_response['access_token'] else: return None
def get_facebook_graph(request=None, access_token=None, redirect_uri=None): ''' 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 ''' #should drop query params be included in the open facebook api, maybe, weird this... DROP_QUERY_PARAMS = ['code', 'signed_request', 'state'] from open_facebook import OpenFacebook, FacebookAuthorization parsed_data = None expires = None if not access_token: #easy case, code is in the get code = request.REQUEST.get('code') if not code: #signed request or cookie leading, base 64 decoding needed signed_data = request.REQUEST.get('signed_request') cookie_name = 'fbsr_%s' % facebook_settings.FACEBOOK_APP_ID cookie_data = request.COOKIES.get(cookie_name) if cookie_data: signed_data = cookie_data #the javascript api assumes a redirect uri of '' redirect_uri = '' if signed_data: parsed_data = FacebookAuthorization.parse_signed_data(signed_data) if 'oauth_token' in parsed_data: # we already have an active access token in the data access_token = parsed_data['oauth_token'] else: # no access token, need to use this code to get one code = parsed_data.get('code', None) if not access_token: if code: #exchange the code for an access token #based on the php api #https://github.com/facebook/php-sdk/blob/master/src/base_facebook.php #we need to drop signed_request, code and state if redirect_uri: redirect_base, redirect_query = redirect_uri.split('?', 1) query_dict_items = QueryDict(redirect_query).items() else: redirect_base = facebook_settings.FACEBOOK_CANVAS_PAGE query_dict_items = request.GET.items() filtered_query_items = [(k, v) for k, v in query_dict_items if k.lower() not in DROP_QUERY_PARAMS] new_query_dict = QueryDict('', True) new_query_dict.update(dict(filtered_query_items)) #TODO support http and https redirect_uri = redirect_base if new_query_dict: redirect_uri = '%s?%s' % (redirect_base, new_query_dict.urlencode()) try: logger.info('trying to convert the code with redirect uri: %s', redirect_uri) token_response = FacebookAuthorization.convert_code(code, redirect_uri=redirect_uri) expires = token_response.get('expires') except open_facebook_exceptions.OAuthException, e: #TODO: this sometimes fails, should it raise? raise return None access_token = token_response['access_token'] elif request.user.is_authenticated(): #support for offline access tokens stored in the users profile profile = request.user.get_profile() access_token = getattr(profile, 'access_token', None) if not access_token: return None else: return None
def get_facebook_graph(request=None, access_token=None, redirect_uri=None): ''' 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) 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 ''' #should drop query params be included in the open facebook api, maybe, weird this... DROP_QUERY_PARAMS = ['code','signed_request','state'] from open_facebook import OpenFacebook, FacebookAuthorization parsed_data = None if not access_token: #easy case, code is in the get code = request.REQUEST.get('code') if not code: #signed request or cookie leading, base 64 decoding needed signed_data = request.REQUEST.get('signed_request') cookie_name = 'fbsr_%s' % facebook_settings.FACEBOOK_APP_ID cookie_data = request.COOKIES.get(cookie_name) if cookie_data: signed_data = cookie_data #the javascript api assumes a redirect uri of '' redirect_uri = '' if signed_data: parsed_data = FacebookAuthorization.parse_signed_data(signed_data) if 'oauth_token' in parsed_data: # we already have an active access token in the data access_token = parsed_data['oauth_token'] else: # no access token, need to use this code to get one code = parsed_data.get('code', None) if not access_token: if code: #exchange the code for an access token #based on the php api #https://github.com/facebook/php-sdk/blob/master/src/base_facebook.php #we need to drop signed_request, code and state if redirect_uri is None: query_dict_items = [(k,v) for k, v in request.GET.items() if k not in DROP_QUERY_PARAMS] new_query_dict = QueryDict('', True) new_query_dict.update(dict(query_dict_items)) #TODO support http and https redirect_uri = 'http://' + request.META['HTTP_HOST'] + request.path if new_query_dict: redirect_uri += '?%s' % new_query_dict.urlencode() try: token_response = FacebookAuthorization.convert_code(code, redirect_uri=redirect_uri) except open_facebook_exceptions.OAuthException, e: return None access_token = token_response['access_token'] else: return None
def FacebookAuthenticate(): FACEBOOK_ACCESS_TOKEN= FacebookAuthorization.get_app_access_token() return OpenFacebook(FACEBOOK_ACCESS_TOKEN)