Beispiel #1
0
class PyfbTests(unittest.TestCase):

    pyfb_args = {}

    def setUp(self):
        self.pyfb = Pyfb(config["FACEBOOK_APP_ID"], **self.pyfb_args)
        self.pyfb.set_access_token(config["FACEBOOK_TOKEN"])
        self.me = self.pyfb.get_myself()

    def test_auth(self):
        self.assertEquals(type(self.me.name), type(unicode()))

    def test_get_friends(self):
        self.assertTrue(isinstance(self.pyfb.get_friends(self.me.id), list))

    def test_get_photos_paging(self):    	
        photos = self.pyfb.get_photos()
        more_photos = photos.next()
        more_more_photos = more_photos.next()

        if len(photos) < 25 and len(more_photos) > 0:
        	raise Exception()
        
        if len(photos) == 25 and len(more_photos) < 25 and len(more_more_photos) > 0:
        	raise Exception()

        self.assertTrue(isinstance(photos, list))
        self.assertTrue(isinstance(more_photos, list))
        self.assertTrue(isinstance(more_more_photos, list))

        self.assertEquals(len(photos), len(more_photos.previous()))
        self.assertEquals(photos.previous(), [])
Beispiel #2
0
def facebook_login_success(request):
    code = request.GET.get('code')
    facebook = Pyfb(settings.FACEBOOK_APP_ID)
    facebook.get_access_token(settings.FACEBOOK_SECRET_KEY,
                              code,
                              redirect_uri=settings.FACEBOOK_REDIRECT_URL)
    me = facebook.get_myself()

    try:
        email = InviteEmails.objects.get(emailaddress=me.email)
    except ObjectDoesNotExist:
        emailInstanceCreate(me.email)
        email = InviteEmails.objects.get(emailaddress=me.email)

        return render_to_response(
            'invites/result.html',
            RequestContext(request, {
                'email': email,
                'result': 'success'
            }))
    return render_to_response(
        'invites/result.html',
        RequestContext(request, {
            'email': email,
            'result': 'existing'
        }))
Beispiel #3
0
class PyfbTests(unittest.TestCase):

    pyfb_args = {}

    def setUp(self):
        self.pyfb = Pyfb(keys["FACEBOOK_APP_ID"], **self.pyfb_args)
        self.pyfb.set_access_token(keys["FACEBOOK_TOKEN"])
        self.me = self.pyfb.get_myself()

    def test_auth(self):
        self.assertEquals(type(self.me.name), type(unicode()))

    def test_get_friends(self):
        self.assertTrue(isinstance(self.pyfb.get_friends(self.me.id), list))

    def test_get_photos_paging(self):
        photos = self.pyfb.get_photos()
        more_photos = photos.next()
        more_more_photos = more_photos.next()

        if len(photos) < 25 and len(more_photos) > 0:
            raise Exception()

        if len(photos
               ) == 25 and len(more_photos) < 25 and len(more_more_photos) > 0:
            raise Exception()

        self.assertTrue(isinstance(photos, list))
        self.assertTrue(isinstance(more_photos, list))
        self.assertTrue(isinstance(more_more_photos, list))

        self.assertEquals(len(photos), len(more_photos.previous()))
        self.assertEquals(photos.previous(), [])
Beispiel #4
0
def facebook_login_success(request):
    code = request.GET.get('code')    
    facebook = Pyfb(FACEBOOK_APP_ID)
    facebook.get_access_token(FACEBOOK_APP_SECRET, code, redirect_uri=FACEBOOK_REDIRECT_URL)
    me = facebook.get_myself()

    welcome = "Welcome %s. Your Facebook login has been completed successfully! Is this your email address? %s"
    return HttpResponse(welcome % (me.name, me.email))
