def api_facebook_auth(request, output_format='json'): """Authenticate a user who is already logged into Facebook into the site.""" #logger.debug("entering api_facebook_auth()") data = {} # Response data status = 200 # Ok # Check to see if there's a cookie indicating that the user # is logged in with Facebook. fb_user = facebook.get_user_from_cookie(request.COOKIES, \ settings.FB_API_ID,\ settings.FB_SECRET_KEY) try: if fb_user: try: user_profile = UserProfile.objects.get(\ facebook_user_id=fb_user['uid']) except UserProfile.DoesNotExist: #they're not, so we need to create them and move em along fb_graph = facebook.GraphAPI(fb_user['access_token']) fb_profile = fb_graph.get_object("me") username = fb_profile['first_name'] + fb_profile['last_name'] password = fb_profile['id'] base_user = User.objects.create_user(username=username,\ password=password, email='na') user_profile = UserProfile(user=base_user,\ facebook_user_id=fb_profile['id']) user_profile.save() finally: # Log the user in without authenticating them # See http://zcentric.com/2010/05/12/django-fix-for-user-object-has-no-attribute-backend/ user_profile.user.backend = \ 'django.contrib.auth.backends.ModelBackend' login(request, user_profile.user) #logger.debug("User %s logged in." % (user_profile.user)) # Set up our return data data['username'] = user_profile.user.username data['uri'] = '/api/%s/users/%s/' % (output_format, \ user_profile.user.username) else: raise NoFacebookUser except NoFacebookUser as detail: status = 401 # unauthorized data['error'] = "%s" % error return HttpResponse(content=json.dumps(data), mimetype='application/json', status=status)
def weblogin(request): """ on the login page we can accept django username/password or they can use the facebook login button if the user enters django credentials, we check those in do_login if the user hits the facebook login button, they move through we use Facebooks external authorization flow (which we verify in the auth method) """ template_dict = {} template_dict['fb_app_id'] = settings.FB_API_ID template_dict['auth_page'] = 'authenticate' fb_user = facebook.get_user_from_cookie(request.COOKIES, \ settings.FB_API_ID, \ settings.FB_SECRET_KEY) if fb_user: template_dict['fb_user_detected'] = True if request.method == 'POST': #the user has submitted the form form = LoginForm(request.POST) if form.is_valid(): #things look good, log the user in fUsername = form.cleaned_data['username'] fPass = form.cleaned_data['password'] return do_login(fUsername, fPass, request) else: #user done messed up, let em know template_dict['form'] = form return render_to_response('static_login.html',template_dict,\ context_instance=RequestContext(request)) else: #the user is either coming to the login page from another page #or they had some issues submitting input correctly form = LoginForm() template_dict['form'] = form return render_to_response('static_login.html',template_dict,\ context_instance=RequestContext(request))
def auth(request): """ Facebook auth uses the Javascript SDK to authenticate in the browswer and it stocks a cookie The cookie is read on the server side in the **auth(request)** method * if that cookie exists and a django user doesn't, we create a django user and move them to the site **I set the username to be the first+last name to avoid spaces The password becomes the facebook id, b/c no one should ever have to enter it and the authenication on for our django site is a formality since facebook verified the user NOTE: The login page, when the user clicks the sign in via FB button a JS callbacr function is called and on successful logins it routes the browser to /authenticate to run necessary checks if that cookie exists and a django user does, we move them to the site if no cookie exists, we move them onto the login page NOTE: if a user has a django account there is no method for them to add a facebook account if they decide to log in VIA facebook their prior account won't be merged, thus we have two unique accounts with no bridge. """ if request.user.is_authenticated(): return HttpResponseRedirect('/') # Check to see if there's a cookie indicating that the user # is logged in with Facebook. fb_user = facebook.get_user_from_cookie(request.COOKIES, \ settings.FB_API_ID,\ settings.FB_SECRET_KEY) if fb_user: #user has a FB account and we need to see if they have been #registered in our db try: user_profile = UserProfile.objects.get(\ facebook_user_id=fb_user['uid']) #we need to log the FB user in #http://zcentric.com/2010/05/12/django-fix-for-user-object-has-no-attribute-backend/ #TODO: send message telling the user they have been logged in # via FB user_profile.user.backend = \ 'django.contrib.auth.backends.ModelBackend' login(request, user_profile.user) return HttpResponseRedirect('/') except UserProfile.DoesNotExist: #they're not, so we need to create them and move em along fb_graph = facebook.GraphAPI(fb_user['access_token']) fb_profile = fb_graph.get_object("me") username = fb_profile['first_name'] + fb_profile['last_name'] password = fb_profile['id'] base_user = User.objects.create_user(username=username,\ password=password, email='na') new_user_profile = UserProfile(user=base_user,\ facebook_user_id=fb_profile['id']) new_user_profile.save() return do_login(username, password, request) else: #no residual auth tokens found, move the user to login return HttpResponseRedirect('login')