def _register_user(request, facebook, profile_callback=None): ''' Creates a new user and authenticates The registration form handles the registration and validation Other data on the user profile is updates afterwards ''' if not facebook.is_authenticated(): raise ValueError( 'Facebook needs to be authenticated for connect flows') #get the backend on new registration systems, or none if we are on an older version backend = get_registration_backend() #gets the form class specified in FACEBOOK_REGISTRATION_FORM form_class = get_form_class(backend, request) facebook_data = facebook.facebook_registration_data() data = request.POST.copy() for k, v in facebook_data.items(): if not data.get(k): data[k] = v if request.REQUEST.get('force_registration_hard'): data['email'] = data['email'].replace('@', '+%s@' % randint(0, 100000)) form = form_class(data=data, files=request.FILES, initial={'ip': request.META['REMOTE_ADDR']}) if not form.is_valid(): error = facebook_exceptions.IncompleteProfileError( 'Facebook data %s ' 'gave error %s' % (facebook_data, form.errors)) error.form = form raise error #for new registration systems use the backends methods of saving if backend: new_user = backend.register(request, **form.cleaned_data) else: # For backward compatibility, if django-registration form is used try: new_user = form.save(profile_callback=profile_callback) except TypeError: new_user = form.save() signals.facebook_user_registered.send(sender=get_profile_class(), user=new_user, facebook_data=facebook_data) #update some extra data not yet done by the form new_user = _update_user(new_user, facebook) # IS this the correct way for django 1.3? seems to require the backend # attribute for some reason new_user.backend = 'django_facebook.auth_backends.FacebookBackend' auth.login(request, new_user) return new_user
def register(request): """ A very simplistic register view """ backend = get_registration_backend() form_class = backend.get_form_class(request) template_name = backend.get_registration_template() if request.method == 'POST': form = form_class(data=request.POST, files=request.FILES) if form.is_valid(): new_user = backend.register(request, form=form, **form.cleaned_data) # keep the post behaviour exactly the same as django facebook's # connect flow response = backend.post_connect(request, new_user, CONNECT_ACTIONS.REGISTER) return response else: form = form_class() context = RequestContext(request) context['form'] = form response = render_to_response(template_name, context_instance=context) return response
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 _register_user(request, facebook, profile_callback=None, remove_old_connections=False): ''' Creates a new user and authenticates The registration form handles the registration and validation Other data on the user profile is updates afterwards if remove_old_connections = True we will disconnect old profiles from their facebook flow ''' if not facebook.is_authenticated(): raise ValueError( 'Facebook needs to be authenticated for connect flows') # get the backend on new registration systems, or none # if we are on an older version backend = get_registration_backend() logger.info('running backend %s for registration', backend) # gets the form class specified in FACEBOOK_REGISTRATION_FORM form_class = get_form_class(backend, request) facebook_data = facebook.facebook_registration_data() data = request.POST.copy() for k, v in facebook_data.items(): if not data.get(k): data[k] = v if remove_old_connections: _remove_old_connections(facebook_data['facebook_id']) if request.REQUEST.get('force_registration_hard'): data['email'] = data['email'].replace( '@', '+test%s@' % randint(0, 1000000000)) form = form_class(data=data, files=request.FILES, initial={'ip': request.META['REMOTE_ADDR']}) if not form.is_valid(): # show errors in sentry form_errors = form.errors error = facebook_exceptions.IncompleteProfileError( 'Facebook signup incomplete') error.form = form raise error try: # for new registration systems use the backends methods of saving new_user = None if backend: new_user = backend.register(request, form=form, **form.cleaned_data) # fall back to the form approach if new_user is None: raise ValueError( 'new_user is None, note that backward compatability for the older versions of django registration has been dropped.') except IntegrityError, e: # this happens when users click multiple times, the first request registers # the second one raises an error raise facebook_exceptions.AlreadyRegistered(e)
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 register(request): """ A very simplistic register view """ backend = get_registration_backend() form_class = backend.get_form_class(request) template_name = backend.get_registration_template() if request.method == 'POST': form = form_class(data=request.POST, files=request.FILES) if form.is_valid(): new_user = backend.register(request, form=form, **form.cleaned_data) # keep the post behaviour exactly the same as django facebook's # connect flow response = backend.post_connect( request, new_user, CONNECT_ACTIONS.REGISTER) return response else: form = form_class() context = {'form':form} response = render(request, template_name, context) return response
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 _register_user(request, facebook, profile_callback=None): ''' Creates a new user and authenticates The registration form handles the registration and validation Other data on the user profile is updates afterwards ''' if not facebook.is_authenticated(): raise ValueError('Facebook needs to be authenticated for connect flows') #get the backend on new registration systems, or none if we are on an older version backend = get_registration_backend() #gets the form class specified in FACEBOOK_REGISTRATION_FORM form_class = get_form_class(backend, request) facebook_data = facebook.facebook_registration_data() data = request.POST.copy() for k, v in facebook_data.items(): if not data.get(k): data[k] = v if request.REQUEST.get('force_registration_hard'): data['email'] = data['email'].replace('@', '+%s@' % randint(0, 100000)) form = form_class(data=data, files=request.FILES, initial={'ip': request.META['REMOTE_ADDR']}) if not form.is_valid(): error = facebook_exceptions.IncompleteProfileError('Facebook data %s ' 'gave error %s' % (facebook_data, form.errors)) error.form = form raise error #for new registration systems use the backends methods of saving if backend: new_user = backend.register(request, **form.cleaned_data) else: # For backward compatibility, if django-registration form is used try: new_user = form.save(profile_callback=profile_callback) except TypeError: new_user = form.save() signals.facebook_user_registered.send(sender=get_profile_class(), user=new_user, facebook_data=facebook_data) #update some extra data not yet done by the form new_user = _update_user(new_user, facebook) # IS this the correct way for django 1.3? seems to require the backend # attribute for some reason new_user.backend = 'django_facebook.auth_backends.FacebookBackend' auth.login(request, new_user) return new_user
def _register_user(request, facebook, profile_callback=None, remove_old_connections=False): """ Creates a new user and authenticates The registration form handles the registration and validation Other data on the user profile is updates afterwards if remove_old_connections = True we will disconnect old profiles from their facebook flow """ if not facebook.is_authenticated(): raise ValueError("Facebook needs to be authenticated for connect flows") # get the backend on new registration systems, or none # if we are on an older version backend = get_registration_backend() logger.info("running backend %s for registration", backend) # gets the form class specified in FACEBOOK_REGISTRATION_FORM form_class = get_form_class(backend, request) facebook_data = facebook.facebook_registration_data() data = request.POST.copy() for k, v in facebook_data.items(): if not data.get(k): data[k] = v if remove_old_connections: _remove_old_connections(facebook_data["facebook_id"]) if request.REQUEST.get("force_registration_hard"): data["email"] = data["email"].replace("@", "+test%s@" % randint(0, 1000000000)) form = form_class(data=data, files=request.FILES, initial={"ip": request.META["REMOTE_ADDR"]}) if not form.is_valid(): error_message_format = u"Facebook data %s gave error %s" error_message = error_message_format % (facebook_data, form.errors) error = facebook_exceptions.IncompleteProfileError(error_message) error.form = form raise error try: # for new registration systems use the backends methods of saving new_user = None if backend: new_user = backend.register(request, **form.cleaned_data) # fall back to the form approach if not new_user: # For backward compatibility, if django-registration form is used try: new_user = form.save(profile_callback=profile_callback) except TypeError: new_user = form.save() except IntegrityError, e: # this happens when users click multiple times, the first request registers # the second one raises an error logger.warn("IntegrityError in _register_user") raise facebook_exceptions.AlreadyRegistered(e)
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 ''' 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 _register_user(self, facebook, profile_callback=None): ''' Creates a new user and authenticates The registration form handles the registration and validation Other data on the user profile is updates afterwards ''' if not facebook.is_authenticated(): raise ValueError, 'Facebook needs to be authenticated for connect flows' facebook_user_converter = FacebookUserConverter(facebook) from registration.forms import RegistrationFormUniqueEmail #get the backend on new registration systems, or none if we are on an older version backend = get_registration_backend() #get the form used for registration and fall back to uniqueemail version form_class = RegistrationFormUniqueEmail if backend: form_class = backend.get_form_class(request) facebook_data = facebook_user_converter.facebook_registration_data() data = self.request.POST.copy() for k, v in facebook_data.items(): if not data.get(k): data[k] = v if self.request.REQUEST.get('force_registration_hard'): data['email'] = data['email'].replace('@', '+%s@' % randint(0, 100000)) form = form_class(data=data, files=self.request.FILES, initial={'ip': self.request.META['REMOTE_ADDR']}) if not form.is_valid(): error = facebook_exceptions.IncompleteProfileError( 'Facebook data %s gave error %s' % (facebook_data, form.errors)) error.form = form raise error #for new registration systems use the backends methods of saving if backend: new_user = backend.register(request, **form.cleaned_data) else: new_user = form.save(profile_callback=profile_callback) #update some extra data not yet done by the form new_user = self._update_user(new_user, facebook) #IS this the correct way for django 1.3? seems to require the backend attribute for some reason new_user.backend = 'django_facebook.auth_backends.FacebookBackend' auth.login(self.request, new_user) return new_user
def _register_user(request, facebook, profile_callback=None): ''' Creates a new user and authenticates The registration form handles the registration and validation Other data on the user profile is updates afterwards ''' if not facebook.is_authenticated(): raise ValueError('Facebook needs to be authenticated for connect flows') from registration.forms import RegistrationFormUniqueEmail #get the backend on new registration systems, or none if we are on an older version backend = get_registration_backend() #get the form used for registration and fall back to uniqueemail version form_class = RegistrationFormUniqueEmail if backend: form_class = backend.get_form_class(request) facebook_data = facebook.facebook_registration_data() data = request.POST.copy() for k, v in facebook_data.items(): if not data.get(k): data[k] = v if request.REQUEST.get('force_registration_hard'): data['email'] = data['email'].replace('@', '+%s@' % randint(0, 100000)) form = form_class(data=data, files=request.FILES, initial={'ip': request.META['REMOTE_ADDR']}) #form is not complete until user confirms values confirmed = bool(int(request.REQUEST.get('confirmed', 0))) if not form.is_valid() or not confirmed: error = facebook_exceptions.IncompleteProfileError('Facebook data %s ' 'gave error %s' % (facebook_data, form.errors)) error.form = form raise error #for new registration systems use the backends methods of saving if backend: new_user = backend.register(request, **form.cleaned_data) else: new_user = form.save(profile_callback=profile_callback) #update some extra data not yet done by the form new_user = _update_user(new_user, facebook) # IS this the correct way for django 1.3? seems to require the backend # attribute for some reason new_user.backend = 'django_facebook.auth_backends.FacebookBackend' auth.login(request, new_user) return new_user
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 homepage(request): backend = get_registration_backend() context = RequestContext(request) facebook_login = bool(int(request.REQUEST.get("facebook_login", 0))) if facebook_login: logger.info("trying to connect using facebook") if facebook.is_authenticated(): logger.info("facebook is authenticated") facebook_data = facebook.facebook_profile_data() return render_to_response("base.html", context)
def user_home(request, graph): context = RequestContext(request) backend = get_registration_backend() converter = get_instance_for("user_conversion", graph) if not graph: raise ValueError("No graph") else: x = graph.get("me/friends") f = x["data"] # return HttpResponse("Friends %s" % f) # graph.set('me/feed', message = 'Salesior is coming soon..', url = 'http://www.facebook.com') # send_mail('Successfull login in salesior', 'Congrats..', '*****@*****.**', ['*****@*****.**'], fail_silently = False) return render_to_response("patron/patron_homepage.html", {"friendlist": f}, context)
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 register(request): """ A very simplistic register view """ backend = get_registration_backend() form_class = backend.get_form_class(request) template_name = backend.get_registration_template() if request.method == 'POST': form = form_class(data=request.POST, files=request.FILES) if form.is_valid(): new_user = backend.register(request, **form.cleaned_data) response = backend.post_registration_redirect(request, new_user) #keep the post behaviour exactly the same as django facebook return response else: form = form_class() context = RequestContext(request) context['form'] = form response = render_to_response(template_name, context_instance=context) return response
def _register_user(request, facebook, profile_callback=None, remove_old_connections=False): ''' Creates a new user and authenticates The registration form handles the registration and validation Other data on the user profile is updates afterwards if remove_old_connections = True we will disconnect old profiles from their facebook flow ''' if not facebook.is_authenticated(): raise ValueError( 'Facebook needs to be authenticated for connect flows') # get the backend on new registration systems, or none # if we are on an older version backend = get_registration_backend() logger.info('running backend %s for registration', backend) # gets the form class specified in FACEBOOK_REGISTRATION_FORM form_class = get_form_class(backend, request) facebook_data = facebook.facebook_registration_data() data = request.POST.copy() for k, v in facebook_data.items(): if not data.get(k): data[k] = v if remove_old_connections: _remove_old_connections(facebook_data['facebook_id']) if request.REQUEST.get('force_registration_hard'): data['email'] = data['email'].replace( '@', '+test%s@' % randint(0, 1000000000)) #checking for storing local image if facebook_settings.FACEBOOK_STORE_LOCAL_IMAGE: form = form_class(data=data, files=request.FILES, initial={'ip': request.META['REMOTE_ADDR']}) else: form = form_class(data=data, initial={'ip': request.META['REMOTE_ADDR']}) if not form.is_valid(): error_message_format = u'Facebook data %s gave error %s' error_message = error_message_format % (facebook_data, form.errors) error = facebook_exceptions.IncompleteProfileError(error_message) error.form = form raise error try: #for new registration systems use the backends methods of saving new_user = None if backend: new_user = backend.register(request, **form.cleaned_data) #fall back to the form approach if new_user is None: # For backward compatibility, if django-registration form is used try: new_user = form.save(profile_callback=profile_callback) except TypeError: new_user = form.save() except IntegrityError, e: #this happens when users click multiple times, the first request registers #the second one raises an error raise facebook_exceptions.AlreadyRegistered(e)
def _register_user(request, facebook, profile_callback=None, remove_old_connections=False): ''' Creates a new user and authenticates The registration form handles the registration and validation Other data on the user profile is updates afterwards if remove_old_connections = True we will disconnect old profiles from their facebook flow ''' if not facebook.is_authenticated(): raise ValueError( 'Facebook needs to be authenticated for connect flows') # get the backend on new registration systems, or none # if we are on an older version backend = get_registration_backend() logger.info('running backend %s for registration', backend) # gets the form class specified in FACEBOOK_REGISTRATION_FORM form_class = get_form_class(backend, request) print("0") facebook_data = facebook.facebook_registration_data() print("1") data = request.POST.copy() print("2") for k, v in facebook_data.items(): if not data.get(k): data[k] = v print("3") if remove_old_connections: _remove_old_connections(facebook_data['facebook_id']) print("4") if request.REQUEST.get('force_registration_hard'): data['email'] = data['email'].replace( '@', '+test%s@' % randint(0, 1000000000)) print("debug facebook data ", facebook_data, " data ", data) try: form = form_class(data=data, files=request.FILES, initial={'ip': request.META['REMOTE_ADDR']}) if not form.is_valid(): # show errors in sentry form_errors = form.errors error = facebook_exceptions.IncompleteProfileError( 'Facebook signup incomplete') error.form = form raise error except facebook_exceptions.AlreadyRegistered: print("re raised!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") # TODO raise facebook_exceptions.AlreadyRegistered(_("This email address is already in use. Please supply a different email address.")) print("debug33", data["facebook_id"]) print("debug34", form.cleaned_data) try: # for new registration systems use the backends methods of saving new_user = None if backend: new_user = backend.register(request, form=form, **form.cleaned_data) # fall back to the form approach if new_user is None: raise ValueError( 'new_user is None, note that backward compatability for the older versions of django registration has been dropped.') except IntegrityError as e: # this happens when users click multiple times, the first request registers # the second one raises an error raise facebook_exceptions.AlreadyRegistered(e) # update some extra data not yet done by the form print("debu4", new_user.facebook_id) new_user = _update_user(new_user, facebook) print("debu5", new_user.facebook_id) new_user.facebook_id = data["facebook_id"] new_user.raw_data = data new_user.save() signals.facebook_user_registered.send(sender=get_user_model(), user=new_user, facebook_data=facebook_data, request=request, converter=facebook) # IS this the correct way for django 1.3? seems to require the backend # attribute for some reason new_user.backend = 'django_facebook.auth_backends.FacebookBackend' auth.login(request, new_user) return new_user
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 test_connect(self): ''' Test if we can do logins django_facebook.connect.connect_user ''' user = get_user_model().objects.all()[:1][0] url = self.url example_url = reverse('facebook_example') # test registration flow with patch('django_facebook.views.connect_user', return_value=(CONNECT_ACTIONS.REGISTER, user)) as wrapped_connect: post_data = dict( access_token='short_username', next='%s?register=1' % example_url, ) response = self.client.post(url, post_data, follow=True) self.assertEqual(wrapped_connect.call_count, 1) self.assertIn('register', response.redirect_chain[0][0]) self.assertEqual(response.status_code, 200) # user register next instead of next with patch('django_facebook.views.connect_user', return_value=(CONNECT_ACTIONS.REGISTER, user)) as wrapped_connect: post_data = dict(access_token='short_username', register_next='%s?register=1' % example_url) response = self.client.post(url, post_data, follow=True) self.assertEqual(wrapped_connect.call_count, 1) self.assertIn('register', response.redirect_chain[0][0]) self.assertEqual(response.status_code, 200) # test login with patch('django_facebook.views.connect_user', return_value=(CONNECT_ACTIONS.LOGIN, user)) as wrapped_connect: post_data = dict( access_token='short_username', next='%s?loggggg=1' % example_url, ) response = self.client.post(url, post_data, follow=True) self.assertEqual(wrapped_connect.call_count, 1) self.assertIn('?loggggg=1', response.redirect_chain[0][0]) self.assertEqual(response.status_code, 200) # test connect with patch('django_facebook.views.connect_user', return_value=(CONNECT_ACTIONS.CONNECT, user)) as wrapped_connect: post_data = dict(access_token='short_username', next='%s?loggggg=1' % example_url) response = self.client.post(url, post_data, follow=True) self.assertEqual(wrapped_connect.call_count, 1) assert '?loggggg=1' in response.redirect_chain[0][0] self.assertEqual(response.status_code, 200) # test connect from django_facebook import exceptions as facebook_exceptions profile_error = facebook_exceptions.IncompleteProfileError() profile_error.form = None with patch('django_facebook.views.connect_user', return_value=(CONNECT_ACTIONS.REGISTER, user), side_effect=profile_error) as wrapped_connect: post_data = dict(access_token='short_username', next='%s?loggggg=1' % example_url) response = self.client.post(url, post_data, follow=True) self.assertEqual(wrapped_connect.call_count, 1) self.assertEqual(response.status_code, 200) self.assertTrue(response.context) template = self.get_response_template(response) backend = get_registration_backend() assert template.name in backend.get_registration_template()
def _register_user(request, facebook, profile_callback=None, remove_old_connections=False): ''' Creates a new user and authenticates The registration form handles the registration and validation Other data on the user profile is updates afterwards if remove_old_connections = True we will disconnect old profiles from their facebook flow ''' if not facebook.is_authenticated(): raise ValueError( 'Facebook needs to be authenticated for connect flows') # get the backend on new registration systems, or none # if we are on an older version backend = get_registration_backend() logger.info('running backend %s for registration', backend) # gets the form class specified in FACEBOOK_REGISTRATION_FORM form_class = get_form_class(backend, request) facebook_data = facebook.facebook_registration_data() data = request.POST.copy() logger.info('data for registration form %s', data) for k, v in facebook_data.items(): if not data.get(k): data[k] = v if remove_old_connections: _remove_old_connections(facebook_data['facebook_id']) if request.REQUEST.get('force_registration_hard'): data['email'] = data['email'].replace( '@', '+test%s@' % randint(0, 1000000000)) form = form_class(data=data, files=request.FILES, initial={'ip': request.META['REMOTE_ADDR']}) # BONGOMAGIC-1005 We need to attach facebook user profile to the already registered users # We don't want to create new one and show form error email = data['email'] existing_users = get_user_model().objects.filter(email=email) logger.info("RU01 found users with email %s : %s " % (email, existing_users)) existing_user = None new_user = None for _existing_user in existing_users: if not _existing_user.is_client() and not _existing_user.is_subclient(): existing_user = _existing_user break logger.info("RU02 Possible to attach fb profile to user %s " % existing_user) if existing_user: new_fb_profile = FacebookUserProfile.objects.create(user=existing_user) logger.info("RU03 Created new fb profile %s " % new_fb_profile) new_user = existing_user if not existing_user: logger.info("RU04 No existing user, need to create one") if not form.is_valid(): # show errors in sentry form_errors = form.errors error = facebook_exceptions.IncompleteProfileError( 'Facebook signup incomplete') error.form = form raise error try: # for new registration systems use the backends methods of saving if backend: new_user = backend.register(request, form=form, **form.cleaned_data) # fall back to the form approach if new_user is None: raise ValueError( 'new_user is None, note that backward compatability for the older versions of django registration has been dropped.') except IntegrityError, e: # this happens when users click multiple times, the first request registers # the second one raises an error raise facebook_exceptions.AlreadyRegistered(e) signals.facebook_user_registered.send(sender=get_user_model(), user=new_user, facebook_data=facebook_data, request=request)
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_user(request, access_token=None, facebook_graph=None): """ Given a request either - (if authenticated) connect the user - login - register """ user = None graph = facebook_graph or get_facebook_graph(request, access_token) converter = get_instance_for("user_conversion", graph) assert converter.is_authenticated() facebook_data = converter.facebook_profile_data() force_registration = request.REQUEST.get("force_registration") or request.REQUEST.get("force_registration_hard") connect_facebook = to_bool(request.REQUEST.get("connect_facebook")) backend = get_registration_backend() logger.debug("force registration is set to %s", force_registration) if connect_facebook and request.user.is_authenticated() and not force_registration: # we should only allow connect if users indicate they really want to connect # only when the request.CONNECT_FACEBOOK = 1 # if this isn't present we just do a login action = CONNECT_ACTIONS.CONNECT user = _connect_user(request, converter) if backend.is_user_banned(user): raise PermissionDenied() else: email = facebook_data.get("email", False) email_verified = facebook_data.get("verified", False) kwargs = {} if email and email_verified: kwargs = {"facebook_email": email} auth_user = authenticate(facebook_id=facebook_data["id"], **kwargs) if backend.is_user_banned(auth_user): raise PermissionDenied() if auth_user and not force_registration: action = CONNECT_ACTIONS.LOGIN # Has the user registered without Facebook, using the verified FB # email address? # It is after all quite common to use email addresses for usernames update = getattr(auth_user, "fb_update_required", False) profile = try_get_profile(auth_user) current_facebook_id = get_user_attribute(auth_user, profile, "facebook_id") if not current_facebook_id: update = True # login the user user = _login_user(request, converter, auth_user, update=update) else: action = CONNECT_ACTIONS.REGISTER # when force registration is active we should remove the old # profile try: user = _register_user(request, converter, remove_old_connections=force_registration) except facebook_exceptions.AlreadyRegistered, e: # in Multithreaded environments it's possible someone beats us to # the punch, in that case just login logger.info("parallel register encountered, slower thread is doing a login") auth_user = authenticate(facebook_id=facebook_data["id"], **kwargs) action = CONNECT_ACTIONS.LOGIN user = _login_user(request, converter, auth_user, update=False)
def 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, 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 _register_user(request, facebook, profile_callback=None, remove_old_connections=False): """ Creates a new user and authenticates The registration form handles the registration and validation Other data on the user profile is updates afterwards if remove_old_connections = True we will disconnect old profiles from their facebook flow """ if not facebook.is_authenticated(): raise ValueError("Facebook needs to be authenticated for connect flows") # get the backend on new registration systems, or none # if we are on an older version backend = get_registration_backend() logger.info("running backend %s for registration", backend) # gets the form class specified in FACEBOOK_REGISTRATION_FORM form_class = get_form_class(backend, request) facebook_data = facebook.facebook_registration_data() data = request.POST.copy() for k, v in facebook_data.items(): if not data.get(k): data[k] = v if remove_old_connections: _remove_old_connections(facebook_data["facebook_id"]) if request.REQUEST.get("force_registration_hard"): data["email"] = data["email"].replace("@", "+test%s@" % randint(0, 1000000000)) form = form_class(data=data, files=request.FILES, initial={"ip": request.META["REMOTE_ADDR"]}) if not form.is_valid(): error_message_format = u"Facebook data %s gave error %s" error_message = error_message_format % (facebook_data, form.errors) error = facebook_exceptions.IncompleteProfileError(error_message) error.form = form raise error # for new registration systems use the backends methods of saving new_user = None if backend: new_user = backend.register(request, **form.cleaned_data) # fall back to the form approach if not new_user: # For backward compatibility, if django-registration form is used try: new_user = form.save(profile_callback=profile_callback) except TypeError: new_user = form.save() signals.facebook_user_registered.send(sender=auth.models.User, user=new_user, facebook_data=facebook_data) # update some extra data not yet done by the form new_user = _update_user(new_user, facebook) # IS this the correct way for django 1.3? seems to require the backend # attribute for some reason new_user.backend = "django_facebook.auth_backends.FacebookBackend" auth.login(request, new_user) return new_user
def _register_user(request, facebook, profile_callback=None, remove_old_connections=False,graph = None): ''' Creates a new user and authenticates The registration form handles the registration and validation Other data on the user profile is updates afterwards if remove_old_connections = True we will disconnect old profiles from their facebook flow ''' if not facebook.is_authenticated(): raise ValueError( 'Facebook needs to be authenticated for connect flows') # get the backend on new registration systems, or none # if we are on an older version backend = get_registration_backend() logger.info('running backend %s for registration', backend) # gets the form class specified in FACEBOOK_REGISTRATION_FORM form_class = get_form_class(backend, request) # print form_class facebook_data = facebook.facebook_registration_data() data = request.POST.copy() for k, v in facebook_data.items(): if not data.get(k): data[k] = v if graph: try: from meetme.users.tasks import get_facebook_email data['email'] = get_facebook_email(graph.access_token)['email'] except: data['email']= create_random_username() if remove_old_connections: _remove_old_connections(facebook_data['facebook_id']) if request.REQUEST.get('force_registration_hard'): data['email'] = data['email'].replace( '@', '+test%s@' % randint(0, 1000000000)) form = form_class(data=data, files=request.FILES, initial={'ip': request.META['REMOTE_ADDR']}) # print form if not form.is_valid(): print "Form is invalid" # show errors in sentry form_errors = form.errors error = facebook_exceptions.IncompleteProfileError( 'Facebook signup incomplete') error.form = form raise error try: # for new registration systems use the backends methods of saving new_user = None if backend: new_user = backend.register(request, form=form, **form.cleaned_data) # fall back to the form approach if new_user is None: raise ValueError( 'new_user is None, note that backward compatability for the older versions of django registration has been dropped.') except IntegrityError as e: # this happens when users click multiple times, the first request registers # the second one raises an error raise facebook_exceptions.AlreadyRegistered(e) # update some extra data not yet done by the form new_user = _update_user(new_user, facebook) signals.facebook_user_registered.send(sender=get_user_model(), user=new_user, facebook_data=facebook_data, request=request, converter=facebook) # IS this the correct way for django 1.3? seems to require the backend # attribute for some reason new_user.backend = 'django_facebook.auth_backends.FacebookBackend' auth.login(request, new_user) return new_user
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, 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 test_connect(self): ''' Test if we can do logins django_facebook.connect.connect_user ''' user = get_user_model().objects.all()[:1][0] url = self.url example_url = reverse('facebook_example') # test registration flow with patch('django_facebook.views.connect_user', return_value=(CONNECT_ACTIONS.REGISTER, user)) as wrapped_connect: post_data = dict( access_token='short_username', next='%s?register=1' % example_url, ) response = self.client.post(url, post_data, follow=True) self.assertEqual(wrapped_connect.call_count, 1) self.assertIn('register', response.redirect_chain[0][0]) self.assertEqual(response.status_code, 200) # user register next instead of next with patch('django_facebook.views.connect_user', return_value=(CONNECT_ACTIONS.REGISTER, user)) as wrapped_connect: post_data = dict( access_token='short_username', register_next='%s?register=1' % example_url ) response = self.client.post(url, post_data, follow=True) self.assertEqual(wrapped_connect.call_count, 1) self.assertIn('register', response.redirect_chain[0][0]) self.assertEqual(response.status_code, 200) # test login with patch('django_facebook.views.connect_user', return_value=(CONNECT_ACTIONS.LOGIN, user)) as wrapped_connect: post_data = dict( access_token='short_username', next='%s?loggggg=1' % example_url, ) response = self.client.post(url, post_data, follow=True) self.assertEqual(wrapped_connect.call_count, 1) self.assertIn('?loggggg=1', response.redirect_chain[0][0]) self.assertEqual(response.status_code, 200) # test connect with patch('django_facebook.views.connect_user', return_value=(CONNECT_ACTIONS.CONNECT, user)) as wrapped_connect: post_data = dict( access_token='short_username', next='%s?loggggg=1' % example_url ) response = self.client.post(url, post_data, follow=True) self.assertEqual(wrapped_connect.call_count, 1) assert '?loggggg=1' in response.redirect_chain[0][0] self.assertEqual(response.status_code, 200) # test connect from django_facebook import exceptions as facebook_exceptions profile_error = facebook_exceptions.IncompleteProfileError() profile_error.form = None with patch('django_facebook.views.connect_user', return_value=(CONNECT_ACTIONS.REGISTER, user), side_effect=profile_error) as wrapped_connect: post_data = dict(access_token='short_username', next='%s?loggggg=1' % example_url) response = self.client.post(url, post_data, follow=True) self.assertEqual(wrapped_connect.call_count, 1) self.assertEqual(response.status_code, 200) self.assertTrue(response.context) template = self.get_response_template(response) backend = get_registration_backend() assert template.name in backend.get_registration_template()
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)