Beispiel #5
0
    def get(self, user_token):
        #return {User_data: User[token]}
        
        FACEBOOK_APP_ID = '134416106741047'

        facebook = Pyfb(FACEBOOK_APP_ID)

        #Opens a new browser tab instance and authenticates with the facebook API
        #It redirects to an url like http://www.facebook.com/connect/login_success.html#access_token=[access_token]&expires_in=0
        facebook.authenticate()

        #Copy the [access_token] and enter it below
        getToken = user_token#'CAACEdEose0cBACIgotCQGDecYsWW1O7wrc5saw0ZCxrM8nKzF3wWgIvQqGyb9H5u3MIBKak9jcYc3l1CNZCdYniVI3tweTC8vX2PdibMlJrdrH1LIeJnmgWQS8WpkXyRzY8dpvGgFDZARq2amdAZBEXEXJePKSuMqTIOXCCfQMzNd3QMtldxD25lkFg3IANRVfjviSo6uQZDZD'

        #Sets the authentication token
        facebook.set_access_token(getToken)

        #Gets info about myself
        me = facebook.get_myself()
        me_pic = facebook.fql_query('SELECT pic_small FROM user WHERE uid = me()')
        #friends = facebook.get_friends()

        me_name = me.name
        me_id = me.id
        me_gender = me.gender
        location = getattr(me, "location")
        me_location = location.name

        for i in me_pic:
            try:
                my_pic = i.pic_small
            except AttributeError:
                my_pic = 'None'
            try:
                me_birthday = me.birthday
            except AttributeError:
                me_birthday = 'None'

            try:
                me_status = me.relationship_status   
            except AttributeError:
                me_status = 'None'

            try:
                me_link = me.link
            except AttributeError:
                me_link = 'None'
    
    
        me_all = {'name': me_name, 'id': me_id, 'gender': me_gender, 'location': me_location, 'birthday': me_birthday, 'status': me_status, 'link': me_link, 'picture': my_pic  }    
        #db.dannysaban.insert(me_all)
        #print 'me - done!'
        #get_me = db.dannysaban.find({'id': me_id})
        return me_all   
    

        ''' update user data '''    
Beispiel #6
0
def facebook_login_success(request):
    
    code = request.GET.get('code')    

    facebook = Pyfb(FACEBOOK_APP_ID)
    facebook.get_access_token(FACEBOOK_SECRET_KEY, code, redirect_uri=FACEBOOK_REDIRECT_URL)
    me = facebook.get_myself()
    
    welcome = "Welcome <b>%s</b>. Your Facebook login has been completed successfully!"
    return HttpResponse(welcome % me.name)
Beispiel #7
0
class pyfbTests(unittest.TestCase):
    def setUp(self):
        self.facebook = Pyfb(FACEBOOK_APP_ID)
        self.facebook.set_access_token(FACEBOOK_TOKEN)
        self.me = self.facebook.get_myself()

    def test_auth(self):
        self.assertEquals(type(self.me.name), type(unicode()))

    def test_get_friends(self):
        self.assertEquals(type(self.facebook.get_friends(self.me.id)),
                          type(list()))
Beispiel #8
0
class pyfbTests(unittest.TestCase):

    def setUp(self):
        self.facebook = Pyfb(FACEBOOK_APP_ID)
        self.facebook.set_access_token(FACEBOOK_TOKEN)
        self.me = self.facebook.get_myself()

    def test_auth(self):
        self.assertEquals(type(self.me.name), type(unicode()))

    def test_get_friends(self):
        self.assertEquals(type(self.facebook.get_friends(self.me.id)), type(list()))
Beispiel #9
0
def facebook_login_success(request):

    code = request.GET.get('code')

    facebook = Pyfb(FACEBOOK_APP_ID)
    facebook.get_access_token(FACEBOOK_SECRET_KEY,
                              code,
                              redirect_uri=FACEBOOK_REDIRECT_URL)
    me = facebook.get_myself()

    welcome = "Welcome <b>%s</b>. Your Facebook login has been completed successfully!"
    return HttpResponse(welcome % me.name)
