def wrapper(request, *args, **kwargs): # if this is already the callback, do not wrap. if getattr(request, 'avoid_redirect', False): logger.debug('entered calback. View: %s, kwargs: %s' % (view, kwargs)) return view(request, *args, **kwargs) if 'facebook' in request.META['HTTP_USER_AGENT']: return view(request, *args, **kwargs) session = get_session(request) app_dict = get_app_dict(app_name) signed_request = session.signed_request if not signed_request: #logger.debug('No signed_request in current session. Returning View.') #return view(request, *args, **kwargs) logger.debug( 'No signed_request in current session. Redirecting.\n') url = u'%s?sk=app_%s&app_data=%s' % (app_dict['REDIRECT-URL'], app_dict['ID'], urlencode(request.path)) return render_to_response('facebook/redirecter.html', {'destination': url}, RequestContext(request)) logger.debug('signed_request: %s\n' % signed_request) # This is handled by the Redirect2AppDataMiddleware if 'app_data' in signed_request: app_data = signed_request['app_data'] del request.session['facebook']['signed_request']['app_data'] request.session.modified = True logger.debug('found app_data url: %s' % app_data) return HttpResponseRedirect(app_data) else: #check if the app is inside the specified page. try: page = signed_request['page']['id'] except KeyError: page = 0 if int(page) not in app_dict['PAGES'] and getattr( settings, 'FB_REDIRECT', True): url = u'%s?sk=app_%s&app_data=%s' % ( app_dict['REDIRECT-URL'], app_dict['ID'], urlencode(request.path)) logger.debug( 'Tab is not in original Page (id: %s, should be: %s. Redirecting to: %s' % (page, app_dict['PAGES'][0], url)) return render_to_response('facebook/redirecter.html', {'destination': url}, RequestContext(request)) return view(request, *args, **kwargs)
def fb_app_settings(app_id=None): """ Returns a link to the user's app settings page for the current app. """ if not settings.DEBUG: return '' else: if not app_id: app = get_app_dict() app_id = app['ID'] link = '<a id="fb_app_settings_link" href="http://www.facebook.com/settings/?tab=applications&app_id=%s" target="_blank">X</a>' % app_id return mark_safe(link)
def connect(request, redirect_field_name=REDIRECT_FIELD_NAME, application=None): fb_app = get_app_dict(application) cookie = facebook.get_user_from_cookie(request.COOKIES, fb_app['ID'], fb_app['SECRET']) redirect_to = request.REQUEST.get(redirect_field_name, reverse('account')) if request.user.is_authenticated() and cookie: try: graph = facebook.GraphAPI(cookie["access_token"]) profile = graph.get_object("me") except facebook.GraphAPIError as e: return render_to_response( 'registration/facebook/graph_error.html', {'error': e}, context_instance=RequestContext(request)) # if the user has already a facebook connection, abort and show # error message if hasattr(request.user, 'facebookuser'): connected_profile = graph.get_object("%s" % request.user.facebookuser.id) ctx = {'fb_name' : connected_profile['name'], 'fb_link' : connected_profile['link'], 'username' : request.user.username} return render_to_response( 'registration/facebook/already_connected.html', ctx, context_instance=RequestContext(request)) try: # if that facebook user already exists, abort and show error message fb_user = FacebookUser.objects.get(id=cookie['uid']) ctx = {'fb_name' : profile["name"], 'user' : fb_user.user} return render_to_response( 'registration/facebook/user_exists.html', ctx, context_instance=RequestContext(request)) except FacebookUser.DoesNotExist: fb_user = FacebookUser(id=cookie['uid'], user=request.user, profile_url=profile["link"], access_token=cookie["access_token"]) fb_user.save() return HttpResponseRedirect(redirect_to) elif request.user.is_authenticated(): ctx = {'username' : request.user.username} # if no cookie is present, the user did not authorize the application # in facebook. show the facebook connect button return render_to_response('registration/facebook/connect.html', ctx, context_instance=RequestContext(request)) else: # there is no facebook graph cookie and the user is not logged in # -> redirect to login page return HttpResponseRedirect(reverse('auth_login'))
def wrapper(request, *args, **kwargs): # if this is already the callback, do not wrap. if getattr(request, "avoid_redirect", False): logger.debug("entered calback. View: %s, kwargs: %s" % (view, kwargs)) return view(request, *args, **kwargs) if "facebook" in request.META["HTTP_USER_AGENT"]: return view(request, *args, **kwargs) session = get_session(request) app_dict = get_app_dict(app_name) signed_request = session.signed_request if not signed_request: # logger.debug('No signed_request in current session. Returning View.') # return view(request, *args, **kwargs) logger.debug("No signed_request in current session. Redirecting.\n") url = u"%s?sk=app_%s&app_data=%s" % (app_dict["REDIRECT-URL"], app_dict["ID"], urlencode(request.path)) return render_to_response("facebook/redirecter.html", {"destination": url}, RequestContext(request)) logger.debug("signed_request: %s\n" % signed_request) # This is handled by the Redirect2AppDataMiddleware if "app_data" in signed_request: app_data = signed_request["app_data"] del request.session["facebook"]["signed_request"]["app_data"] request.session.modified = True logger.debug("found app_data url: %s" % app_data) return HttpResponseRedirect(app_data) else: # check if the app is inside the specified page. try: page = signed_request["page"]["id"] except KeyError: page = 0 if int(page) not in app_dict["PAGES"] and getattr(settings, "FB_REDIRECT", True): url = u"%s?sk=app_%s&app_data=%s" % ( app_dict["REDIRECT-URL"], app_dict["ID"], urlencode(request.path), ) logger.debug( "Tab is not in original Page (id: %s, should be: %s. Redirecting to: %s" % (page, app_dict["PAGES"][0], url) ) return render_to_response("facebook/redirecter.html", {"destination": url}, RequestContext(request)) return view(request, *args, **kwargs)
def get_context(self, request, *args, **kwargs): application = None try: page = Page.objects.for_request(request) except Page.DoesNotExist: pass else: if hasattr(page, 'facebook_application'): application = page.facebook_application app_dict = get_app_dict(application) api_key = app_dict['ID'] self.context.update({'api_key' : api_key, 'FACEBOOK_REDIRECT_PAGE_URL': app_dict['REDIRECT-URL']}) return self.context
def logout(request, next_page=None, template_name='registration/logged_out.html', redirect_field_name=REDIRECT_FIELD_NAME, application=None): fb_app = get_app_dict(application) cookie = facebook.get_user_from_cookie(request.COOKIES, fb_app['ID'], fb_app['SECRET']) response = auth_views.logout(request, next_page, template_name, redirect_field_name) if cookie: response.delete_cookie("fbs_" + fb_app['ID']) return response
def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, app_name=None): fb_app = get_app_dict(app_name) try: graph = get_graph(request, app_name=app_name) except IOError: graph = None redirect_to = request.REQUEST.get(redirect_field_name, '') # Because we override the login, we should check for POST data, #to give priority to the django auth view if request.method == 'GET' and graph and graph.via not in ( 'application', ): # Light security check on redirect_to (lifted from django.contrib.auth.views) netloc = urlparse.urlparse(redirect_to)[1] if not redirect_to or netloc != request.get_host(): redirect_to = fb_app['REDIRECT-URL'] """ # TODO: Check only if the domain is in 'DOMAIN' or 'facebook.com' but without the protocol elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to): redirect_to = fb_app['REDIRECT-URL'] """ new_user = authenticate(graph=graph) logger.debug('new user: %s' % new_user) # Authentication might still fail -- new_user might be an # instance of AnonymousUser. if new_user and new_user.is_authenticated(): auth_login(request, new_user) if 'registration' in settings.INSTALLED_APPS: from registration import signals signals.user_registered.send(sender='facebook_login', user=new_user, request=request) return redirect(redirect_to) return auth_views.login(request, template_name, redirect_field_name, authentication_form)
def deauthorize_and_delete(request): """ Deletes a user on a deauthorize callback. """ if request.method == 'GET': raise Http404 if 'signed_request' in request.POST: application = get_app_dict() parsed_request = parseSignedRequest(request.REQUEST['signed_request'], application['SECRET']) user = get_object_or_404(User, id=parsed_request['user_id']) if settings.DEBUG == False: user.delete() logger.info('Deleting User: %s' % user) else: logger.info('User %s asked for deauthorization. Not deleted in Debug mode.') return HttpResponse('ok') raise Http404
def deauthorize_and_delete(request): """ Deletes a user on a deauthorize callback. """ if request.method == "GET": raise Http404 if "signed_request" in request.POST: application = get_app_dict() parsed_request = parseSignedRequest(request.REQUEST["signed_request"], application["SECRET"]) user = get_object_or_404(User, id=parsed_request["user_id"]) if settings.DEBUG == False: user.delete() logger.info("Deleting User: %s" % user) else: logger.info("User %s asked for deauthorization. Not deleted in Debug mode.") return HttpResponse("ok") raise Http404
def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, app_name=None): fb_app = get_app_dict(app_name) try: graph = get_graph(request, app_name=app_name) except IOError: graph = None redirect_to = request.REQUEST.get(redirect_field_name, '') # Because we override the login, we should check for POST data, #to give priority to the django auth view if request.method == 'GET' and graph and graph.via not in ('application',): # Light security check on redirect_to (lifted from django.contrib.auth.views) netloc = urlparse.urlparse(redirect_to)[1] if not redirect_to or netloc != request.get_host(): redirect_to = fb_app['REDIRECT-URL'] """ # TODO: Check only if the domain is in 'DOMAIN' or 'facebook.com' but without the protocol elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to): redirect_to = fb_app['REDIRECT-URL'] """ new_user = authenticate(graph=graph) logger.debug('new user: %s' %new_user) # Authentication might still fail -- new_user might be an # instance of AnonymousUser. if new_user and new_user.is_authenticated(): auth_login(request, new_user) if 'registration' in settings.INSTALLED_APPS: from registration import signals signals.user_registered.send(sender='facebook_login', user=new_user, request=request) return redirect(redirect_to) return auth_views.login(request, template_name, redirect_field_name, authentication_form)
def wrapper(*args, **kwargs): request = args[0] # if this is already the callback, do not wrap. if getattr(request, 'avoid_redirect', False): logger.debug('entered calback. View: %s, kwargs: %s' %(view, kwargs)) return view(*args, **kwargs) session = request.session.get('facebook', dict()) try: signed_request = session['signed_request'] except KeyError: logger.debug('No signed_request in current session. Returning View.') return view(*args, **kwargs) logger.debug('signed_request: %s' %signed_request) if 'app_data' in signed_request: app_data = signed_request['app_data'] del request.session['facebook']['signed_request']['app_data'] request.session.modified = True logger.debug('found app_data url: %s' %app_data) #return HttpResponseRedirect(app_data) try: original_view = resolve(app_data) except Resolver404: logger.debug('Did not find view for %s.' %app_data) url = u'%s?sk=app_%s' % (redirect_url, app_id) return render_to_response('redirecter.html', {'destination': url }, RequestContext(request)) logger.debug('found original view url: %s' %original_view) setattr(request, 'avoid_redirect' , True) # call the view that was originally requested: return original_view.func(request, *original_view.args, **original_view.kwargs) else: #check if the app is inside the specified page. app_dict = get_app_dict() page_id = app_dict['PAGE-ID'] try: page = signed_request['page']['id'] except KeyError: page = None if page <> page_id and not runserver: logger.debug('Tab is not in original Page. Redirecting...') url = u'%s?sk=app_%s&app_data=%s' % (redirect_url, app_id, urlencode(request.path)) return render_to_response('redirecter.html', {'destination': url }, RequestContext(request)) return view(*args, **kwargs)
def connect(request, redirect_field_name=REDIRECT_FIELD_NAME, app_name=None): """ Connects the Facebook Account to the current logged-in user. """ fb_app = get_app_dict(app_name) graph = get_graph(request, app_name=app_name) redirect_to = request.REQUEST.get(redirect_field_name, fb_app['REDIRECT-URL']) if request.user.is_authenticated(): try: me = graph.get_object("me") except facebook.GraphAPIError as e: return redirect('fb_login') # if the user has already a facebook connection, abort and show # error message if hasattr(request.user, 'user'): logger.debug('The logged in user is already connected.') # check if the django user and FB user match: if graph.user_id <> request.user.user.id: logger.debug( 'User %s already connected with Facebook account %s' % (request.user.get_full_name, request.user.user._name)) auth_views.logout(request, next_page=reverse('fb_app')) # Otherwise redirect return redirect(redirect_to) else: # The User has no Facebook account attached. Connect him. try: # if that facebook user already exists, abort and show error message fb_user = FacebookUser.objects.get(id=graph.user_id) except FacebookUser.DoesNotExist: fb_user = FacebookUser(id=graph.user_id) fb_user.get_from_facebook(graph=graph, save=True) else: if isinstance(fb_user.user, User): auth_views.logout(request, next_page=reverse('fb_login')) else: fb_user.user = request.user fb_user.save() finally: return redirect(redirect_to) else: # The user is not logged in # -> redirect to login page return redirect('fb_login')
def deauthorize_and_delete(request): """ Deletes a user on a deauthorize callback. """ if request.method == 'GET': raise Http404 if 'signed_request' in request.POST: application = get_app_dict() parsed_request = parseSignedRequest(request.REQUEST['signed_request'], application['SECRET']) user = get_object_or_404(User, id=parsed_request['user_id']) if settings.DEBUG == False: user.delete() logger.info('Deleting User: %s' % user) else: logger.info( 'User %s asked for deauthorization. Not deleted in Debug mode.' ) return HttpResponse('ok') raise Http404
def connect(request, redirect_field_name=REDIRECT_FIELD_NAME, app_name=None): """ Connects the Facebook Account to the current logged-in user. """ fb_app = get_app_dict(app_name) graph = get_graph(request, app_name=app_name) redirect_to = request.REQUEST.get(redirect_field_name, fb_app['REDIRECT-URL']) if request.user.is_authenticated(): try: me = graph.get_object("me") except facebook.GraphAPIError as e: return redirect('fb_login') # if the user has already a facebook connection, abort and show # error message if hasattr(request.user, 'user'): logger.debug('The logged in user is already connected.') # check if the django user and FB user match: if graph.user_id <> request.user.user.id: logger.debug('User %s already connected with Facebook account %s' % (request.user.get_full_name, request.user.user._name)) auth_views.logout(request, next_page=reverse('fb_app')) # Otherwise redirect return redirect(redirect_to) else: # The User has no Facebook account attached. Connect him. try: # if that facebook user already exists, abort and show error message fb_user = FacebookUser.objects.get(id=graph.user_id) except FacebookUser.DoesNotExist: fb_user = FacebookUser(id=graph.user_id) fb_user.get_from_facebook(graph=graph, save=True) else: if isinstance(fb_user.user, User): auth_views.logout(request, next_page=reverse('fb_login')) else: fb_user.user = request.user fb_user.save() finally: return redirect(redirect_to) else: # The user is not logged in # -> redirect to login page return redirect('fb_login')
def logout(request, next_page=None, template_name='registration/logged_out.html', redirect_field_name=REDIRECT_FIELD_NAME): fb_app=get_app_dict() # TODO: Make this multi-app capable. Add app to login-url. fb_session = get_session(request) fb_session.store_token(None) response = auth_views.logout(request, next_page, template_name, redirect_field_name) # This might lead to unexpected results with multiple apps. response.delete_cookie("fbsr_" + fb_app['ID']) redirect_to = next_page or request.REQUEST.get(redirect_field_name, '') if not redirect_to or ' ' in redirect_to: redirect_to = fb_app['REDIRECT-URL'] return redirect(redirect_to)
def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, application=None): fb_app = get_app_dict(application) cookie = facebook.get_user_from_cookie(request.COOKIES, fb_app['ID'], fb_app['SECRET']) redirect_to = request.REQUEST.get(redirect_field_name, '') # Because we override the login, we should check for POST data, #to give priority to the django auth view if not request.method == "POST" and cookie: # Light security check -- make sure redirect_to isn't garbage. if not redirect_to or ' ' in redirect_to: redirect_to = fb_app['REDIRECT-URL'] # Heavier security check -- redirects to http://example.com should # not be allowed, but things like /view/?param=http://example.com # should be allowed. This regex checks if there is a '//' *before* a # question mark. elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to): redirect_to = fb_app['REDIRECT-URL'] if not request.user.is_authenticated(): new_user = authenticate(uid=cookie["uid"], access_token=cookie["access_token"]) auth_login(request, new_user) if 'registration' in settings.INSTALLED_APPS: from registration import signals signals.user_registered.send(sender='facebook_login', user=new_user, request=request) return HttpResponseRedirect(redirect_to) else: return auth_views.login(request, template_name, redirect_field_name, authentication_form)
def logout(request, next_page=None, template_name='registration/logged_out.html', redirect_field_name=REDIRECT_FIELD_NAME): fb_app = get_app_dict( ) # TODO: Make this multi-app capable. Add app to login-url. fb_session = get_session(request) fb_session.store_token(None) response = auth_views.logout(request, next_page, template_name, redirect_field_name) # This might lead to unexpected results with multiple apps. response.delete_cookie("fbsr_" + fb_app['ID']) redirect_to = next_page or request.REQUEST.get(redirect_field_name, '') if not redirect_to or ' ' in redirect_to: redirect_to = fb_app['REDIRECT-URL'] return redirect(redirect_to)
def fb_redirect_url(app_name=None): app = get_app_dict(app_name) return app['REDIRECT-URL']
def fb_canvas_url(request, app_name=None): app = get_app_dict(app_name) if request.is_secure and False: # FIXME: For some reason always returns true. return app['SECURE-CANVAS-URL'] else: return app['CANVAS-URL']
def fb_domain(app_name=None): app = get_app_dict(app_name) return app['DOMAIN']
def fb_canvas_page(app_name=None): app = get_app_dict(app_name) return app['CANVAS-PAGE']
def fb_app_id(app_name=None): app = get_app_dict(app_name) return app['ID']
def fb_api_key(app_name=None): app = get_app_dict(app_name) return app['API-KEY']
def add_to_page_dialog(app_name=None): app_dict = get_app_dict(application=app_name) link = u'<a href="https://www.facebook.com/dialog/pagetab?app_id=%s&display=popup&next=%s">Add to page</a>'\ % (app_dict['ID'], app_dict['REDIRECT-URL']) return mark_save(link)