Ejemplo n.º 1
0
def test_login(request, fb_id):
    from facebook.models import FacebookProfile

    try:
        fb_user = FacebookProfile.objects.get(facebook_id=fb_id)
        user = fb_user.user
    except FacebookProfile.DoesNotExist:
        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()

    fb_user.user.backend = 'django.contrib.auth.backends.ModelBackend' 
    auth_login(request, fb_user.user)
    url = getattr(settings, "LOGIN_REDIRECT_URL", "/")
    resp = HttpResponseRedirect(url)
    return resp
Ejemplo n.º 2
0
    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 = fb_profile['id']
                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']
                # 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
Ejemplo n.º 3
0
    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('http://'+ settings.LOCALHOST_ALIAS + '/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)
        if not response:
            return None

        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'])

            # Update access_token
            fb_user.access_token = access_token
            fb_user.save()

        except FacebookProfile.DoesNotExist:
            # Create the FacebookProfile
            fb_user = FacebookProfile(user=request.user, facebook_id=fb_profile['id'], access_token=access_token)
            fb_user.save()

        return fb_user
Ejemplo n.º 4
0
    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
Ejemplo n.º 5
0
    def authenticate(self, user_id=None, access_token=None):
        data = None
        if user_id is None:
            data = urllib.urlopen(
                'https://graph.facebook.com/me?access_token=%s' % access_token)
            data = json.load(data)
            user_id = data[u'id']

        try:
            # try to find the user
            fb_user = FacebookProfile.objects.get(facebook_id=user_id)
            user = fb_user.user

            # update access_token
            fb_user.access_token = access_token
            fb_user.save()

        except FacebookProfile.DoesNotExist:
            # user does not exist yet, get some more data and create a new user
            if data is None:
                data = urllib.urlopen(
                    'https://graph.facebook.com/me?access_token=%s' %
                    access_token)
                data = json.load(data)
                user_id = data[u'id']

            # use Facebook username if possible, but not all Facebook users
            # have usernames. In that case we still ensure the usernames are
            # unique
            username = ""
            email = ""
            if 'username' in data:
                username = data['username']
                if 'email' in data:
                    email = data['email']
                else:
                    email = data['username'] + "@facebook.com"
            elif 'email' in data:
                username = data['email'].split('@')[0] + url_safe_encode(
                    long(user_id))
                email = data['email']
            else:
                username = "******" + url_safe_encode(long(user_id))
                email = username + '@facebook.com'

            user = User.objects.create_user(username, email)
            user.first_name = data['first_name']
            user.last_name = data['last_name']
            user.save()

            # Create the FacebookProfile
            fb_user = FacebookProfile(user=user,
                                      facebook_id=user_id,
                                      access_token=access_token)
            fb_user.save()

        return user
Ejemplo n.º 6
0
    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, create one

            username = fb_profile.get('username', fb_profile['email'].split(
                '@')[0])  # Not all users have usernames
            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
Ejemplo n.º 7
0
    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:
            # See if email has already been registered
            try:
                user = User.objects.get(email=fb_profile['email'])
            except User.DoesNotExist:
                # 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 FacebookProfile
            fb_user = FacebookProfile(user=user,
                                      facebook_id=fb_profile['id'],
                                      access_token=access_token)
            fb_user.save()
        return user
Ejemplo n.º 8
0
    def authenticate(self, request=None, token=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_login_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
            facebook_profile = FacebookProfile.objects.get(
                facebook_id=fb_profile['id'])

            # Update access_token
            facebook_profile.access_token = access_token
            facebook_profile.save()

        except FacebookProfile.DoesNotExist:
            # No existing user, create one
            facebook_profile = FacebookProfile(facebook_id=fb_profile['id'],
                                               access_token=access_token)
            facebook_profile.save()
        backend = facebook_profile.getLoginBackend(request)

        try:
            fb_username = fb_profile['username']
            fb_mail = fb_profile['email']
            user = backend.login(facebook_profile,
                                 related_name='facebook_profile',
                                 username=fb_profile['username'],
                                 email=fb_profile['email'])
        except:
            import sys
            print "error ", sys.exc_info()[0]
        return user
Ejemplo n.º 9
0
    def authenticate(self, user_id=None, access_token=None):
        data = None
        if user_id is None:
            data = urllib.urlopen('https://graph.facebook.com/me?access_token=%s' % access_token)
            data = json.load(data)
            user_id = data[u'id']
            
        try:
            # try to find the user
            fb_user = FacebookProfile.objects.get(facebook_id=user_id)
            user = fb_user.user

            # update access_token
            fb_user.access_token = access_token
            fb_user.save()

        except FacebookProfile.DoesNotExist:
            # user does not exist yet, get some more data and create a new user
            if data is None:
                data = urllib.urlopen('https://graph.facebook.com/me?access_token=%s' % access_token)
                data = json.load(data)
                user_id = data[u'id']
            
            # use Facebook username if possible, but not all Facebook users
            # have usernames. In that case we still ensure the usernames are
            # unique
            username = ""
            email = ""
            if 'username' in data:
                username = data['username']
                if 'email' in data:
                    email = data['email']
                else:
                    email = data['username'] + "@facebook.com"
            elif 'email' in data:
                username = data['email'].split('@')[0] + url_safe_encode(long(user_id))
                email = data['email']
            else:
                username = "******" + url_safe_encode(long(user_id))
                email = username + '@facebook.com'
            
            user = User.objects.create_user(username, email)
            user.first_name = data['first_name']
            user.last_name = data['last_name']
            user.save()

            # Create the FacebookProfile
            fb_user = FacebookProfile(user=user, facebook_id=user_id, access_token=access_token)
            fb_user.save()

        return user
Ejemplo n.º 10
0
    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-authenticaton-callback')),
            'code': token,
        }

        # Get a legit access token
        target = urllib.urlopen('https://graph.facebook.com/oauth/access_token?%s' % urllib.urlencode(args)).read()
        response = urlparse.parse_qs(target)
        if 'error' in response.keys() or not token:
            return None
        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 = 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

        except FacebookProfile.DoesNotExist:
            if request and request.user.is_authenticated():
                user = request.user
                try:
                    profile = user.facebookprofile
                    # todo: check if this profile contains fb id
                    return user
                except FacebookProfile.DoesNotExist:
                    pass

            else:
                user = User.objects.create_user(fb_profile['email'], 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('/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, create one

            username = fb_profile.get('username', fb_profile['email'].split('@')[0])# Not all users have usernames
            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
Ejemplo n.º 12
0
def getAccessToken(request):
	code = request.GET.get('code')
	consumer = oauth.Consumer(key=APP_ID, secret=APP_SECRET)
	client = oauth.Client(consumer)
	redirect_uri = 'http://localhost:8000/facebook/getAccessToken'
	request_url = ACCESS_TOKEN_URL + '?client_id=%s&redirect_uri=%s&client_secret=%s&code=%s' % (APP_ID, redirect_uri, APP_SECRET, code)
	resp, content = client.request(request_url, 'GET')
	access_token = dict(urlparse.parse_qsl(content))['access_token']
	request_url = CHECK_AUTH + '?access_token=%s' % access_token
	if resp['status'] == '200':
		resp, content = client.request(request_url, 'GET')
		content_dict = json.loads(content)
		userid = content_dict['id']
		try:
			myprofile = FacebookProfile.objects.get(user=request.user)
			myprofile.update_token(access_token)
		except:
			myprofile = FacebookProfile(user=request.user, facebook_id=userid, image_url=(GRAPH_URL + content_dict['username'] + '/picture'), access_token=access_token)
			myprofile.get_remote_image()
			myprofile.save()
		# user = authenticate(username=profile.user.username, password=hashlib.new(profile.fb_uid).hexdigest())
		# login(request,user)
	return redirect('dashboard.views.dashboard')
Ejemplo n.º 13
0
    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
Ejemplo n.º 14
0
    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/'+invite_token+"/"+is_sign_up),
            '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)

        
        if not 'access_token' in response:
            raise UserDidNotGivePermissionException
        access_token = response['access_token'][-1]

        # Read the user's profile information
        fb_profile = urllib.urlopen('https://graph.facebook.com/me?access_token=%s&fields=id,username,email,first_name,last_name,gender,birthday' % 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
            print "=====================1"
            fb_user.access_token = access_token
            fb_user.save()

        except FacebookProfile.DoesNotExist:
            print "=====================2"
            # Not all users have usernames
            username = fb_profile['id']
            try:
                print "=====================3"
                user = User.objects.get(email = fb_profile['email'])
                fb_user = FacebookProfile(user=user, facebook_id=fb_profile['id'], access_token=access_token)
                fb_user.save()
                return user
            except User.DoesNotExist:
                print "=====================4"
                try:
                    user = User.objects.create_user(username,fb_profile['email'])
                    print "=====================5"
                except IntegrityError:
                    # Username already exists, make it unique

                    user = User.objects.create_user(fb_profile['id']+"asdf", fb_profile['email'])


                
                user.is_active = True # change to false if using email activation
                user.first_name = fb_profile["first_name"]
                user.last_name = fb_profile["last_name"]
                user.set_password("from facebook so doesnt matter")
                user.save()

                fb_user = FacebookProfile(user=user, facebook_id=fb_profile['id'], access_token=access_token)
                fb_user.save()


        return user
Ejemplo n.º 15
0
    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
Ejemplo n.º 16
0
    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