Beispiel #10
0
def FacebookLoginSuccess (request):
	code = request.GET.get('code')

	facebook = Pyfb(FACEBOOK_APP_ID)
	facebook.get_access_token(FACEBOOK_SECRET_KEY, code, redirect_uri=FACEBOOK_REDIRECT_URL)
	me = facebook.get_myself()

	if (type(me.name) == type(unicode())):
		return HttpResponse('It worked')

	welcome = "Welcome <b>%s</b>. Your Facebook login has been completed successfully!"
	return HttpResponse(welcome % me.username)
Beispiel #11
0
    def save(self, access_token, request):

        pyfb = Pyfb(FACEBOOK_CONFIG["id"], access_token=access_token)
        me = pyfb.get_myself()

        user, created = User.objects.get_or_create(username=me.name, email=me.email)

        if created:
            user.save()
            player = self.new(remote_id=me.id, user=user)
            player.save()

        self.login(user, request)
        return user
Beispiel #12
0
def facebook_login_success(request):
    code = request.GET.get('code')    
    facebook = Pyfb(settings.FACEBOOK_APP_ID)
    facebook.get_access_token(settings.FACEBOOK_SECRET_KEY, code, redirect_uri=settings.FACEBOOK_REDIRECT_URL)
    me = facebook.get_myself()

    try:
        email = InviteEmails.objects.get(emailaddress = me.email)
    except ObjectDoesNotExist:
        emailInstanceCreate(me.email)
        email = InviteEmails.objects.get(emailaddress = me.email)

        return render_to_response('invites/result.html', RequestContext(request, {'email':email, 'result':'success'}))
    return render_to_response('invites/result.html', RequestContext(request, {'email':email, 'result':'existing'}))
Beispiel #13
0
def facebook_javascript_login_sucess(request):

    access_token = request.GET.get("access_token")
    # print "printing access token"
    facebook = Pyfb(FACEBOOK_APP_ID)
    facebook.set_access_token(access_token)

    user_id = "https://graph.facebook.com/me?access_token="+str(access_token)
    UID = requests.get(user_id)
    # print UID
    if UID.ok:
        jData = json.loads(UID.content)
        UID = jData['id']

    print str(UID) #print FACEBOOK USER ID
    url = "http://graph.facebook.com/v2.7/"+str(UID)+"/picture?redirect=false"
    print url
    myResponse = requests.get(url)
    print myResponse
    if myResponse.ok:
        jData = json.loads(myResponse.content)
        data = jData['data']
        pic_url = data['url'] #Profile Picture
        print pic_url
    else:
        myResponse.raise_for_status()
        print "error"
    photos = facebook.get_photos()
    print "These are my photos:\n"

    facebook_user = True
    users = User.objects.all()
    me = facebook.get_myself()
    fullname = me.name.split()
    first_name = str(fullname[0])
    last_name = str(fullname[1])
    fullname = first_name + last_name
    if User.objects.filter(username=fullname).exists():
        u = authenticate(username=fullname, password=fullname)
        user_profile = UserProfile.objects.get(user=)
        login(request, u)
        return HttpResponseRedirect('/')
    else:
        return _render_user(facebook, facebook_user, request)
Beispiel #14
0
def facebooksignupsuccess(request):
    code = request.GET.get('code')    
    facebook = Pyfb(settings.FACEBOOK_APP_ID)
    fb_token = facebook.get_access_token(settings.FACEBOOK_SECRET_KEY, code, redirect_uri=settings.FACEBOOK_SIGNUP_REDIRECT_URL)
    me = facebook.get_myself()

    try:
        user = User.objects.get(email = me.email)
        try:
            fbk = FacebookProfiles.objects.get(user = user)
        except ObjectDoesNotExist:
            fbk = FacebookProfiles.objects.create(
                user = user,
                fbk_id = me.id,
                fbk_token = fb_token
            )

        return HttpResponseRedirect('/auth/login/')
    except ObjectDoesNotExist:
        user = User.objects.create_user(
            username = me.username,
            email = me.email
            )

        fbk = FacebookProfiles.objects.create(
            user = user,
            fbk_id = me.id,
            fbk_token = fb_token
        )

        name_split = shlex.split(me.name)
        fname = name_split[0]
        lname = ''
    
        for x in name_split[1:]:
            lname += (x + ' ')

        user.first_name = fname
        user.last_name = lname
            
        user.save()

        return HttpResponseRedirect('/auth/setpwd/%s' % str(me.id))
