def connect(request): ''' Exception and validation functionality around the _connect view Separated this out from _connect to preserve readability Don't bother reading this code, skip to _connect for the bit you're interested in :) ''' facebook_login = to_bool(request.REQUEST.get('facebook_login')) context = RequestContext(request) #validation to ensure the context processor is enabled if not context.get('FACEBOOK_APP_ID'): message = 'Please specify a Facebook app id and ensure the context processor is enabled' raise ValueError(message) #hide the connect page, convenient for testing with new users in production though if not facebook_login and not settings.DEBUG and facebook_settings.FACEBOOK_HIDE_CONNECT_TEST: raise Http404('not showing the connect page') try: response = _connect(request, facebook_login) except open_facebook_exceptions.FacebookUnreachable, e: #often triggered when Facebook is slow warning_format = u'%s, often caused by Facebook slowdown, error %s' warn_message = warning_format % (type(e), e.message) send_warning(warn_message, e=e) response = error_next_redirect(request, additional_params=dict( fb_error_or_cancel=1) )
def parse_signed_data(cls, signed_request, secret=facebook_settings.FACEBOOK_APP_SECRET): ''' Thanks to http://stackoverflow.com/questions/3302946/how-to-base64-url-decode-in-python and http://sunilarora.org/parsing-signedrequest-parameter-in-python-bas ''' from open_facebook.utils import base64_url_decode_php_style l = signed_request.split('.', 2) encoded_sig = l[0] payload = l[1] from open_facebook.utils import json sig = base64_url_decode_php_style(encoded_sig) import hmac import hashlib data = json.loads(base64_url_decode_php_style(payload)) algo = data.get('algorithm').upper() if algo != 'HMAC-SHA256': send_warning('Unknown algorithm we only support HMAC-SHA256 user asked for %s', algo) logger.error('Unknown algorithm') return None else: expected_sig = hmac.new(secret, msg=payload, digestmod=hashlib.sha256).digest() if sig != expected_sig: send_warning('Signature %s didnt match the expected signature %s', sig, expected_sig) return None else: logger.debug('valid signed request received..') return data
def connect(request, graph): ''' Exception and validation functionality around the _connect view Separated this out from _connect to preserve readability Don't bother reading this code, skip to _connect for the bit you're interested in :) ''' backend = get_registration_backend() context = RequestContext(request) # validation to ensure the context processor is enabled if not context.get('FACEBOOK_APP_ID'): message = 'Please specify a Facebook app id and ensure the context processor is enabled' raise ValueError(message) try: response = _connect(request, graph) except open_facebook_exceptions.FacebookUnreachable as e: # often triggered when Facebook is slow warning_format = '%s, often caused by Facebook slowdown, error %s' warn_message = warning_format % (type(e), e.message) send_warning(warn_message, e=e) additional_params = dict(fb_error_or_cancel=1) response = backend.post_error(request, additional_params) return response
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: logger.info('trying to connect using facebook') graph = get_persistent_graph(request) if graph: logger.info('found a graph object') facebook = FacebookUserConverter(graph) if facebook.is_authenticated(): logger.info('facebook is authenticated') facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: warn_message = u'Incomplete profile data encountered '\ u'with error %s' % e send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, 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: if 'attempt' in request.GET: return next_redirect( request, next_key=['error_next', 'next'], additional_params=dict(fb_error_or_cancel=1)) else: logger.info('Facebook authentication needed for connect, ' \ 'raising an error') raise OpenFacebookException('please authenticate') return next_redirect(request)
def parse_signed_data(cls, signed_request, secret=facebook_settings.FACEBOOK_APP_SECRET): ''' Thanks to http://stackoverflow.com/questions/3302946/how-to-base64-url-decode-in-python and http://sunilarora.org/parsing-signedrequest-parameter-in-python-bas ''' from open_facebook.utils import base64_url_decode_php_style l = signed_request.split('.', 2) encoded_sig = l[0] payload = l[1] from open_facebook.utils import json sig = base64_url_decode_php_style(encoded_sig) import hmac import hashlib data = json.loads(base64_url_decode_php_style(payload)) algo = data.get('algorithm').upper() if algo != 'HMAC-SHA256': send_warning('Unknown algorithm we only support HMAC-SHA256 ' \ 'user asked for %s', algo) logger.error('Unknown algorithm') return None else: expected_sig = hmac.new(secret, msg=payload, digestmod=hashlib.sha256).digest() if sig != expected_sig: send_warning('Signature %s didnt match the expected ' \ 'signature %s', sig, expected_sig) return None else: logger.debug('valid signed request received..') return data
def connect(request, graph): ''' Exception and validation functionality around the _connect view Separated this out from _connect to preserve readability Don't bother reading this code, skip to _connect for the bit you're interested in :) ''' backend = get_registration_backend() context = RequestContext(request) # validation to ensure the context processor is enabled if not context.get('FACEBOOK_APP_ID'): message = 'Please specify a Facebook app id and ensure the context processor is enabled' logger.info('CO01 Please specify a Facebook app id and ensure the context processor is enabled') raise ValueError(message) try: response = _connect(request, graph) except open_facebook_exceptions.FacebookUnreachable, e: logger.info('CO02 Probably slow FB') # often triggered when Facebook is slow warning_format = u'%s, often caused by Facebook slowdown, error %s' warn_message = warning_format % (type(e), e.message) send_warning(warn_message, e=e) additional_params = dict(fb_error_or_cancel=1) response = backend.post_error(request, additional_params)
def _connect(request, facebook_login): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' backend = get_registration_backend() context = RequestContext(request) if facebook_login: logger.info('trying to connect using Facebook') graph = require_persistent_graph(request) authenticated = False if graph: logger.info('found a graph object') facebook = FacebookUserConverter(graph) authenticated = facebook.is_authenticated() if authenticated: logger.info('Facebook is authenticated') facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: #show them a registration form to add additional data warning_format = u'Incomplete profile data encountered with error %s' warn_message = warning_format % e.message send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) except facebook_exceptions.AlreadyConnectedError, e: user_ids = [u.id for u in e.users] ids_string = ','.join(map(str, user_ids)) return error_next_redirect( request, additional_params=dict(already_connected=ids_string)) if action is CONNECT_ACTIONS.CONNECT: #connect means an existing account was attached to facebook messages.info(request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: #hook for tying in specific post registration functionality response = backend.post_registration_redirect( request, user) #compatibility for Django registration backends which return redirect tuples instead of a response if not isinstance(response, HttpResponse): to, args, kwargs = response response = redirect(to, *args, **kwargs) return response
def connect(request): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' backend = get_registration_backend() 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: logger.info('trying to connect using facebook') graph = require_persistent_graph(request) if graph: logger.info('found a graph object') facebook = FacebookUserConverter(graph) if facebook.is_authenticated(): logger.info('facebook is authenticated') facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: #show them a registration form to add additional data warning_format = u'Incomplete profile data encountered with error %s' warn_message = warning_format % e.message send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) except facebook_exceptions.AlreadyConnectedError, e: user_ids = [u.id for u in e.users] ids_string = ','.join(map(str, user_ids)) return next_redirect(request, next_key=['error_next', 'next'], additional_params=dict(already_connected=ids_string)) if action is CONNECT_ACTIONS.CONNECT: #connect means an existing account was attached to facebook messages.info(request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: #hook for tying in specific post registration functionality response = backend.post_registration_redirect(request, user) #compatability for django registration backends which return tuples instead of a response #alternatively we could wrap django registration backends, but that would be hard to understand response = response if isinstance(response, HttpResponse) else redirect(response) return response
def connect(request): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' backend = get_registration_backend() 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: require_persistent_graph(request) logger.info('trying to connect using facebook') graph = get_persistent_graph(request) if graph: logger.info('found a graph object') facebook = FacebookUserConverter(graph) if facebook.is_authenticated(): logger.info('facebook is authenticated') facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: warn_message = u'Incomplete profile data encountered '\ u'with error %s' % e.message.decode('utf-8', 'replace') send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, 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: response = backend.post_registration_redirect(request, user) return response else: if 'attempt' in request.GET: return next_redirect(request, next_key=['error_next', 'next'], additional_params=dict(fb_error_or_cancel=1)) else: logger.info('Facebook authentication needed for connect, ' \ 'raising an error') raise OpenFacebookException('please authenticate') 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: # code to redirect if we don't have adequate permissions from django_facebook.utils import test_permissions scope_list = facebook_settings.FACEBOOK_DEFAULT_SCOPE # standardizing the url to prevent things like attempt from being included redirect_uri = request.build_absolute_uri(request.path) + "?facebook_login=1" oauth_url, redirect_uri = get_oauth_url(request, scope_list, redirect_uri=redirect_uri) if not test_permissions(request, scope_list, redirect_uri): return HttpResponseRedirect(oauth_url) graph = get_persistent_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) logger.info("Django facebook, action was %s", action) except facebook_exceptions.IncompleteProfileError, e: warn_message = u"Incomplete profile data encountered " u"with error %s" % e send_warning(warn_message, e=e, facebook_data=facebook.facebook_profile_data()) context["facebook_mode"] = True context["form"] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, 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, graph): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register We are already covered by the facebook_required_lazy decorator So we know we either have a graph and permissions, or the user denied the oAuth dialog ''' backend = get_registration_backend() context = RequestContext(request) connect_facebook = to_bool(request.REQUEST.get('connect_facebook')) logger.info('trying to connect using Facebook') if graph: logger.info('found a graph object') converter = get_instance_for('user_conversion', graph) authenticated = converter.is_authenticated() # Defensive programming :) if not authenticated: raise ValueError('didnt expect this flow') logger.info('Facebook is authenticated') facebook_data = converter.facebook_profile_data() # either, login register or connect the user try: action, user = connect_user( request, connect_facebook=connect_facebook) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: # show them a registration form to add additional data warning_format = u'Incomplete profile data encountered with error %s' warn_message = warning_format % unicode(e) send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form #MJA modification to auto-register #backend.register(request, None, username='******', eamil='*****@*****.**', password1='Blahblah3') #return next_redirect(request) return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) except facebook_exceptions.AlreadyConnectedError, e: user_ids = [u.get_user_id() for u in e.users] ids_string = ','.join(map(str, user_ids)) additional_params = dict(already_connected=ids_string) return backend.post_error(request, additional_params)
def _report_broken_facebook_data(cls, facebook_data, original_facebook_data, e): """ Sends a nice error email with the - facebook data - exception - stacktrace """ from pprint import pformat data_dump = json.dumps(original_facebook_data) data_dump_python = pformat(original_facebook_data) message_format = "The following facebook data failed with error %s" "\n\n json %s \n\n python %s \n" data_tuple = (unicode(e), data_dump, data_dump_python) message = message_format % data_tuple extra_data = {"data_dump": data_dump, "data_dump_python": data_dump_python, "facebook_data": facebook_data} send_warning(message, **extra_data)
def connect(request, graph): ''' Exception and validation functionality around the _connect view Separated this out from _connect to preserve readability Don't bother reading this code, skip to _connect for the bit you're interested in :) ''' backend = get_registration_backend() try: response = _connect(request, graph) except open_facebook_exceptions.FacebookUnreachable as e: # often triggered when Facebook is slow warning_format = u'%s, often caused by Facebook slowdown, error %s' warn_message = warning_format % (type(e), str(e)) send_warning(warn_message, e=e) additional_params = dict(fb_error_or_cancel=1) response = backend.post_error(request, additional_params) return response
def _report_broken_facebook_data(cls, facebook_data, original_facebook_data, e): ''' Sends a nice error email with the - facebook data - exception - stacktrace ''' from pprint import pformat data_dump = json.dumps(original_facebook_data) data_dump_python = pformat(original_facebook_data) message_format = 'The following facebook data failed with error %s\n\n json %s \n\n python %s \n' data_tuple = (unicode(e), data_dump, data_dump_python) message = message_format % data_tuple extra_data = { 'data_dump': data_dump, 'data_dump_python': data_dump_python, 'facebook_data': facebook_data, } send_warning(message, **extra_data)
def _connect(request, facebook_login): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' backend = get_registration_backend() context = RequestContext(request) if True: logger.info('trying to connect using Facebook') graph = require_persistent_graph(request) authenticated = False if graph: logger.info('found a graph object') facebook = FacebookUserConverter(graph) authenticated = facebook.is_authenticated() if authenticated: logger.info('Facebook is authenticated') facebook_data = facebook.facebook_profile_data() #either, login register or connect the user : This is where it interfaces with Django try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) print user print request.user except facebook_exceptions.IncompleteProfileError, e: #show them a registration form to add additional data warning_format = u'Incomplete profile data encountered with error %s' warn_message = warning_format % e.message send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) except facebook_exceptions.AlreadyConnectedError, e: user_ids = [u.user_id for u in e.users] ids_string = ','.join(map(str, user_ids)) return error_next_redirect( request, additional_params=dict(already_connected=ids_string)) if action is CONNECT_ACTIONS.CONNECT: #connect means an existing account was attached to facebook messages.info(request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: #hook for tying in specific post registration functionality #response = backend.post_registration_redirect( # request, user) return HttpResponseRedirect(reverse('home_logged_home')) #compatibility for Django registration backends which return redirect tuples instead of a response if not isinstance(response, HttpResponse): to, args, kwargs = response response = redirect(to, *args, **kwargs) return response
def connect(request): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' backend = get_registration_backend() 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: require_persistent_graph(request) logger.info('trying to connect using facebook') graph = get_persistent_graph(request) if graph: logger.info('found a graph object') klass = get_facebook_user_converter_class() facebook = klass(graph) if facebook.is_authenticated(): logger.info('facebook is authenticated') facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: #show them a registration form to add additional data warning_format = u'Incomplete profile data encountered with error %s' warn_message = warning_format % e.message send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) if action is CONNECT_ACTIONS.CONNECT: #connect means an existing account was attached to facebook messages.info(request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: #hook for tying in specific post registration functionality response = backend.post_registration_redirect(request, user) return response else: if 'attempt' in request.GET: return next_redirect(request, next_key=['error_next', 'next'], additional_params=dict(fb_error_or_cancel=1)) else: logger.info('Facebook authentication needed for connect, ' \ 'raising an error') raise OpenFacebookException('please authenticate') #for CONNECT and LOGIN we simple redirect to the next page return next_redirect(request, default=facebook_settings.FACEBOOK_LOGIN_DEFAULT_REDIRECT)
def _connect(request, graph): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register We are already covered by the facebook_required_lazy decorator So we know we either have a graph and permissions, or the user denied the oAuth dialog ''' backend = get_registration_backend() context = RequestContext(request) connect_facebook = to_bool(request.REQUEST.get('connect_facebook')) logger.info('trying to connect using Facebook') if graph: logger.info('found a graph object') converter = get_instance_for('user_conversion', graph) authenticated = converter.is_authenticated() # Defensive programming :) if not authenticated: raise ValueError('didnt expect this flow') logger.info('Facebook is authenticated') facebook_data = converter.facebook_profile_data() # either, login register or connect the user try: action, user = connect_user(request, connect_facebook=connect_facebook) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError as e: # show them a registration form to add additional data warning_format = 'Incomplete profile data encountered with error %s' warn_message = warning_format % str(e) send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) except facebook_exceptions.AlreadyConnectedError as e: user_ids = [u.get_user_id() for u in e.users] ids_string = ','.join(map(str, user_ids)) additional_params = dict(already_connected=ids_string) return backend.post_error(request, additional_params) response = backend.post_connect(request, user, action) if action is CONNECT_ACTIONS.LOGIN: pass elif action is CONNECT_ACTIONS.CONNECT: # connect means an existing account was attached to facebook messages.info( request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: # hook for tying in specific post registration functionality response.set_cookie('fresh_registration', user.id) else: # the user denied the request additional_params = dict(fb_error_or_cancel='1') response = backend.post_error(request, additional_params) return response
def _connect(request, graph): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register We are already covered by the facebook_required_lazy decorator So we know we either have a graph and permissions, or the user denied the oAuth dialog ''' backend = get_registration_backend() context = RequestContext(request) connect_facebook = to_bool(request.REQUEST.get('connect_facebook')) logger.info('C01: trying to connect using Facebook') if graph: logger.info('C02: found a graph object') converter = get_instance_for('user_conversion', graph) authenticated = converter.is_authenticated() # Defensive programming :) if not authenticated: logger.info('C04: not authenticated') raise ValueError('didnt expect this flow') logger.info('C05: Facebook is authenticated') facebook_data = converter.facebook_profile_data() # either, login register or connect the user try: action, user = connect_user( request, connect_facebook=connect_facebook) logger.info('Django facebook performed action: %s', action) # If client or subclient were detected redirect them to client login page if action == CONNECT_ACTIONS.CLIENT_REDIRECT: return redirect("facebook_client_login") except facebook_exceptions.IncompleteProfileError, e: # show them a registration form to add additional data warning_format = u'Incomplete profile data encountered with error %s' warn_message = warning_format % unicode(e) logger.info(warn_message) send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['blocked_email'] = e.form.data['email'] e.form.data['email'] = u'' context['form'] = e.form # Style register page layout = get_layout(request=request) logger.info('C06: Got layout %s' % layout) context['layout'] = layout return render_to_response( backend.get_registration_template(), context_instance=context, ) except facebook_exceptions.AlreadyConnectedError, e: logger.info('Already connected error') user_ids = [u.get_user_id() for u in e.users] ids_string = ','.join(map(str, user_ids)) additional_params = dict(already_connected=ids_string) return backend.post_error(request, additional_params)
def _connect(request, facebook_login): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' backend = get_registration_backend() context = RequestContext(request) if facebook_login: logger.info('trying to connect using Facebook') try: graph = require_persistent_graph(request) except: return HttpResponseRedirect('https://www.facebook.com') authenticated = False if graph: logger.info('found a graph object') facebook = FacebookUserConverter(graph) authenticated = facebook.is_authenticated() if authenticated: facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: #show them a registration form to add additional data warning_format = u'Incomplete profile data encountered with error %s' warn_message = warning_format % e.message send_warning(warn_message, e=e,facebook_data=facebook_data) context['facebook_mode'] = True m = re.search(r'{(?P<hello>.*)}',str(e).replace('\t','').replace('\n','')) all_d = smart_str(m.group('hello')) #return HttpResponse(all_d) all_data = splitting(all_d) sec = get_random_string(250) all_data['sec'] = sec error = False try: bb = all_data['birthday'].split('/') birthday = bb[2] +'-' + bb[0] + '-' + bb[1] except: error = True ############################################################################### pss = hashlib.sha512(str(all_data['password1'])).hexdigest() #,avatar2=all_data['image'] try: if not error: cix = Account.objects.create(name=all_data['facebook_name'],email=all_data['email'],gender2=all_data['gender'].upper(),facebook_data=str(all_d),secret=sec,password=pss,facebook_page=all_data['link']) else: cix = Account.objects.create(name=all_data['facebook_name'],birthday=birthday,email=all_data['email'],gender2=all_data['gender'].upper(),facebook_data=str(all_d),secret=sec,password=pss,facebook_page=all_data['link']) except IntegrityError: pass try: cix.facebook_data=str(all_d) cix.save() except: pass ##############################################################################3 xt = Account.objects.is_valid3(all_data['email']) if not xt[0]: request.META['authenticated2'] = str(all_data['link']) else: request.META['authenticated2'] = xt[1] #c = { 'form' : all_data } #featured = BaseCourse.objects.filter(featured=True) #c['f1'] = featured[:3] #c['f2'] = featured[3:6] #c['f3'] = featured[6:9] #c['number_of_courses'] = BaseCourse.objects.all().count() return HttpResponseRedirect('/coursewall') except facebook_exceptions.AlreadyConnectedError, e: user_ids = [u.user_id for u in e.users] ids_string = ','.join(map(str, user_ids)) return error_next_redirect( request, additional_params=dict(already_connected=ids_string)) if action is CONNECT_ACTIONS.CONNECT: #connect means an existing account was attached to facebook messages.info(request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: #hook for tying in specific post registration functionality response = backend.post_registration_redirect( request, user) #compatibility for Django registration backends which return redirect tuples instead of a response if not isinstance(response, HttpResponse): to, args, kwargs = response response = redirect(to, *args, **kwargs) return response
def _connect(request, graph): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register We are already covered by the facebook_required_lazy decorator So we know we either have a graph and permissions, or the user denied the oAuth dialog ''' backend = get_registration_backend() context = RequestContext(request) connect_facebook = to_bool(request.REQUEST.get('connect_facebook')) logger.info('trying to connect using Facebook') if graph: logger.info('found a graph object') converter = get_instance_for('user_conversion', graph) authenticated = converter.is_authenticated() # Defensive programming :) if not authenticated: raise ValueError('didnt expect this flow') logger.info('Facebook is authenticated') facebook_data = converter.facebook_profile_data() # either, login register or connect the user try: action, user = connect_user( request, connect_facebook=connect_facebook) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError as e: # show them a registration form to add additional data warning_format = u'Incomplete profile data encountered with error %s' warn_message = warning_format % unicode(e) send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( backend.get_registration_template(), context_instance=context, ) except facebook_exceptions.AlreadyConnectedError as e: user_ids = [u.get_user_id() for u in e.users] ids_string = ','.join(map(str, user_ids)) additional_params = dict(already_connected=ids_string) return backend.post_error(request, additional_params) response = backend.post_connect(request, user, action) if action is CONNECT_ACTIONS.LOGIN: pass elif action is CONNECT_ACTIONS.CONNECT: # connect means an existing account was attached to facebook messages.info(request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: # hook for tying in specific post registration functionality response.set_cookie('fresh_registration', user.id) else: # the user denied the request additional_params = dict(fb_error_or_cancel='1') response = backend.post_error(request, additional_params) return response
def connect(request): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' backend = get_registration_backend() 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: logger.info('trying to connect using facebook') graph = require_persistent_graph(request) if graph: logger.info('found a graph object') facebook = FacebookUserConverter(graph) if facebook.is_authenticated(): logger.info('facebook is authenticated') facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: #show them a registration form to add additional data warning_format = u'Incomplete profile data encountered with error %s' warn_message = warning_format % e.message send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) except facebook_exceptions.AlreadyConnectedError, e: user_ids = [u.id for u in e.users] ids_string = ','.join(map(str, user_ids)) return next_redirect( request, next_key=['error_next', 'next'], additional_params=dict(already_connected=ids_string)) if action is CONNECT_ACTIONS.CONNECT: #connect means an existing account was attached to facebook messages.info( request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: #hook for tying in specific post registration functionality response = backend.post_registration_redirect( request, user) #compatability for django registration backends which return tuples instead of a response #alternatively we could wrap django registration backends, but that would be hard to understand response = response if isinstance( response, HttpResponse) else redirect(response) return response
def connect(request): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' backend = get_registration_backend() 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: require_persistent_graph(request) logger.info('trying to connect using facebook') graph = get_persistent_graph(request) if graph: logger.info('found a graph object') klass = get_facebook_user_converter_class() facebook = klass(graph) if facebook.is_authenticated(): logger.info('facebook is authenticated') facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: #show them a registration form to add additional data warning_format = u'Incomplete profile data encountered with error %s' warn_message = warning_format % e.message send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) if action is CONNECT_ACTIONS.CONNECT: #connect means an existing account was attached to facebook messages.info( request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: #hook for tying in specific post registration functionality response = backend.post_registration_redirect( request, user) return response else: if 'attempt' in request.GET: return next_redirect( request, next_key=['error_next', 'next'], additional_params=dict(fb_error_or_cancel=1)) else: logger.info('Facebook authentication needed for connect, ' \ 'raising an error') raise OpenFacebookException('please authenticate') #for CONNECT and LOGIN we simple redirect to the next page return next_redirect( request, default=facebook_settings.FACEBOOK_LOGIN_DEFAULT_REDIRECT)
def connect(request): """ Handles the view logic around connect user - (if authenticated) connect the user - login - register """ backend = get_registration_backend() 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: logger.info("trying to connect using facebook") graph = require_persistent_graph(request) if graph: logger.info("found a graph object") facebook = FacebookUserConverter(graph) if facebook.is_authenticated(): logger.info("facebook is authenticated") facebook_data = facebook.facebook_profile_data() # either, login register or connect the user try: action, user = connect_user(request) logger.info("Django facebook performed action: %s", action) except facebook_exceptions.IncompleteProfileError, e: # show them a registration form to add additional data warning_format = u"Incomplete profile data encountered with error %s" warn_message = warning_format % e.message send_warning(warn_message, e=e, facebook_data=facebook_data) context["facebook_mode"] = True context["form"] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context ) if action is CONNECT_ACTIONS.CONNECT: # connect means an existing account was attached to facebook messages.info( request, _("You have connected your account " "to %s's facebook profile") % facebook_data["name"], ) elif action is CONNECT_ACTIONS.REGISTER: # hook for tying in specific post registration functionality response = backend.post_registration_redirect(request, user) # compatability for django registration backends which return tuples instead of a response # alternatively we could wrap django registration backends, but that would be hard to understand response = response if isinstance(response, HttpResponse) else redirect(response) return response else: if "attempt" in request.GET: return next_redirect( request, next_key=["error_next", "next"], additional_params=dict(fb_error_or_cancel=1) ) else: logger.info("Facebook authentication needed for connect, " "raising an error") raise OpenFacebookException("please authenticate")
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: #code to redirect if we don't have adequate permissions from django_facebook.utils import test_permissions scope_list = facebook_settings.FACEBOOK_DEFAULT_SCOPE #standardizing the url to prevent things like attempt from being included redirect_uri = request.build_absolute_uri( request.path) + '?facebook_login=1' oauth_url, redirect_uri = get_oauth_url(request, scope_list, redirect_uri=redirect_uri) if not test_permissions(request, scope_list, redirect_uri): return HttpResponseRedirect(oauth_url) graph = get_persistent_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) logger.info('Django facebook, action was %s', action) except facebook_exceptions.IncompleteProfileError, e: warn_message = u'Incomplete profile data encountered '\ u'with error %s' % e send_warning( warn_message, e=e, facebook_data=facebook.facebook_profile_data()) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, 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)