def get_user(request): from django.contrib.auth.models import AnonymousUser if 'facebook' in settings.OPENAUTH_DATA : from facebook import Facebook fb = Facebook(settings.OPENAUTH_DATA['facebook']['key'], settings.OPENAUTH_DATA['facebook']['secret']) fb.check_session(request) if fb.uid is not None : identity = 'facebook:%s' % fb.uid try : from .models import OpenUser oiuser = OpenUser.objects.get(openid=identity, source='openid') return oiuser.user except OpenUser.DoesNotExist : pass try: auth = request.COOKIES.get(AUTH_COOKIE, '') parts = auth.split('|') if len(parts) != 4 : user = AnonymousUser() elif parts[3] == md5("|".join([parts[0], parts[1], parts[2], settings.SECRET_KEY])).hexdigest() : backend = load_backend(parts[2]) user = backend.get_user(parts[0]) or AnonymousUser() else : user = AnonymousUser() except KeyError: user = AnonymousUser() return user
def facebook_connect(request, template='socialregistration/facebook.html', extra_context=dict()): """ View to handle connecting existing accounts with facebook """ fb = Facebook(settings.FACEBOOK_API_KEY, settings.FACEBOOK_SECRET_KEY) if not fb.check_session(request) \ or not request.user.is_authenticated(): extra_context.update( dict(error=FB_ERROR) ) return render_to_response( template, extra_context, context_instance=RequestContext(request) ) try: profile = FacebookProfile.all().filter('uid=',fb.uid).fetch(1)[0] except IndexError: fb_profile = fb.users.getInfo(fb.uid, ['name','email','pic_square','username', ])[0] profile = FacebookProfile(user=request.user, uid=fb.uid, username = fb_profile['username'], real_name = fb_profile['name'], email = fb_profile['email'], pic_url = fb_profile['pic_square'], ) profile.save() return HttpResponseRedirect(_get_next(request))
class AuthFactory(object): # TODO: begin auth/verify auth needed @staticmethod def FacebookAuth(func): def authenticated_request_method(self, *args, **kw): from gaesessions import get_current_session session = get_current_session() self.user = None self.fb = Facebook(creds['AppSecret'], creds['AppID']) if session.has_key('fb_auth_state') and session['fb_auth_state'] == self.request.get('state'): if self.fb.exchange_code_for_auth_token(self.request): session.terminate() session = get_current_session() session['uid'] = 'F' + self.fb.uid self.user = UserFactory.getFacebookUser(self.fb) else: if session.has_key('uid'): self.user = UserFactory.getFacebookUserById(session['uid']) elif not self.fb.check_authentication(self.request): if session.is_active(): session.terminate() import hashlib md5 = hashlib.md5() md5.update("cam is cool") session['fb_auth_state'] = md5.hexdigest() else: if not session.has_key('uid'): session['uid'] = 'F' + self.fb.uid self.user = UserFactory.getFacebookUser(self.fb) func(self, *args, **kw) return authenticated_request_method
def desktop_app(): userdata = {} apiattr = ['uid', 'name', 'about_me', 'activities', 'birthday_date', 'relationship_status', 'books', 'current_location', 'email_hashes', 'first_name', 'hometown_location', 'hs_info', 'interests', 'last_name', 'locale', 'meeting_for', 'meeting_sex', 'movies', 'music', 'notes_count', 'notes_count', 'pic_with_logo', 'pic_big', 'pic_big_with_logo','pic_small','pic_small_with_logo','pic_square','pic_square_with_logo', 'political','profile_blurb','profile_update_time','profile_url','proxied_email', 'quotes','religion','sex','significant_other_id','status','timezone','tv','username', 'username','wall_count','website','work_history', 'education_history', 'affiliations'] # Get api_key and secret_key from a file homedir = os.path.expanduser('~') fbs = open(homedir + '/.fbkeys').readlines() facebook = Facebook(fbs[0].strip(), fbs[1].strip()) file = open('fbdat_1.txt', 'w') facebook.auth.createToken() # Show login window facebook.login() wait_login() # somehow wait for the user to log in # Login to the window, then press enter #print 'After logging in, press enter...' #raw_input() facebook.auth.getSession() info = facebook.users.getInfo([facebook.uid], ['name', 'birthday', 'affiliations', 'sex'])[0] for attr in info: print '%s: %s' % (attr, info[attr]) friends = facebook.friends.get() print friends dat = facebook.users.getInfo(friends,apiattr) print '################################ DAT #########################' print dat for da in dat: # put to dict userdata[da[u'uid']] = da print '################################ USERDATA ####################' print userdata pickle.dump(userdata, file) ## for user in userdata: ## #if not user.haskey(u'uid'): ## s = str(userdata[user]) ## sd = s.encode(output_encoding) ## file.write(sd) file.close() exit()
def context_processor(request) : key = None if 'facebook' in settings.OPENAUTH_DATA and 'key' in settings.OPENAUTH_DATA['facebook'] : key = settings.OPENAUTH_DATA['facebook']['key'] result = {} user = get_user(request) if not user.is_anonymous() : from views import GENERATED_USERBASE result.update({ 'openauth' : { 'need_name' : len(user.get_full_name()) == 0, #'need_screen' : user.username.find(GENERATED_USERBASE) == 0, 'need_email' : user.email == '', } }) inCanvas = False if 'facebook' in settings.OPENAUTH_DATA : from facebook import Facebook fb = Facebook(settings.OPENAUTH_DATA['facebook']['key'], settings.OPENAUTH_DATA['facebook']['secret']) fb.check_session(request) inCanvas = fb.in_canvas result.update({ 'facebook' : { 'apikey' : key, 'inCanvas' : inCanvas, } }) return result
def connect(self, api_key, secret_key): facebook = Facebook(api_key, secret_key) facebook.auth.createToken() facebook.login() print "After logging in, press enter..." raw_input() facebook.auth.getSession()
def authenticate(self, request): if not settings.FACEBOOK_API_KEY in request.COOKIES: return None facebook = Facebook(settings.FACEBOOK_API_KEY, settings.FACEBOOK_SECRET_KEY) check = facebook.check_session(request) fb_user = facebook.users.getLoggedInUser() try: profile = FacebookUserProfile.objects.get(facebook_uid = fb_user) return profile.user except FacebookUserProfile.DoesNotExist: fb_data = facebook.users.getInfo([fb_user], ['uid', 'first_name', 'last_name', 'pic_small', 'current_location']) if not fb_data: return None fb_data = fb_data[0] username = '******' % fb_data['uid'] user_email = '%s@facebookuser.%s.com'%(fb_data['first_name'], settings.SITE_NAME) user = User.objects.create(username = username, email=user_email) user.first_name = fb_data['first_name'] user.last_name = fb_data['last_name'] user.save() location = str(fb_data['current_location']) fb_profile = FacebookUserProfile(facebook_uid = fb_data['uid'], user = user, profile_image_url = fb_data['pic_small'], location=location) fb_profile.save() auth_meta = AuthMeta(user=user, provider='Facebook').save() return user except Exception, e: print str(e)
def on_start(self): self.facebook = Facebook(FACEBOOK_APP_ID, permissions=['publish_actions', 'basic_info']) global modal_ctl modal_ctl = ModalCtl() netcheck.set_prompt(modal_ctl.ask_connect) self.facebook.set_retry_prompt(modal_ctl.ask_retry_facebook)
def post(self): fb = Facebook(settings.key.api, settings.key.secret) logging.debug('Created Facebook instance') # Checks to make s ure that the user is logged into Facebook. if fb.check_session(self.request): pass else: # If not redirect them to your application add page. url = fb.get_add_url() self.response.out.write('<fb:redirect url="' + url + '" />') return # Checks to make sure the user has added your application. if fb.added: pass else: # If not redirect them to your application add page. url = fb.get_add_url() self.response.out.write('<fb:redirect url="' + url + '" />') return greeting = Greeting() greeting.uid = fb.uid greeting.content = self.request.get('content') greeting.put() self.redirect('/')
def fbLogin(): from facebook import Facebook facebook = Facebook(API,SECRET) facebook.auth.createToken() facebook.login() facebook.auth.getSession() return facebook
def app(): from facebook import Facebook #Get api key and secret key facebook=Facebook(API_KEY, API_SECRET) facebook.auth.createToken() #Show login window facebook.login() #Log in to the window and then press enter print "After you log in, press enter" raw_input() facebook.request_extended_permission('friends_birthday') raw_input() facebook.auth.getSession() info = facebook.users.getInfo([facebook.uid], ['name', 'birthday'])[0] print info for attr in info: print '%s: %s' % (attr, info[attr]) friends = facebook.friends.get() friends = facebook.users.getInfo(friends[0:100], ['name', 'birthday']) for friend in friends: if friend['birthday'] is not None: print friend['name'], 'has a birthday on', friend['birthday'] else: print friend['name'], 'has no birthday'
def desktop_app(): from facebook import Facebook # Get api_key and secret_key from a file fbs = open(FB_SETTINGS).readlines() facebook = Facebook(fbs[0].strip(), fbs[1].strip()) facebook.auth.createToken() # Show login window facebook.login() # Login to the window, then press enter print 'After logging in, press enter...' raw_input() facebook.auth.getSession() info = facebook.users.getInfo([facebook.uid], ['name', 'birthday', 'affiliations', 'sex'])[0] for attr in info: print '%s: %s' % (attr, info[attr]) friends = facebook.friends.get() friends = facebook.users.getInfo(friends[0:5], ['name', 'birthday', 'relationship_status']) for friend in friends: if 'birthday' in friend: print friend['name'], 'has a birthday on', friend['birthday'], 'and is', friend['relationship_status'] else: print friend['name'], 'has no birthday and is', friend['relationship_status'] arefriends = facebook.friends.areFriends([friends[0]['uid']], [friends[1]['uid']]) photos = facebook.photos.getAlbums(friends[1]['uid']) print photos
def download_data(api): if api == '&VK': vkapi = VK() return vkapi.get_information_friends() if api == '&Facebook': fbapi = Facebook() return fbapi.get_friends()
def parsing_data_tours(self, url, name, session): fb = Facebook([], self.city) tour_info = {} tour_info["name"] = name header = get_random_user_agent(self.user_agents_list) try: #response = requests.get(url, headers={"User-Agent": header}) response = session.get(url, headers={"User-Agent": header}, timeout=5) except requests.exceptions.RequestException as e: print("Ocurrio un error") try: header = get_random_user_agent(self.user_agents_list) response = session.get(url, headers={"User-Agent": header}, timeout=5) except: print("Ocurrio un segundo error") return tour_info soup = BeautifulSoup(response.text, "lxml") tour_info["name"] = core.get_tour_name(soup) tour_info["telephone"] = core.get_tour_tel(soup) tour_info["email"] = core.get_tour_mail(soup) tour_info["website"] = core.get_tour_website(soup) if tour_info["email"] == "": if "facebook" in tour_info["website"]: tour_info["email"] = scrapper_facebook(tour_info["website"]) else: data = fb.scraping_facebook_tripadvisor(tour_info["name"]) tour_info["email"] = data.get("email", "") del fb return tour_info
def authenticate(self, request): """ Started at http://github.com/uswaretech/Django-Socialauth/blob/master/socialauth/auth_backends.py Made massive improvements with error handling. """ facebook = Facebook(settings.FACEBOOK_API_KEY, settings.FACEBOOK_SECRET_KEY) check = facebook.check_session(request) clear_permissions(request) # for internal perms try: fb_user = facebook.users.getLoggedInUser() fb_data = get_fb_data(facebook, fb_user) profile = FacebookUserProfile.objects.get(facebook_uid = unicode(fb_user)) except FacebookUserProfile.DoesNotExist: username = '******' % fb_data['uid'] fb_user,new_user = User.objects.get_or_create(username = username) fb_user.is_active = True fb_user.first_name = fb_data['first_name'] fb_user.last_name = fb_data['last_name'] fb_user.email = fb_data['email'] fb_user.save() try: profile = FacebookUserProfile(facebook_uid= unicode(fb_data['uid']), user=fb_user) profile.save() auth_meta = AuthMeta(user=user, provider='Facebook').save() except: pass except Exception, e: return None
def _start_fb_session(self): api_key = settings.FACEBOOK_API_KEY secret_key = settings.FACEBOOK_SECRET_KEY app_name = getattr(settings, 'FACEBOOK_APP_NAME', None) callback_path = getattr(settings, 'FACEBOOK_CALLBACK_PATH', None) internal = getattr(settings, 'FACEBOOK_INTERNAL', True) proxy = getattr(settings, 'HTTP_PROXY', None) facebook = Facebook(api_key, secret_key, app_name=app_name, internal=internal, callback_path=callback_path, proxy=proxy) facebook.auth.createToken() # Show login window # Set popup=True if you want login without navigational elements facebook.login() # Login to the window, then press enter print 'After logging in, press enter...' raw_input() facebook.auth.getSession() print 'Session Key: ', facebook.session_key print 'Your UID: ', facebook.uid info = facebook.users.getInfo( [facebook.uid], ['name', 'birthday', 'affiliations', 'sex'])[0] print 'Hi ', info['name'] return facebook
def refresh_data(self): """Refresh this user's data using the Facebook Graph API""" me = Facebook().api(u'/me', {u'fields': u'picture,friends', u'access_token': self.access_token}) self.dirty = False self.name = me[u'name'] self.email = me.get(u'email') self.picture = me[u'picture'] self.friends = [user[u'id'] for user in me[u'friends'][u'data']] return self.put()
def facebook_init(): facebook = Facebook(API_KEY, SECRET) facebook.auth.createToken() facebook.login() print 'After logging in, press any key...' raw_input() facebook.auth.getSession() return facebook
def __init__(self, project_id, collector_id, process_name): BaseCollector.__init__(self, project_id, collector_id, process_name) self.thread_count = 0 self.thread_name = '' self.l = None self.l_thread = None self.e = threading.Event() # First, authenticate with the Facebook Graph API w/ creds from Mongo self.fb = Facebook(client_id=self.auth['client_id'], client_secret=self.auth['client_secret'])
def __init__(self, request): self.facebook = Facebook(deploy.get_facebook_key(), deploy.get_facebook_secret()) if not self.facebook.check_connect_session(request): raise NotLoggedInError() info = self.facebook.users.getInfo([self.facebook.uid], ['name', 'pic_square_with_logo'])[0] super(FacebookUser, self).__init__(models.UserInfo.FACEBOOK, self.facebook.uid, info['name'], info['pic_square_with_logo'])
def process(self, file): facebook = Facebook(self.apikey, self.secret) facebook.session_key = file["fbsession"] try: userinfo = facebook.users.getLoggedInUser() except FacebookError, e: # TODO: Error handling. What do we do if the user isn't logged in? if e.code == 102: # session key has expired log.info("%s is not a valid session, removing upload", file["fbsession"]) file["msg"] = "Facebook session not valid" file["na"] = na.AUTHENTICATE self.cleanup(file) return False
def open(self): """ Opens connection to facebook. """ from facebook import Facebook super(facebook_connector, self).open() facebook = Facebook(api_key=self.api_key, secret_key=self.secret_key) auth_token = facebook.auth.createToken() facebook.login(self.email) time.sleep(self.delay_time) session = facebook.auth.getSession() return facebook
def refresh_data(self): """Refresh this user's data using the Facebook Graph API""" me = Facebook().api(u'/me', { u'fields': u'picture,friends', u'access_token': self.access_token }) self.dirty = False self.name = me[u'name'] self.email = me.get(u'email') self.picture = me[u'picture'] self.friends = [user[u'id'] for user in me[u'friends'][u'data']] return self.put()
def main(): """ The main code. You need have chromedriver in your path. """ # get the credentials credentials = Credentials() credentials.validate_credentials() # to get online on facebook facebook = Facebook(browser) facebook.log_in(credentials) # choice on action to do on Facebook actions(facebook, credentials)
def post(self): rating = int(cgi.escape(self.request.get("rating_select"))) review = str(cgi.escape(self.request.get("reviewtext"))) courseId = int(cgi.escape(self.request.get("courseId"))) fb = Facebook(FB_API_KEY, FB_APP_SECRET) if fb.check_session(self.request): courseQuery = db.Query(Course) courseQuery.filter('courseId =', courseId) cr = CourseReview(courseID=courseId, reviewText=review, overallRating=rating, fbUID=long(fb.uid)) cr.put() self.redirect('/coursepage/?id=' + str(courseId))
def facebook_download(outDir, fb_uid = None): # out dir setup if exists(outDir): rmtree(outDir) os.makedirs(outDir) # Get api_key and secret_key from a file # first line is api key and second line is secret fbs = open('/tmp/facebook_keys.txt').readlines() facebook = Facebook(fbs[0].strip(), fbs[1].strip()) facebook.auth.createToken() # Show login window facebook.login() # Login to the window, then press enter print 'After logging in, press enter...' raw_input() facebook.auth.getSession() # PHOTOS # By album ID # photos = facebook.photos.getAlbums(friends[1]['uid']) # photos = facebook.photos.get('', '5307080636404757', '') friends = facebook.friends.get() names = facebook.users.getInfo(friends, ['name']) for n in names: print n['name'].encode('utf-8'), ':', n['uid'] # By user id if fb_uid is None: fb_uid = facebook.uid photos = facebook.photos.get(fb_uid) progress = ProgressMsg(len(photos), output=sys.stderr) for p in photos: url = p['src_big'] fn = url.split('/')[-1] fd = open(join(outDir, fn), 'w') import urllib bytes = urllib.urlopen(url).read() fd.write(bytes) fd.close() progress.Increment()
def setup_facebook(): FB_SETTINGS = '.facebook' from facebook import Facebook # Get api_key and secret_key from a file fbs = open(FB_SETTINGS).readlines() facebook = Facebook(fbs[0].strip(), fbs[1].strip()) facebook.auth.createToken() print facebook.get_login_url() #facebook.session_key = "1b2fcc7cabfc2574898155c2-1926269" #facebook.secret = u'd21ee6b6b24515fb00af58fa3bfea907' raw_input("waiting") facebook.auth.getSession() return facebook
def handle(self, *args, **options): """Load the templates into facebook (probably clear them out beforehand)""" facebook_obj = Facebook(settings.FACEBOOK_API_KEY, settings.FACEBOOK_SECRET_KEY) #blow up all templates current_templates = facebook_obj.feed.getRegisteredTemplateBundles() for t in current_templates: print "Deactivating old bundle #%i ..." % t['template_bundle_id'] facebook_obj.feed.deactivateTemplateBundleByID( t['template_bundle_id']) #install templates from our facebook settings file for bundle in settings.FACEBOOK_TEMPLATES: name = bundle[0] one_line_template = bundle[1][0] short_template = bundle[1][1] full_template = bundle[1][2] action_template = bundle[1][3] response = facebook_obj.feed.registerTemplateBundle( one_line_template, short_template, full_template, action_template) try: template = FacebookTemplate.objects.get(name=name) #facebook_obj.feed.deactivateTemplateBundleByID(template.template_bundle_id) print "Replacing old '%s' bundle ..." % (name.capitalize()) except FacebookTemplate.DoesNotExist: template = FacebookTemplate(name=name) print "Loading '%s' bundle ..." % (name.capitalize()) template.template_bundle_id = response template.save()
def get_connected_friends(api_key, secret_key, fb_session_key, fb_uid, retry=0): """Return a list with the FB user's friends' IDs that are connected to our app""" retval = [] try: facebook = Facebook(api_key, secret_key) facebook.session_key = fb_session_key info = facebook.friends.getAppUsers() retval = info except urllib2.URLError, ue: if retry < _MAX_RETRIES: # retry once time.sleep(0.1) return get_connected_friends(api_key, secret_key, fb_session_key, fb_uid, retry=retry + 1) else: _log.exception(ue) _log.warn("Could not get FB friends: %s", fb_uid)
def setUp(self): super().setUp() self.actor['numeric_id'] = '212038' self.source = Facebook.new(actor=self.actor) self.domain = Domain(id='snarfed.org', tokens=['towkin']).put() self.auth = f'token=towkin&key={self.source.key.urlsafe().decode()}' self.mox.StubOutWithMock(gr_facebook, 'now_fn')
def test_profile_new_user(self): self.assertIsNone(Facebook.get_by_id('212038')) # webmention discovery self.expect_requests_get('https://snarfed.org/', '', stream=None) self.mox.ReplayAll() resp = self.get_response('profile?token=towkin', text=MBASIC_HTML_ABOUT) self.assertEqual(200, resp.status_int, resp.text) self.assertEqual(self.source.key.urlsafe().decode(), resp.json) fb = Facebook.get_by_id('212038') self.assertEqual('Ryan Barrett', fb.name) self.assertEqual('https://scontent-sjc3-1.xx.fbcdn.net/v/t1.0-1/cp0/e15/q65/p74x74/39610935_10104076860151373_4179282966062563328_o.jpg?...', fb.picture) self.assertEqual(['https://snarfed.org/', 'https://foo.bar/'], fb.domain_urls) self.assertEqual(['snarfed.org', 'foo.bar'], fb.domains)
def fb_checking(data): start = time.time() try: facebook_close = Facebook(data).check() if facebook_close: email = 'C' print('C in fb') return email else: email = Facebook(data).get_mail() print('mail in fb!!!') return email except: pass end = time.time() print("----{} seconds---- Facebook".format(end - start))
def process_request(self, request): self._setcookie = [] request.__class__.user = LazyUser() request._authMiddleware = self import settings if 'facebook' in settings.OPENAUTH_DATA : from facebook import Facebook fb = Facebook(settings.OPENAUTH_DATA['facebook']['key'], settings.OPENAUTH_DATA['facebook']['secret']) fb.check_session(request) request.facebook = fb else : request.facebook = None return None
def desktop_app(): # Get api_key and secret_key from a file fbs = open(FB_SETTINGS).readlines() facebook = Facebook(fbs[0].strip(), fbs[1].strip()) facebook.auth.createToken() # Show login window facebook.login() # Login to the window, then press enter #print 'After logging in, press enter...' #raw_input() facebook.auth.getSession() return facebook
def get_user_info(api_key, secret_key, fb_session_key, fb_uid, retry=0): """Return a dictionary with the FB user's name and email address""" retval = {"name": None, "email": None} try: facebook = Facebook(api_key, secret_key) facebook.session_key = fb_session_key info = facebook.users.getInfo([fb_uid], ["name", "proxied_email"])[0] retval["name"] = info.get("name", None) retval["email"] = info.get("proxied_email", None) except urllib2.URLError, ue: if retry < _MAX_RETRIES: # retry once time.sleep(0.1) return get_user_info(api_key, secret_key, fb_session_key, fb_uid, retry=retry + 1) else: _log.exception(ue) _log.warn("Could not get FB user info: %s", fb_uid)
def setUp(self, ): parser = SafeConfigParser() parser.read("credentials.ini") self.user = parser.get("facebook", "user") self.passwd = parser.get("facebook", "passwd") # self.display = Display(visible=0, size=(800,600)) # self.display.start() self.fb = Facebook(self.user, self.passwd)
class Shazam(object): """ Provides methods for downloading Shazam history """ def __init__(self, fb_email=None, fb_password=None): self.session = Ghost().start() self.facebook = Facebook(self.session, fb_email, fb_password) self.login_successful = False self.fat = None # Facebook access token def login(self): """ Performs Shazam login :return: bool - True if success, False - otherwise """ if self.login_successful: return True if not self.facebook.login(): return False # fat = self.facebook.get_access_token(app_id) # if not fat: # logging.error("Couldn't get Facebook access token") # return False # # user_id = self.facebook.get_user_id() # if not user_id: # logging.error("Couldn't get Facebook user id") # return False # # query = [("fat", fat), # ("uid", user_id)] # body = urllib.urlencode(query) # login_url = "http://www.shazam.com/login" # try: # self.session.open(login_url, # method="post", # body=body) # except Exception, e: # logging.error("Shazam login failed") # logging.error(str(e)) # return False myshazam_url = "http://www.shazam.com/myshazam" try: self.session.open(myshazam_url) except Exception, e: logging.error("Shazam login failed. Couldn't open myshazam page.") logging.error(str(e)) return False try: self.session.click(".js-fblogin") except Exception, e: logging.error("Shazam login failed. Couldn't click login button.") logging.error(str(e)) return False
def get_friends(self): """Fetch this user's friends using the Facebook Graph API""" me = Facebook().api( u'/me', { u'fields': u'id,name,picture,friends', u'access_token': self.access_token }) return me["friends"]["data"]
def facebook(self): """Get a facebook object, if pyfacebook is present, the user is logged in and is a facebook connect user. Otherwise this is None.""" try: from facebook import Facebook except ImportError: log.warning("PyFacebook is not installed!") else: if self.user and self.user.profile.uses_facebook_connect: # This implies, that the correct cookies must be set. We don't # double check for that. api_key = get_app().cfg['facebook/api_key'] secret_key = get_app().cfg['facebook/secret_key'] facebook = Facebook(api_key, secret_key) # Setting the cookie values # It's so cool to have no private attributes. (; facebook.uid = self.session['fb_user_id'] facebook.session_key = self.session['fb_session_id'] return facebook
def get_facebook_api(request): """ This will return None on failure (we call this from places where we know there's no API -- responsible for checking None condition on other IFs) """ from jjmaker.models import get_user_profile, new_user_profile fb = Facebook(settings.FACEBOOK_API_KEY, settings.FACEBOOK_SECRET_KEY) # Use the data from the cookie if present try: auth_token = get_facebook_access_token(request) except: auth_token = request.GET.get('auth_token', None) try: fb.auth_token = auth_token userprofile_id = get_facebook_uid(request) except KeyError, MultiValueDictKeyError: traceback.print_exc() fb = None
def test_can_handle_pyfacebook_error_on_none_expires(self): # setup partial mock on check_session() request = mox.MockObject(HttpRequest) request.method = "GET" request.GET = {} request.POST = {} facebook = Facebook('foo', 'bar', 'baz') request.facebook = facebook def mock_validate_signature(*args, **kwargs): ret = self.validate_signature_return() ret['expires'] = 'None' return ret facebook.validate_signature = mock_validate_signature replay_all(request) auth = FacebookConnectBackend() self.assertEqual(None, auth.authenticate(request=request))
def authenticate(self, request): """ if not settings.FACEBOOK_API_KEY in request.COOKIES: logging.debug("Could not find FACEBOOK_API_KEY in Cookies") return None """ facebook = Facebook(settings.FACEBOOK_API_KEY, settings.FACEBOOK_SECRET_KEY) check = facebook.check_session(request) fb_user = facebook.users.getLoggedInUser() try: profile = FacebookUserProfile.objects.get(facebook_uid = str(fb_user)) return profile.user except FacebookUserProfile.DoesNotExist: fb_data = facebook.users.getInfo([fb_user], ['uid', 'about_me', 'first_name', 'last_name', 'pic_big', 'pic', 'pic_small', 'current_location', 'profile_url', 'email']) if not fb_data: return None fb_data = fb_data[0] username = '******' % fb_data['uid'] email = fb_data['email'] try: user = User.objects.get(email=email) except: #user_email = '*****@*****.**'%(fb_data['uid']) user = User.objects.create(username = username) user.first_name = fb_data['first_name'] user.last_name = fb_data['last_name'] user.save() location = str(fb_data['current_location']) about_me = str(fb_data['about_me']) url = str(fb_data['profile_url']) fb_profile = FacebookUserProfile(facebook_uid = str(fb_data['uid']), user = user, profile_image_url = fb_data['pic'], profile_image_url_big = fb_data['pic_big'], profile_image_url_small = fb_data['pic_small'], location=location, about_me=about_me, url=url) fb_profile.save() auth_meta = AuthMeta(user=user, provider='Facebook').save() return user except Exception, e: print str(e)
def simple_web_app(request, api_key, secret_key): fb = Facebook(api_key, secret_key, request.GET['auth_token']) fb.auth.getSession() friend_ids = fb.friends.get() info = fb.users.getInfo(friend_ids, ['name', 'pic']) print '<html><body>' for friend in info: print '<a href="%(pic)s">%(name)s</a>' % friend print '</body></html>'
def authenticate(self, request): if not settings.FACEBOOK_API_KEY in request.COOKIES: return None facebook = Facebook(settings.FACEBOOK_API_KEY, settings.FACEBOOK_SECRET_KEY) check = facebook.check_session(request) fb_user = facebook.users.getLoggedInUser() try: profile = FacebookUserProfile.objects.get(facebook_uid=fb_user) return profile.user except FacebookUserProfile.DoesNotExist: fb_data = facebook.users.getInfo([fb_user], [ 'uid', 'first_name', 'last_name', 'pic_small', 'current_location' ]) if not fb_data: return None fb_data = fb_data[0] username = '******' % fb_data['uid'] user_email = '%s@facebookuser.%s.com' % (fb_data['first_name'], settings.SITE_NAME) user = User.objects.create(username=username, email=user_email) user.first_name = fb_data['first_name'] user.last_name = fb_data['last_name'] user.save() location = str(fb_data['current_location']) fb_profile = FacebookUserProfile( facebook_uid=fb_data['uid'], user=user, profile_image_url=fb_data['pic_small'], location=location) fb_profile.save() auth_meta = AuthMeta(user=user, provider='Facebook').save() return user except Exception, e: print str(e)
def receive_message(): try: if request.method == "GET": token_sent = request.args.get("hub.verify_token") hub_challenge = request.args.get("hub.challenge") verify_token = fb.verify_fb_token(token_sent, hub_challenge) return verify_token else: output = request.get_json() for event in output["entry"]: messaging = event["messaging"] for message in messaging: if message.get("message"): recipient_id = message["sender"]["id"] profile = fb.get_profile(recipient_id) fullname = profile["fullname"] if message["message"].get("text"): text = message["message"].get("text") data = qismo.send_message(recipient_id, fullname, text) if message["message"].get("attachments"): message = message["message"] attachments = message["attachments"] attachment = attachments[0] payload = attachment["payload"] if payload is not None: attachment_url = payload["url"] if attachment_url is not None: data = qismo.send_attachment_message( recipient_id, fullname, attachment_url) success_message = "Success processing facebook message" app.logger.info(success_message) return jsonify(success.message(success_message)), 200 except Exception as e: app.logger.error(str(e)) return jsonify(error.fb_error(str(e))), 200
def get_user_info(api_key, secret_key, fb_session_key, fb_uid, retry=0): """Return a dictionary with the FB user's name and email address""" retval = {'name': None, 'email': None} try: facebook = Facebook(api_key, secret_key) facebook.session_key = fb_session_key info = facebook.users.getInfo([fb_uid], ['name', 'proxied_email'])[0] retval['name'] = info.get('name', None) retval['email'] = info.get('proxied_email', None) except urllib2.URLError, ue: if retry < _MAX_RETRIES: # retry once time.sleep(.1) return get_user_info(api_key, secret_key, fb_session_key, fb_uid, retry=retry + 1) else: _log.exception(ue) _log.warn("Could not get FB user info: %s", fb_uid)
def qismo_message(): try: output = request.get_json() participants = output["payload"]["room"]["participants"] recipient_id = helper.search_customer(participants) if recipient_id is None: raise Exception("Customer ID not found") # message_type = output["payload"]["message"]["type"] payload = output["payload"] message = payload["message"] message_type = message["type"] if message_type == "text": text = message["text"] fb.send_message(recipient_id, text) elif message_type == "file_attachment": attachment_payload = message["payload"] caption = attachment_payload["caption"] attachment_url = attachment_payload["url"] # !!!Send file like csv still error fb.send_attachment_message(recipient_id, attachment_url) if caption is not None or caption is not "": fb.send_message(recipient_id, caption) return jsonify(success.message("Success handling Qismo message")), 200 except Exception as e: app.logger.error(str(e)) return jsonify(error.qismo_error(str(e))), 200
def initialize(self, request, response): """ Initialize's this request's Facebook client. """ super(FacebookRequestHandler, self).initialize(request, response) app_name = self._fbconfig_value('app_name', '') api_key = self._fbconfig_value('api_key', None) secret_key = self._fbconfig_value('secret_key', None) require_app = self._fbconfig_value('require_app', True) require_login = self._fbconfig_value('require_login', True) need_session = self._fbconfig_value('need_session', True) check_session = self._fbconfig_value('check_session', True) self.facebook = Facebook(api_key, secret_key, app_name=app_name) self._messages = None self.redirecting = False if require_app or require_login: if not self.facebook.check_session(request): self.redirect(self.facebook.get_login_url(next=[request.path,""][request.path == '/'])) self.redirecting = True return elif check_session: self.facebook.check_session(request) # ignore response # NOTE: require_app is deprecated according to modern Facebook login # policies. Included for completeness, but unnecessary. if require_app and not self.facebook.added: self.redirect(self.facebook.get_add_url(next=[request.path,""][request.path == '/'])) self.redirecting = True return if not (require_app or require_login) and need_session: self.facebook.auth.getSession()
def app(): from facebook import Facebook #Get api key and secret key facebook = Facebook(API_KEY, API_SECRET) facebook.auth.createToken() #Show login window facebook.login() #Log in to the window and then press enter print "After you log in, press enter" raw_input() facebook.request_extended_permission('friends_birthday') raw_input() facebook.auth.getSession() info = facebook.users.getInfo([facebook.uid], ['name', 'birthday'])[0] print info for attr in info: print '%s: %s' % (attr, info[attr]) friends = facebook.friends.get() friends = facebook.users.getInfo(friends[0:100], ['name', 'birthday']) for friend in friends: if friend['birthday'] is not None: print friend['name'], 'has a birthday on', friend['birthday'] else: print friend['name'], 'has no birthday'
def send_fb_notifications(aptf, results): fb = Facebook(settings.FACEBOOK_API_KEY, settings.FACEBOOK_SECRET_KEY) uid = int(aptf.get_email()[3:]) r = fb.dashboard.setCount(uid, int(time.time())) r = fb.dashboard.addNews(uid, [{ 'message': 'Test!', 'action_link': { 'href': 'http://cnn.com', 'text': 'boo' }, }]) r = fb.notifications.sendEmail([uid], "Test!", "This is another test", '') raise Exception(r)
def init(webhandler): State._tabs = { 'fb': { 'label': 'Facebook Events' }, 'friends': { 'label': 'Friends\' Events' }, 'mine': { 'label': 'My Events' } } for day_tab in config.DAY_TABS: State._tabs[day_tab] = config.DAY_TABS[day_tab] State._selected = webhandler.request.get('tab', config.DEFAULT_TAB) fb = Facebook(config.FACEBOOK_API_KEY, config.FACEBOOK_SECRET_KEY) fb.check_session(webhandler.request) State._facebook = fb State._facebook_user = fb.uid
def terminal(args): fb = Facebook() if args['messages']: show_unread_messages(fb) if args['notifications']: show_notifications(fb) if args['online']: show_friends_online(fb) if args['post']: post_on_wall(fb, args['post']) if args['query']: custom_FQL(fb, args['query'].lower()) if args['spy_friend']: show_friend_online_status(fb, args['spy_friend'])
def test_silo_url(self): self.source.username = None self.assertEqual('https://www.facebook.com/212038', self.source.silo_url()) self.source.username = '******' self.assertEqual('https://www.facebook.com/foo', self.source.silo_url()) self.actor.update({ 'numeric_id': '1000000000000001', 'username': None, }) self.assertIsNone(Facebook.new(actor=self.actor).silo_url())
def init_facebook(self): """Sets up the request specific Facebook and User instance""" facebook = Facebook() user = None # initial facebook request comes in as a POST with a signed_request if u'signed_request' in self.request.POST: facebook.load_signed_request(self.request.get('signed_request')) # we reset the method to GET because a request from facebook with a # signed_request uses POST for security reasons, despite it # actually being a GET. in webapp causes loss of request.POST data. self.request.method = u'GET' self.set_cookie('u', facebook.user_cookie, datetime.timedelta(minutes=1440)) elif 'u' in self.request.cookies: facebook.load_signed_request(self.request.cookies.get('u')) # try to load or create a user object if facebook.user_id: user = User.get_by_key_name(facebook.user_id) if user: # update stored access_token if facebook.access_token and \ facebook.access_token != user.access_token: user.access_token = facebook.access_token user.put() # refresh data if we failed in doing so after a realtime ping if user.dirty: user.refresh_data() # restore stored access_token if necessary if not facebook.access_token: facebook.access_token = user.access_token if not user and facebook.access_token: me = facebook.api(u'/me', {u'fields': u'picture,friends'}) user = User( key_name=facebook.user_id, user_id=facebook.user_id, access_token=facebook.access_token, name=me[u'name'], email=me.get(u'email'), # optional picture=me[u'picture'], friends=[user[u'id'] for user in me[u'friends'][u'data']]) user.put() self.facebook = facebook self.user = user