Beispiel #15
0
def facebook_login_success(request):
    code = request.GET.get('code')
    facebook = Pyfb(settings.FACEBOOK_APP_ID)
    access_token = facebook.get_access_token(settings.FACEBOOK_SECRET_KEY, code, redirect_uri=settings.FACEBOOK_REDIRECT_URL)
    me = facebook.get_myself()
     
    #welcome = "Welcome <b>%s</b>. Your Facebook login has been completed successfully!"
    #return HttpResponse(welcome % me.name)
    print access_token
    
    try:
        u=user.objects.get(facebookid=me.id)
        #update access_token
        u.access_token = access_token
        u.save()
    except user.DoesNotExist:
        uhash = make_uuid()
        u = user.objects.create(uhash=uhash, name=me.name,facebookid = me.id, email=me.email, access_token=access_token)

    return render_to_response('mymovies/facebook_login_success.html',{'name':me.name,'uhash':uhash},context_instance=RequestContext(request))
Beispiel #16
0
def login(request):
    from datetime import datetime 
    from pyfb import Pyfb
    from NossaCarona.settings import FACEBOOK_APP_ID, FACEBOOK_SECRET_KEY, FACEBOOK_REDIRECT_URL_LOGIN
    if request.GET.get('code'): #Login WITH facebook
        code =  request.GET['code']
        facebook = Pyfb(FACEBOOK_APP_ID)
        facebook.get_access_token(FACEBOOK_SECRET_KEY, code, redirect_uri=FACEBOOK_REDIRECT_URL_LOGIN)
        me = facebook.get_myself()
        userdjango = authenticate(fb_id=me.id)
        if not userdjango:
            userdjango = DjangoUser.objects.create_user(me.email, me.email, None)
            userdjango.first_name = me.first_name
            userdjango.last_name = me.last_name
            userdjango.save()
            usuario = Usuario(user=userdjango, sexo=me.gender[0], fb_id=me.id, dt_nascimento=datetime.strptime(me.birthday,'%m/%d/%Y'))
            usuario.save()
        userlogin(request,userdjango)
    else: #login WITHOUT facebook
        pass
    return HttpResponseRedirect('/')
Beispiel #17
0
def facebook_login_success(request):
    code = request.GET.get('code')
    facebook = Pyfb(settings.CLIENT_ID)
    access_token = facebook.get_access_token(
        settings.CLIENT_APP_SECRET,
        code,
        redirect_uri=settings.REDIRECT_URL
    )
    me = facebook.get_myself()

    try:
        fb_user = FacebookUser.objects.get(email_address=me.email)
        fb_user.access_token = access_token
        fb_user.save()
        user = fb_user.user
    except FacebookUser.DoesNotExist:
        user = User.objects.create(
            username=me.email,
            first_name=me.first_name,
            last_name=me.last_name,
            email=me.email
        )
        user.set_password(me.email)
        user.save()
        fb_user = FacebookUser.objects.create(
            first_name=me.first_name,
            last_name=me.last_name,
            access_token=access_token,
            email_address=me.email,
            username=me.email,
            user=user,
        )

    user = authenticate(
        username=me.email,
        password=me.email
    )
    # log the user in
    login(request, user)
    return HttpResponseRedirect(reverse('blacklist_words'))
