def authenticate(self, token=None, request=None): """ Reads in a Facebook code and asks Facebook if it's valid and what user it points to. """ args = { 'client_id': settings.FACEBOOK_APP_ID, 'client_secret': settings.FACEBOOK_APP_SECRET, 'redirect_uri': request.build_absolute_uri( reverse('facebook_callback')), 'code': token, } # Get a legit access token target = urllib.urlopen( 'https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read() response = cgi.parse_qs(target) access_token = response['access_token'][-1] # Read the user's profile information fb_profile = urllib.urlopen( 'https://graph.facebook.com/me?access_token=%s' % access_token) fb_profile = json.load(fb_profile) try: # Try and find existing user fb_user = UserProfile.objects.get(facebook_id=fb_profile['id']) user = fb_user.user # Update access_token fb_user.access_token = access_token fb_user.save() except UserProfile.DoesNotExist: # No existing user if getattr(settings, 'FACEBOOK_FORCE_SIGNUP', False): # No existing user, use anonymous user = AnonymousUser() user.username = username user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] fb_user = UserProfile( facebook_id=fb_profile['id'], access_token=access_token ) user.facebookprofile = fb_user else: # No existing user, create one user = User.objects.create_user(fb_profile['id'], fb_profile['email']) user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] # with django-primate User has one field called 'name' instead # of first_name and last_name user.name = u'%s %s' % (user.first_name, user.last_name) user.save() # Create the UserProfile fb_user = UserProfile(user=user, facebook_id=fb_profile['id'], access_token=access_token) fb_user.save() return user
def authenticate(self, token=None, request=None): """ Reads in a Facebook code and asks Facebook if it's valid and what user it points to. """ args = { "client_id": settings.FACEBOOK_APP_ID, "client_secret": settings.FACEBOOK_APP_SECRET, "redirect_uri": request.build_absolute_uri("/facebook/authentication_callback"), "code": token, } # Get a legit access token target = urllib.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args)).read() response = cgi.parse_qs(target) access_token = response["access_token"][-1] # Read the user's profile information fb_profile = urllib.urlopen("https://graph.facebook.com/me?access_token=%s" % access_token) fb_profile = json.load(fb_profile) try: # Try and find existing user fb_user = FacebookProfile.objects.get(facebook_id=fb_profile["id"]) user = fb_user.user # Update access_token fb_user.access_token = access_token fb_user.save() except FacebookProfile.DoesNotExist: # No existing user # Not all users have usernames username = fb_profile.get("username", fb_profile["id"]) if getattr(settings, "FACEBOOK_FORCE_SIGNUP", False): # No existing user, use anonymous user = AnonymousUser() user.username = username user.first_name = fb_profile["first_name"] user.last_name = fb_profile["last_name"] fb_user = FacebookProfile(facebook_id=fb_profile["id"], access_token=access_token) user.facebookprofile = fb_user else: # No existing user, create one try: user = User.objects.create_user(username, fb_profile["email"]) except IntegrityError: # Username already exists, make it unique user = User.objects.create_user(username + fb_profile["id"], fb_profile["email"]) user.first_name = fb_profile["first_name"] user.last_name = fb_profile["last_name"] user.save() # Create the FacebookProfile fb_user = FacebookProfile(user=user, facebook_id=fb_profile["id"], access_token=access_token) fb_user.save() return user
def process_request(self, request): django_user = get_user(request) google_user = users.get_current_user() # Check to see if the user is authenticated with a different backend, if so, just set # request.user and bail if django_user.is_authenticated(): backend_str = request.session.get(BACKEND_SESSION_KEY) if (not backend_str) or not isinstance( load_backend(backend_str), BaseAppEngineUserAPIBackend): request.user = django_user return if django_user.is_anonymous() and google_user: # If there is a google user, but we are anonymous, log in! # Note that if DJANGAE_FORCE_USER_PRE_CREATION is True then this may not authenticate django_user = authenticate( google_user=google_user) or AnonymousUser() if django_user.is_authenticated(): login(request, django_user) if django_user.is_authenticated(): if not google_user: # If we are logged in with django, but not longer logged in with Google # then log out logout(request) django_user = AnonymousUser() elif django_user.username != google_user.user_id(): # If the Google user changed, we need to log in with the new one logout(request) django_user = authenticate( google_user=google_user) or AnonymousUser() if django_user.is_authenticated(): login(request, django_user) # Note that the logic above may have logged us out, hence new `if` statement if django_user.is_authenticated(): # Now make sure we update is_superuser and is_staff appropriately is_superuser = users.is_current_user_admin() resave = False if is_superuser != django_user.is_superuser: django_user.is_superuser = django_user.is_staff = is_superuser resave = True # for users which already exist, we want to verify that their email is still correct # users are already authenticated with their user_id, so we can save their real email # not the lowercased version if django_user.email != google_user.email(): django_user.email = google_user.email() resave = True if resave: django_user.save() request.user = django_user
class AnonymousUserTests(SimpleTestCase): no_repr_msg = "Django doesn't provide a DB representation for AnonymousUser." def setUp(self): self.user = AnonymousUser() def test_properties(self): self.assertIsNone(self.user.pk) self.assertEqual(self.user.username, '') self.assertEqual(self.user.get_username(), '') self.assertIs(self.user.is_anonymous, True) self.assertIs(self.user.is_authenticated, False) self.assertIs(self.user.is_staff, False) self.assertIs(self.user.is_active, False) self.assertIs(self.user.is_superuser, False) self.assertEqual(self.user.groups.all().count(), 0) self.assertEqual(self.user.user_permissions.all().count(), 0) self.assertEqual(self.user.get_user_permissions(), set()) self.assertEqual(self.user.get_group_permissions(), set()) def test_str(self): self.assertEqual(str(self.user), 'AnonymousUser') def test_eq(self): self.assertEqual(self.user, AnonymousUser()) self.assertNotEqual(self.user, User('super', '*****@*****.**', 'super')) def test_hash(self): self.assertEqual(hash(self.user), 1) def test_int(self): msg = ( 'Cannot cast AnonymousUser to int. Are you trying to use it in ' 'place of User?' ) with self.assertRaisesMessage(TypeError, msg): int(self.user) def test_delete(self): with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): self.user.delete() def test_save(self): with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): self.user.save() def test_set_password(self): with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): self.user.set_password('password') def test_check_password(self): with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): self.user.check_password('password')
def process_request(self, request): django_user = get_user(request) google_user = users.get_current_user() # Check to see if the user is authenticated with a different backend, if so, just set # request.user and bail if django_user.is_authenticated(): backend_str = request.session.get(BACKEND_SESSION_KEY) if (not backend_str) or not isinstance(load_backend(backend_str), BaseAppEngineUserAPIBackend): request.user = django_user return if django_user.is_anonymous() and google_user: # If there is a google user, but we are anonymous, log in! # Note that if DJANGAE_CREATE_UNKNOWN_USER=False then this may not authenticate django_user = authenticate(google_user=google_user) or AnonymousUser() if django_user.is_authenticated(): login(request, django_user) if django_user.is_authenticated(): if not google_user: # If we are logged in with django, but not longer logged in with Google # then log out logout(request) django_user = AnonymousUser() elif django_user.username != google_user.user_id(): # If the Google user changed, we need to log in with the new one logout(request) django_user = authenticate(google_user=google_user) or AnonymousUser() if django_user.is_authenticated(): login(request, django_user) # Note that the logic above may have logged us out, hence new `if` statement if django_user.is_authenticated(): # Now make sure we update is_superuser and is_staff appropriately is_superuser = users.is_current_user_admin() resave = False if is_superuser != django_user.is_superuser: django_user.is_superuser = django_user.is_staff = is_superuser resave = True # for users which already exist, we want to verify that their email is still correct # users are already authenticated with their user_id, so we can save their real email # not the lowercased version if django_user.email != google_user.email(): django_user.email = google_user.email() resave = True if resave: django_user.save() request.user = django_user
class AnonymousUserTests(SimpleTestCase): no_repr_msg = "Django doesn't provide a DB representation for AnonymousUser." def setUp(self): self.user = AnonymousUser() def test_properties(self): self.assertIsNone(self.user.pk) self.assertEqual(self.user.username, '') self.assertEqual(self.user.get_username(), '') self.assertIs(self.user.is_anonymous, True) self.assertIs(self.user.is_authenticated, False) self.assertIs(self.user.is_staff, False) self.assertIs(self.user.is_active, False) self.assertIs(self.user.is_superuser, False) self.assertEqual(self.user.groups.all().count(), 0) self.assertEqual(self.user.user_permissions.all().count(), 0) self.assertEqual(self.user.get_group_permissions(), set()) def test_str(self): self.assertEqual(str(self.user), 'AnonymousUser') def test_eq(self): self.assertEqual(self.user, AnonymousUser()) self.assertNotEqual(self.user, User('super', '*****@*****.**', 'super')) def test_hash(self): self.assertEqual(hash(self.user), 1) def test_int(self): msg = ( 'Cannot cast AnonymousUser to int. Are you trying to use it in ' 'place of User?' ) with self.assertRaisesMessage(TypeError, msg): int(self.user) def test_delete(self): with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): self.user.delete() def test_save(self): with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): self.user.save() def test_set_password(self): with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): self.user.set_password('password') def test_check_password(self): with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): self.user.check_password('password')
def create_request(is_post, url, data=None, is_anonymous=None, **kwargs): user = AnonymousUser() if not is_anonymous: user = mixer.blend('users.User') user.username = "******" user.set_password('123') for key, value in kwargs: setattr(user, key, value) user.save() factory = RequestFactory() request = factory.post(url, data) if is_post else factory.get(url) setattr(request, 'session', 'session') messages = FallbackStorage(request) setattr(request, '_messages', messages) request.user = user request = add_middleware_to_request(request, SessionMiddleware) request.session.save() return request
def authenticate(self, token=None, request=None): """ Reads in a Facebook code and asks Facebook if it's valid and what user it points to. """ args = { 'client_id': settings.FACEBOOK_APP_ID, 'client_secret': settings.FACEBOOK_APP_SECRET, 'redirect_uri': request.build_absolute_uri('/facebook/authentication_callback'), 'code': token, } # Get a legit access token target = urllib.urlopen('https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read() response = cgi.parse_qs(target) access_token = response['access_token'][-1] # Read the user's profile information fb_profile = urllib.urlopen('https://graph.facebook.com/me?access_token=%s' % access_token) fb_profile = json.load(fb_profile) fb_friends = urllib.urlopen('https://graph.facebook.com/me/friends?access_token=%s' % access_token) fb_friends = json.load(fb_friends) try: # Try and find existing user fb_user = FacebookProfile.objects.get(facebook_id=fb_profile['id']) user = fb_user.user # Update access_token fb_user.access_token = access_token fb_user.save() FacebookFriends.objects.filter(user=user).delete() for friend in fb_friends['data']: FacebookFriends.objects.create(user=user,facebook_id=friend['id'],name=friend['name']) except FacebookProfile.DoesNotExist: # No existing user # Not all users have usernames username = fb_profile.get('username', fb_profile['email'].split('@')[0]) if getattr(settings, 'FACEBOOK_FORCE_SIGNUP', False): # No existing user, use anonymous user = AnonymousUser() user.username = username user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] fb_user = FacebookProfile( facebook_id=fb_profile['id'], access_token=access_token ) user.facebookprofile = fb_user else: # No existing user, create one try: user = User.objects.create_user(username, fb_profile['email']) except IntegrityError: # Username already exists, make it unique user = User.objects.create_user(username + fb_profile['id'], fb_profile['email']) user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] user.save() # Create the FacebookProfile fb_user = FacebookProfile(user=user, facebook_id=fb_profile['id'], access_token=access_token) fb_user.save() return user
def authenticate(self, token=None, request=None): """ Reads in a Facebook code and asks Facebook if it's valid and what user it points to. """ #rebuild redirect_uri for user id or next url redirect_uri = request.build_absolute_uri('/facebook/authentication_callback') redirect_args = {} if request.GET.get('next'): redirect_args['next'] = request.GET.get('next') if request.GET.get('user'): redirect_args['user'] = str(request.user.id) if len(redirect_args) != 0: redirect_uri = redirect_uri + '?' + urllib.urlencode(redirect_args) args = { 'client_id': settings.FACEBOOK_APP_ID, 'client_secret': settings.FACEBOOK_APP_SECRET, 'redirect_uri': redirect_uri, 'code': token, } # Get a legit access token target = urllib.urlopen('https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read() response = cgi.parse_qs(target) access_token = response['access_token'][-1] # Read the user's profile information fb_profile = urllib.urlopen('https://graph.facebook.com/me?access_token=%s' % access_token) fb_profile = json.load(fb_profile) #if user is just trying to connect facebook not full login if request.GET.get('user'): user = request.user try: # Try and find existing user fb_user = FacebookProfile.objects.get(facebook_id=fb_profile['id']) user = fb_user.user if request.user.id != user.id: return None except FacebookProfile.DoesNotExist: fb_user = FacebookProfile( user=user, facebook_id=fb_profile['id'], access_token=access_token ) fb_user.save() return user #full login try: # Try and find existing user fb_user = FacebookProfile.objects.get(facebook_id=fb_profile['id']) user = fb_user.user # Update access_token fb_user.access_token = access_token fb_user.save() except FacebookProfile.DoesNotExist: # Not all users have usernames username = fb_profile.get('username', fb_profile['email'].split('@')[0]) if getattr(settings, 'FACEBOOK_FORCE_SIGNUP', False): user = AnonymousUser() user.signup_required = True user.username = username user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] fb_user = FacebookProfile( facebook_id=fb_profile['id'], access_token=access_token ) user.facebookprofile = fb_user else: if getattr(settings, 'FACEBOOK_FORCE_VERIFICATION', False) and \ User.objects.filter(email__iexact=fb_profile['email']).exists(): user = AnonymousUser() user.verification_required = True user.email = fb_profile['email'] user.facebookprofile = FacebookProfile( facebook_id=fb_profile['id'], access_token=access_token ) else: try: user = User.objects.create_user(username, fb_profile['email']) except IntegrityError: # Username already exists, make it unique user = User.objects.create_user(username + fb_profile['id'], fb_profile['email']) user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] user.save() # Create the FacebookProfile fb_user = FacebookProfile(user=user, facebook_id=fb_profile['id'], access_token=access_token) fb_user.save() return user
def authenticate(self, token=None, request=None): """ Reads in a Facebook code and asks Facebook if it's valid and what user it points to. """ args = { 'client_id': settings.FACEBOOK_APP_ID, 'client_secret': settings.FACEBOOK_APP_SECRET, 'redirect_uri': request.build_absolute_uri(reverse('facebook-callback')), 'code': token, } # Get a legit access token target = urllib.urlopen( 'https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read() response = cgi.parse_qs(target) access_token = response['access_token'][-1] # Read the user's profile information fb_profile = urllib.urlopen( 'https://graph.facebook.com/me?access_token=%s' % access_token) fb_profile = json.load(fb_profile) try: # Try and find existing user fb_user = FacebookProfile.objects.get(facebook_id=fb_profile['id']) user = fb_user.user # Update access_token fb_user.access_token = access_token fb_user.save() except FacebookProfile.DoesNotExist: # No existing user if getattr(settings, 'FACEBOOK_FORCE_SIGNUP', False): # No existing user, use anonymous user = AnonymousUser() user.username = username user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] fb_user = FacebookProfile(facebook_id=fb_profile['id'], access_token=access_token) user.facebookprofile = fb_user else: # No existing user, create one user = User.objects.create_user(fb_profile['id'], fb_profile['email']) user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] # Facebook allows for longer name. This fixes the inconsistencies between # Django and Postgres if len(user.first_name) > 30: user.first_name = user.first_name[:30] if len(user.last_name) > 30: user.last_name = user.last_name[:30] # with django-primate User has one field called 'name' instead # of first_name and last_name user.name = u'%s %s' % (user.first_name, user.last_name) user.save() # Create the FacebookProfile fb_user = FacebookProfile(user=user, facebook_id=fb_profile['id'], access_token=access_token) fb_user.save() return user
def userregister(request): """ A registration form endpoint for registering and logging in. This view will permit a user to register if their username is unique, their password is not empty, and an email address is provided. This view returns JSON, with a 'success' property if registration or login was successful. If registration was successful, the JSON also contains a 'redirect' property. If registration was unsuccessful, the JSON also contains a 'message' property, describing why the registration failed. Parameters: request -- An HttpRequest, with the form submitted parameters. Returns: A JSON object indicating if registration/login was successful. """ username = request.POST.get('newusername', None) password = request.POST.get('newpassword1', None) email = request.POST.get('email', None) fname = request.POST.get('firstname', None) lname = request.POST.get('lastname', None) hint = request.POST.get('passwordhint', None) org = request.POST.get('organization', None) anonymous = False status = {'success': False} if username != '' and password != '': if (username == 'anonymous' and password == 'anonymous'): user = AnonymousUser() else: name_exists = User.objects.filter(username__exact=username) if name_exists: status['message'] = 'name exists' return HttpResponse(json.dumps(status)) try: User.objects.create_user(username, email, password) except Exception as error: status[ 'message'] = 'Sorry, we weren\'t able to create your account.' return HttpResponse(json.dumps(status)) # authenticate the user, and add additional registration info user = authenticate(username=username, password=password) user.first_name = fname user.last_name = lname user.save() profile = user.profile profile.organization = org profile.pass_hint = hint profile.save() login(request, user) status['success'] = True status['redirect'] = '/districtmapping/plan/0/view/' return HttpResponse(json.dumps(status)) else: status['message'] = 'Username cannot be empty.' return HttpResponse(json.dumps(status))
def userregister(request): """ A registration form endpoint for registering and logging in. This view will permit a user to register if their username is unique, their password is not empty, and an email address is provided. This view returns JSON, with a 'success' property if registration or login was successful. If registration was successful, the JSON also contains a 'redirect' property. If registration was unsuccessful, the JSON also contains a 'message' property, describing why the registration failed. Parameters: request -- An HttpRequest, with the form submitted parameters. Returns: A JSON object indicating if registration/login was successful. """ username = request.POST.get('newusername', None) password = request.POST.get('newpassword1', None) email = request.POST.get('email', None) fname = request.POST.get('firstname', None) lname = request.POST.get('lastname', None) hint = request.POST.get('passwordhint', None) org = request.POST.get('organization', None) anonymous = False status = { 'success':False } if username != '' and password != '': if (username == 'anonymous' and password == 'anonymous'): user = AnonymousUser() else: name_exists = User.objects.filter(username__exact=username) if name_exists: status['message'] ='name exists' return HttpResponse(json.dumps(status), mimetype='application/json') email_exists = email != '' and User.objects.filter(email__exact = email) if email_exists: status['message'] ='email exists' return HttpResponse(json.dumps(status), mimetype='application/json') try: User.objects.create_user(username, email, password) except Exception as error: status['message'] = 'Sorry, we weren\'t able to create your account.' return HttpResponse(json.dumps(status), mimetype='application/json') # authenticate the user, and add additional registration info user = authenticate(username=username, password=password) user.first_name = fname user.last_name = lname user.save() profile = user.get_profile() profile.organization = org profile.pass_hint = hint profile.save() login( request, user ) status['success'] = True status['redirect'] = '/districtmapping/plan/0/view/' return HttpResponse(json.dumps(status), mimetype='application/json') else: status['message'] = 'Username cannot be empty.' return HttpResponse(json.dumps(status), mimetype='application/json')
def test_anonymous_profile_attrs(self): profile = AnonymousUser().get_profile() self.assertTrue(profile.has_seen_sheet_page) self.assertIsNone(profile.save())
def authenticate(self, token=None, request=None): """ Reads in a Facebook code and asks Facebook if it's valid and what user it points to. """ args = { 'client_id': settings.FACEBOOK_APP_ID, 'client_secret': settings.FACEBOOK_APP_SECRET, 'redirect_uri': request.build_absolute_uri('/facebook/authentication_callback'), 'code': token, } # Get a legit access token target = urllib.urlopen('https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read() response = cgi.parse_qs(target) access_token = response['access_token'][-1] # Read the user's profile information fb_profile = urllib.urlopen('https://graph.facebook.com/me?access_token=%s' % access_token) fb_profile = json.load(fb_profile) try: # Try and find existing user fb_user = FacebookProfile.objects.get(facebook_id=fb_profile['id']) user = fb_user.user # Update access_token fb_user.access_token = access_token fb_user.save() except FacebookProfile.DoesNotExist: # No existing user # Not all users have usernames username = (fb_profile['first_name']+fb_profile['last_name']).lower() if getattr(settings, 'FACEBOOK_FORCE_SIGNUP', False): # No existing user, use anonymous user = AnonymousUser() user.username = username user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] fb_user = FacebookProfile( facebook_id=fb_profile['id'], access_token=access_token ) user.facebookprofile = fb_user else: # No existing user, create one try: user = User.objects.create_user(username, fb_profile['email']) except IntegrityError: # Username already exists, make it unique user = User.objects.create_user(username + fb_profile['id'], fb_profile['email']) user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] user.save() image_url = 'https://graph.facebook.com/'+fb_profile['id']+'/picture?access_token='+access_token+'&type=large' savepath = 'media/members/'+fb_profile['id']+'.jpg' urllib.urlretrieve(image_url, savepath) #enregistrer l'image dans media/members profile = get_object_or_404(Profile, user=user) profile.email = fb_profile['email'] #profile.city = fb_profile['location']['name'] profile.avatar = 'members/'+fb_profile['id']+'.jpg' profile.save() # Create the FacebookProfile fb_user = FacebookProfile(user=user, facebook_id=fb_profile['id'], access_token=access_token) fb_user.save() return user
def authenticate(self, token=None, request=None): """ Reads in a Facebook code and asks Facebook if it's valid and what user it points to. """ args = { 'client_id': settings.FACEBOOK_APP_ID, 'client_secret': settings.FACEBOOK_APP_SECRET, 'redirect_uri': request.build_absolute_uri('/facebook/authentication_callback'), 'code': token, } # Get a legit access token target = urllib.urlopen( 'https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read() response = cgi.parse_qs(target) access_token = response['access_token'][-1] # Read the user's profile information fb_profile = urllib.urlopen( 'https://graph.facebook.com/me?access_token=%s' % access_token) fb_profile = json.load(fb_profile) try: # Try and find existing user fb_user = FacebookProfile.objects.get(facebook_id=fb_profile['id']) user = fb_user.user # Update access_token fb_user.access_token = access_token fb_user.save() except FacebookProfile.DoesNotExist: # No existing user # Not all users have usernames username = fb_profile.get('username', fb_profile['email'].split('@')[0]) if getattr(settings, 'FACEBOOK_FORCE_SIGNUP', False): # No existing user, use anonymous user = AnonymousUser() user.username = username user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] fb_user = FacebookProfile(facebook_id=fb_profile['id'], access_token=access_token) user.facebookprofile = fb_user else: # No existing user, create one try: user = User.objects.create_user(username, fb_profile['email']) except IntegrityError: # Username already exists, make it unique user = User.objects.create_user( username + fb_profile['id'], fb_profile['email']) user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] user.save() # Create the FacebookProfile fb_user = FacebookProfile(user=user, facebook_id=fb_profile['id'], access_token=access_token) fb_user.save() return user
def authenticate(self, token=None, request=None,redirect_uri='/'): """ Reads in a Facebook code and asks Facebook if it's valid and what user it points to. """ args = { 'client_id': settings.FACEBOOK_APP_ID, 'client_secret': settings.FACEBOOK_APP_SECRET, 'redirect_uri': request.build_absolute_uri( redirect_uri ), 'code': token, } # Get Model to use appmodel = settings.AUTH_PROFILE_MODULE.split(".") FacebookProfile = get_model(appmodel[0],appmodel[1]) # Get a legit access token target = urllib.urlopen('https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(args)).read() response = cgi.parse_qs(target) try: access_token = response['access_token'][-1] except KeyError: mail_admins("ERR",response) return None # Read the user's profile information fb_profile = urllib.urlopen('https://graph.facebook.com/me?fields=id,first_name,last_name,email,name&access_token=%s' % access_token) fb_profile = json.load(fb_profile) try: # Try and find existing user fb_user = FacebookProfile.objects.get(facebook_id=fb_profile['id']) user = fb_user.user # Update access_token fb_user.access_token = access_token fb_user.save() except FacebookProfile.DoesNotExist: # No existing user # Not all users have usernames username = fb_profile.get('username', fb_profile['email'].split('@')[0]) if getattr(settings, 'FACEBOOK_FORCE_SIGNUP', False): # No existing user, use anonymous user = AnonymousUser() user.username = username user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] fb_user = FacebookProfile( facebook_id=fb_profile['id'], access_token=access_token ) user.facebookprofile = fb_user else: # No existing user, create one try: user = User.objects.create_user(username, fb_profile['email']) except IntegrityError: # Username already exists, make it unique user = User.objects.create_user(username + fb_profile['id'], fb_profile['email']) user.first_name = fb_profile['first_name'] user.last_name = fb_profile['last_name'] user.save() # Create the FacebookProfile fb_user = FacebookProfile(user=user, facebook_id=fb_profile['id'], access_token=access_token) fb_user.save() return user