本文整理汇总了Python中open_facebook.api.FacebookAuthorization类的典型用法代码示例。如果您正苦于以下问题:Python FacebookAuthorization类的具体用法?Python FacebookAuthorization怎么用?Python FacebookAuthorization使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FacebookAuthorization类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_register
def test_register(self):
return 'currently this doesnt work reliably with the live facebook api'
#setup the test user
permissions = facebook_settings.FACEBOOK_DEFAULT_SCOPE
app_access_token = FacebookAuthorization.get_cached_app_access_token()
test_user = FacebookAuthorization.get_or_create_test_user(app_access_token, permissions)
#test the connect view in the registration mode (empty db)
c = Client()
url = reverse('facebook_connect')
access_token = test_user.access_token
response = c.get(url, {'facebook_login': '1', 'access_token': access_token})
self.assertEqual(response.status_code, 302)
user = User.objects.all().order_by('-id')[:1][0]
profile = user.get_profile()
self.assertEqual(access_token, profile.access_token)
#test the login flow
response = c.get(url, {'facebook_login': '1', 'access_token': access_token})
self.assertEqual(response.status_code, 302)
new_user = User.objects.all().order_by('-id')[:1][0]
new_profile = user.get_profile()
self.assertEqual(access_token, new_profile.access_token)
self.assertEqual(user, new_user)
示例2: test_extend_token
def test_extend_token(self):
return 'this doesnt work in travis, but locally its fine... weird'
app_access_token = FacebookAuthorization.get_cached_app_access_token()
test_user = FacebookAuthorization.get_or_create_test_user(app_access_token)
access_token = test_user.access_token
results = FacebookAuthorization.extend_access_token(access_token)
if 'access_token' not in results:
raise ValueError('we didnt get a fresh token')
示例3: test_create_test_user
def test_create_test_user(self):
#Also, somehow unittest.skip doesnt work with travis ci?
return 'Skipping since you might have created test users manually, lets not delete them :)'
#start by clearing out our test users (maybe this isnt safe to use in testing)
#if other people create test users manualy this could be annoying
app_access_token = FacebookAuthorization.get_cached_app_access_token()
FacebookAuthorization.delete_test_users(app_access_token)
#the permissions for which we want a test user
permissions = ['email', 'publish_actions']
#gets the test user object
test_user = FacebookAuthorization.get_or_create_test_user(app_access_token, permissions)
graph = test_user.graph()
me = graph.me()
assert me
示例4: _extend_access_token
def _extend_access_token(self, access_token):
from open_facebook.api import FacebookAuthorization
results = FacebookAuthorization.extend_access_token(access_token)
access_token = results['access_token']
self.access_token = access_token
self.save()
return results
示例5: parse_signed_request
def parse_signed_request(signed_request_string):
'''
Just here for your convenience, actual logic is in the
FacebookAuthorization class
'''
from open_facebook.api import FacebookAuthorization
signed_request = FacebookAuthorization.parse_signed_data(
signed_request_string)
return signed_request
示例6: extend_access_tokens
def extend_access_tokens():
for user in UserEx.objects.filter(facebook_id__isnull=False):
results = FacebookAuthorization.extend_access_token(user.access_token)
access_token = results['access_token']
old_token = user.access_token
token_changed = access_token != old_token
if token_changed:
user.access_token = access_token
user.new_token_required = False
user.save()
示例7: handle_existing_user
def handle_existing_user(self, provider, user, access, info):
"""Here we store the access token for the facebook page that we got from facebook."""
if len(Token.objects.all()) < 5:
fb = OpenFacebook(access.access_token.split("=")[1])
me = fb.get('me/accounts')
for page in me['data']:
if 'Roseniuskyrkan' in page.values():
token = FacebookAuthorization.extend_access_token(page['access_token'])['access_token']
Token.objects.create(token = token)
return super(LoginCallback, self).handle_existing_user(provider, user, access, info)
示例8: setupFBUpdates
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))
示例9: test_users
def test_users(request):
'''
Create test users for facebook
'''
if not request.user.is_staff:
raise Http404("access denied")
context = RequestContext(request)
if request.POST:
from open_facebook.api import FacebookAuthorization
token = FacebookAuthorization.get_app_access_token()
fb_response = ''
if request.POST.get('create_user', None):
name = request.POST.get('user_name', None)
app_access = request.POST.get('app_access', None)
if app_access == 'on':
app_access = True
else:
app_access = False
fb_response = FacebookAuthorization.create_test_user(token, name=name, app_access=app_access)
if request.POST.get('get_users', None):
fb_response = FacebookAuthorization.get_test_users(token)
test_users = []
if len(fb_response) > 0:
test_users = fb_response
context['test_users'] = test_users
# test_users = FacebookTestUser.objects.filter(app_access_token=token)
if request.POST.get('delete_user', None):
user_id = request.POST.get('delete_user_id', None)
fb_response = FacebookAuthorization.delete_test_user(token, user_id)
context['fb_response'] = fb_response
return render_to_response('django_facebook/test_users.html', context)
示例10: _extend_access_token
def _extend_access_token(self, access_token):
from open_facebook.api import FacebookAuthorization
results = FacebookAuthorization.extend_access_token(access_token)
access_token, expires = results['access_token'], int(results['expires'])
new_token = access_token != self.access_token
message = 'a new' if new_token else 'the same'
log_format = 'Facebook provided %s token, which expires at %s'
expires_delta = datetime.timedelta(seconds=expires)
logger.info(log_format, message, expires_delta)
if new_token:
logger.info('Saving the new access token')
self.access_token = access_token
self.save()
return results
示例11: _extend_access_token
def _extend_access_token(self, access_token):
from open_facebook.api import FacebookAuthorization
results = FacebookAuthorization.extend_access_token(access_token)
access_token, expires = results["access_token"], int(results["expires"])
old_token = self.access_token
token_changed = access_token != old_token
message = "a new" if token_changed else "the same"
log_format = "Facebook provided %s token, which expires at %s"
expires_delta = datetime.timedelta(seconds=expires)
logger.info(log_format, message, expires_delta)
if token_changed:
logger.info("Saving the new access token")
self.access_token = access_token
self.save()
from django_facebook.signals import facebook_token_extend_finished
facebook_token_extend_finished.send(sender=self, profile=self, token_changed=token_changed, old_token=old_token)
return results
示例12: _extend_access_token
def _extend_access_token(self, access_token):
from open_facebook.api import FacebookAuthorization
results = FacebookAuthorization.extend_access_token(access_token)
access_token = results['access_token']
old_token = self.access_token
token_changed = access_token != old_token
message = 'a new' if token_changed else 'the same'
log_format = 'Facebook provided %s token, which expires at %s'
expires_delta = timedelta(days=60)
logger.info(log_format, message, expires_delta)
if token_changed:
logger.info('Saving the new access token')
self.access_token = access_token
self.save()
from django_facebook.signals import facebook_token_extend_finished
facebook_token_extend_finished.send(sender=self, profile=self,
token_changed=token_changed, old_token=old_token
)
return results
示例13: process_request
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
"""
logger.info("PR01 process_request in django-facebook middleware")
# 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:
logger.info("PR02 referrer %s" % referer)
urlparsed = urlparse(referer)
is_facebook = urlparsed.netloc.endswith("facebook.com")
# facebook redirect
if is_facebook and urlparsed.path.endswith("/l.php"):
logger.info("PR03 is_facebook = True")
return
if not is_facebook:
logger.info("PR04 is_facebook = False")
return
# when there is an error, we attempt to allow user to
# reauthenticate
if "error" in request.GET:
logger.info("PR05 errors in request.GET")
return redirect_login_oauth
else:
logger.info("PR06 no referrer")
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 = long(parsed_signed_request["user_id"])
logger.info("PR07 facebook_id = %s" % facebook_id)
except:
logger.info("PR08 app is not authorized by user")
# redirect to authorization dialog
# if app not authorized by user
return redirect_login_oauth
# check for permissions
try:
graph = self.check_permissions(access_token)
logger.info("PR09 got graph")
except MissingPermissionsError:
logger.info("PR010 no graph")
return redirect_login_oauth
# check if user authenticated and if it's the same
if request.user.is_authenticated():
logger.info("PR11 use is authenticated, user_id = %s" % request.user.id)
if not self.check_django_facebook_user(request, facebook_id, access_token):
logger.info("PR12 check django facebook user failed")
return
request.facebook = graph
if not request.user.is_authenticated():
logger.info("PR13 user is not authenticated")
_action, _user = connect_user(request, access_token, graph)
# override http method, since this actually is a GET
if request.method == "POST":
logger.info("PR14 overwrite POST to GET")
request.method = "GET"
return
示例14: process_request
def process_request(self, request):
"""Process requests for Facebook apps. This is expecially
useful for canvas apps, since it handles signed_request logins,
application requests, etc.
Information about the current interaction status with Facebook
is stored into ``request.fb_info`` as a dict with following
keys:
- ``is_canvas`` - Whether we are running inside canvas or not.
This is determined by the presence of a signed request
via POST.
- ``is_signed_request`` - Whether we received a signed request,
either via POST parameter (canvas) or cookie (js sdk method).
- ``signed_request_type`` - ``"post"`` or ``"cookie"``
- ``app_request_ids`` - If a ``request_ids`` GET was passed,
the IDs of requests to be processed.
- ``is_authenticated`` - Whether we have a valid access_token
for this user, or not.
- Validate signed requests from Facebook
- Login when running in canvas
- For the deauthorize_callback ping
- Process the requests execution when a request_ids parameter
is passed -> redirect to somewhere
- We should also prevent CSRF code to be checked if the request
is using ``signed_request``.
.. NOTE::
This middleware should go before CsrfMiddleware in order
to skip CSRF validation for POSTs inside canvas apps,
in case a valid signed_request was received.
"""
logger.debug("Running FacebookRequest Middleware")
request.fb_info = {
"is_canvas": False,
"is_signed_request": None,
"signed_request_type": None,
"app_request_ids": None,
"is_authenticated": None,
}
## Set ``request.csrf_processing_done = True`` to skip CSRF checking for signed_request
## Check signed request
_sr_from = None
_sr_data = None
if request.POST.has_key('signed_request'):
logger.debug("Got a signed_request via POST")
_sr_from = 'post'
_sr_data = request.POST['signed_request']
elif request.GET.has_key('signed_request'):
logger.debug("Got a signed_request via GET -- strange, but valid..")
_sr_from = 'get'
_sr_data = request.GET['signed_request']
else:
pass
# Disabled as this would generate _sr_data for every image,
# css, etc
"""
cookie_name = 'fbsr_%s' % facebook_settings.FACEBOOK_APP_ID
cookie_data = request.COOKIES.get(cookie_name)
if cookie_data:
logger.debug("Got a signed_request via cookie")
_sr_from = 'cookie'
_sr_data = cookie_data
"""
if _sr_data:
parsed_data = FacebookAuthorization.parse_signed_data(_sr_data)
if parsed_data:
if _sr_from in ('post', 'get'):
request.fb_info['is_canvas'] = True
request.fb_info['is_signed_request'] = True
request.fb_info['signed_request_type'] = _sr_from
request.fb_info['signed_request_data'] = parsed_data
## Skip CSRF validation in case of valid signed request
request.csrf_processing_done = True
## Login the user
user = authenticate(facebook_id=parsed_data['user_id'])
if user and (not request.user.is_authenticated() or request.user != user):
# If the FB user is registered with the app and isn't logged in-
login(request, user)
## --- Application requests --------------------------------------------
if request.REQUEST.has_key('request_ids'):
request.fb_info['app_request_ids'] = request.REQUEST['request_ids'].split(',')
return###===================================== STOP HERE ===============
## TODO: Check whether we are running inside canvas
#.........这里部分代码省略.........
示例15: get_facebook_friends
def get_facebook_friends(request):
app_access_token = FacebookAuthorization.get_cached_app_access_token()
graph = get_persistent_graph(request, access_token=app_access_token)
converter = FacebookUserConverter(graph)
friends_uids = ','.join([str(f['uid']) for f in converter.get_friends()])
return graph.fql('SELECT name, username, pic_square, pic FROM user WHERE uid IN (%s)' % friends_uids)