Beispiel #18
0
    def get_third_party_auth(self, auth_type, facebook_access_token=None):
        """Wrangle and return authentication data from third parties.

        Args:
            auth_type: str, either 'google', or 'facebook'
            facebook_access_token: str, returned by the facebook javasript sdk
                when user logs in.
        Returns tuple of:
            dictionary of user information, which will always contain
                the key 'auth_id', or None if no third-party info is found.
            error as a string
        """
        if auth_type == 'google':
            gae_user = app_engine_users.get_current_user()
            if not gae_user:
                logging.info("No google login found.")
                return (None, 'credentials_missing')
            # Get user first and last names from nickname
            first_name = None
            last_name = None
            if gae_user.nickname():
                nickname = gae_user.nickname()
                if ' ' in nickname:
                    first_name = nickname.split(' ')[0]
                    last_name = nickname.split(' ')[1]
                else:
                    if '@' in nickname:
                        first_name = nickname.split('@')[0]
                    else:
                        first_name = nickname
            # Combine fields in user keyword arguments
            user_kwargs = {
                'auth_id': User.get_auth_id(auth_type, gae_user.user_id()),
                'email': gae_user.email(),
                'google_id': gae_user.user_id(),
                'first_name': first_name,
                'last_name': last_name,
            }
        elif auth_type == 'facebook':
            fb_api = Facebook(config.facebook_app_id)
            fb_api.set_access_token(facebook_access_token)
            me = fb_api.get_myself()

            if me:
                if not hasattr(me, 'email'):
                    # Facebook users might not have an email address, or they
                    # might refuse to share it with us. We can't move forward
                    # without a way to contact them, so treat it as if their
                    # credentials were missing.
                    logging.warning("Found fb user, but they had no email.")
                    return (None, 'email_not_found')

                user_kwargs = {
                    'auth_id': User.get_auth_id(auth_type, me.id),
                    'email': me.email,
                    'facebook_id': me.id,
                    'first_name': me.first_name,
                    'last_name': me.last_name,
                }
            else:
                # The connection between PERTS and facebook is expired or has
                # been used with the GraphAPI already.
                logging.error("Facebook connection expired.")
                return (None, 'credentials_missing')

        return (user_kwargs, None)
Beispiel #19
0
FACEBOOK_APP_ID = '178358228892649'

facebook = Pyfb(FACEBOOK_APP_ID)

#Opens a new browser tab instance and authenticates with the facebook API
#It redirects to an url like http://www.facebook.com/connect/login_success.html#access_token=[access_token]&expires_in=0
facebook.authenticate()

#Copy the [access_token] and enter it below
token = raw_input("Enter the access_token\n")

#Sets the authentication token
facebook.set_access_token(token)

#Gets info about myself
me = facebook.get_myself()

print "-" * 40
print "Name: %s" % me.name
print "From: %s" % me.hometown.name
print

print "Speaks:"
for language in me.languages:
    print "- %s" % language.name

print
print "Worked at:"
for work in me.work:
    print "- %s" % work.employer.name
Beispiel #20
0
class FacebookAccount:
    """Wrapper for facebook API  """

    def __init__(self):
        self.user = None
        self._user_id = None
        self._access_token = None
        self._api = Pyfb(FACEBOOK_APP_ID)
        self._auth_code = None

    def is_authorized(self):
        """Check if alreade authorized via FB"""
        if self._access_token is None:
            return False
        return True

    def _load_user_info(self):
        """Get out user info"""
        fb_user = self._api.get_myself()
        if fb_user is None:
            return False
        self.user = fb_user.name
        self._user_id = str(fb_user.id)
        return True

    def get_auth_url(self):
        """Return URL for authorization"""
        url = self._api.get_auth_code_url(redirect_uri=FACEBOOK_REDIRECT_URL)
        return url

    def set_auth_code(self, code):
        """Save auth. code returned from FB in case of sucessfull login"""
        self._auth_code = code

    def request_access_token(self):
        """Request access token from FB"""
        self._access_token = self._api.get_access_token(
            FACEBOOK_APP_SECRET, self._auth_code, redirect_uri=FACEBOOK_REDIRECT_URL
        )
        print "FB access token: %s" % self._access_token

    #    def get_extended_at(self, short_lived_access_token):
    #        """Get long time lived access token from short lived."""
    #        from facepy.utils import get_extended_access_token
    #        long_lived_access_token, expires_at = get_extended_access_token(
    #            short_lived_access_token,
    #            FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
    #        return long_lived_access_token

    def load_messages(self, messages):
        """Load Messages from Twitter"""
        if not self.is_authorized():
            return False
        if self.user is None:
            if not self._load_user_info():
                return False

        print "facebook_access_token=%s" % self._access_token
        url = "https://graph.facebook.com/%s/posts?access_token=%s" % (self._user_id, self._access_token)
        req = urllib2.Request(url)

        try:
            response = urllib2.urlopen(req)
        except ValueError:
            print "Connection Error - Cannot load data from Facebook "
            return False

        # load data to json
        page = response.read()
        fb_data = json.loads(page)
        # print  json.dumps(fb_data,indent=2)
        response.close()

        # Parse loaded data
        msg_count = 0
        for msg in fb_data["data"]:
            text = ""

            # if 'story' field found use it  as a main text to be shown
            if "story" in msg:
                text = msg["story"]

            # Use text from 'message field as a text instead of 'story'
            # if 'message' field exist
            if "message" in msg:  #
                text = msg["message"]

            # create a new message key from timestamp + 'f'
            # where 'f' is added to be unique ('f' means - facebook)
            record_key = str(to_timestamp(msg["created_time"])) + "f"

            # fill out  message with data
            record = {"account": "facebook", "created": to_ctime(msg["created_time"]), "text": text}
            if text.find(" likes") >= 0:
                # Additionally parse url if this is 'like'-message
                picture_id = msg["id"][msg["id"].find("_") + 1 :]
                record["description"] = FB_POST_URL % (self._user_id, picture_id)
                record["link"] = FB_POST_URL % (self._user_id, picture_id)
            if "link" in msg:
                record["link"] = msg["link"]
            if "picture" in msg:
                record["picture"] = msg["picture"]
            if "name" in msg:
                record["name"] = msg["name"]
            if "description" in msg:
                record["description"] = msg["description"]

            # Add new message
            messages[record_key] = record
            msg_count = msg_count + 1
        print "Facebook : %i messages loaded." % msg_count
Beispiel #21
0
def FacebookMobileLogin (request):
	if request.method == 'POST':

		primary_user = 1

		facebook_id = request.POST.get('fb_user_id', None)
		facebook_email = request.POST.get('fb_user_email', None)
		token = request.POST.get('oauth_token', None)
		expiration = request.POST.get('expiration', None)
		creation = request.POST.get('created', None)

		if not request.user.is_authenticated():
			if token and expiration and creation:
				new_token = OAuthToken(token=token, issued_at=datetime.fromtimestamp(float(creation)),
				                       expires_at=datetime.fromtimestamp(float(expiration)))
				new_token.save()

				facebook = Pyfb(FACEBOOK_APP_ID)
				facebook.set_access_token(token)
				me = facebook.get_myself()

				if (type(me.name) == type(unicode())):

					try:
						find_fb_user = FacebookAppUser.objects.get(fb_uid=me.id)
						find_fb_user.oauth_token = new_token
						find_fb_user.save()
						user = User.objects.get(pk=find_fb_user.appuser.user.pk)
						user.backend = 'django.contrib.auth.backends.ModelBackend'
						login(request, user)
						#response = json.dumps({'status': 'success', 'user':user})
						serialized_response = serializers.serialize('json', [find_fb_user.appuser, ], relations={
							'user': {'fields': ( 'username', 'first_name', 'last_name', 'email', )},
							'facebook_user': {'fields': ( 'fb_uid', 'fb_email', )}, })
						return HttpResponse(serialized_response, mimetype="application/json")

					except FacebookAppUser.DoesNotExist:

						birthday = None
						if hasattr(me, 'birthday'):
							birthday = datetime.strptime(me.birthday, '%m/%d/%Y')

						new_fb_user = FacebookAppUser(user_id=primary_user, fb_uid=me.id, fb_email=me.email,
						                              oauth_token=new_token)
						new_fb_user.save()

						new_user = User.objects.create_user(username=me.username.lower(), email=me.email,
						                                    password=token)
						new_user.first_name = me.first_name
						new_user.last_name = me.last_name
						new_user.save()

						new_appuser = AppUser(user=new_user, facebook_user=new_fb_user, gender=me.gender,
						                      birthdate=birthday)
						new_appuser.save()

						new_fb_user.appuser = new_appuser
						new_fb_user.save()

						new_user.backend = 'django.contrib.auth.backends.ModelBackend'
						login(request, new_user)

						#response = json.dumps({'status': 'success', 'user':new_user})
						#serialized_response = serializers.serialize('json', [ new_user, ])
						#return HttpResponse(me.__dict__)
						serialized_response = serializers.serialize('json', [new_appuser, ], relations={
							'user': {'fields': ('username', 'first_name', 'last_name', 'email', )},
							'facebook_user': {'fields': ( 'fb_uid', 'fb_email', )}, })
						return HttpResponse(serialized_response, mimetype="application/json")

		else:
			if token and expiration and creation:
				new_token = OAuthToken(token=token, issued_at=datetime.fromtimestamp(float(creation)),
				                       expires_at=datetime.fromtimestamp(float(expiration)))
				new_token.save()

				facebook = Pyfb(FACEBOOK_APP_ID)
				facebook.set_access_token(token)
				me = facebook.get_myself()

				if (type(me.name) == type(unicode())):
					try:
						#also need to update to the current token
						fb_user = FacebookAppUser.objects.get(fb_uid=me.id)
						user = fb_user.appuser.user
						#response = json.dumps({'status': 'success', 'user':user, 'fb_user':fb_user})
						#serialized_response = serializers.serialize('json', [ user, fb_user, ])
						#return HttpResponse(me.__dict__)
						serialized_response = serializers.serialize('json', [fb_user.appuser, ], relations={
							'user': {'fields': ( 'username', 'first_name', 'last_name', 'email', )},
							'facebook_user': {'fields': ( 'fb_uid', 'fb_email', )}, })
						return HttpResponse(serialized_response, mimetype="application/json")
					#return HttpResponse(response, mimetype="application/json")
					#if (find_fb_user.appuser.user == request.user):
					#find_fb_user.oauth_token = new_token
					#find_fb_user.save()
					#response = json.dumps({'status': 'success',})
					#return HttpResponse(response, mimetype="application/json")
					#else:
					#response = json.dumps({'status': 'unauthorized',})
					#return HttpResponse(response, mimetype="application/json", status=401)

					except FacebookAppUser.DoesNotExist:
						birthday = None
						if hasattr(me, 'birthday'):
							birthday = datetime.strptime(me.birthday, '%m/%d/%Y')
						new_fb_user = FacebookAppUser(user_id=primary_user, fb_uid=me.id, fb_email=me.email, oauth_token=new_token)
						new_fb_user.save()

						current_user = request.user
						current_user.first_name = me.first_name
						current_user.last_name = me.last_name
						current_user.save()

						app_user = current_user.appuser
						app_user.gender = me.gender
						app_user.birthdate = birthday
						app_user.facebook_user = new_fb_user
						app_user.save()

						return HttpResponse('profile updated with facebook')


		return HttpResponse('failed', status=400)
Beispiel #22
0
FACEBOOK_APP_ID = '178358228892649'

facebook = Pyfb(FACEBOOK_APP_ID)

#Opens a new browser tab instance and authenticates with the facebook API
#It redirects to an url like http://www.facebook.com/connect/login_success.html#access_token=[access_token]&expires_in=0
facebook.authenticate()

#Copy the [access_token] and enter it below
token = raw_input("Enter the access_token\n")

#Sets the authentication token
facebook.set_access_token(token)

#Gets info about myself
me = facebook.get_myself()

print "-" * 40
print "Name: %s" % me.name
print "From: %s" % me.hometown.name
print

print "Speaks:"
for language in me.languages:
    print "- %s" % language.name

print
print "Worked at:"
for work in me.work:
    print "- %s" % work.employer.name