def authorized(request, authorization_id): auth = FacebookAuthorization.objects.get(id=authorization_id) if request.GET.get('error'): # @todo Handle user not wanting to auth. return redirect(auth.get_absolute_url()) # @todo We are probably better of using some kind of # application_installation custom signal that creates the user. code = request.GET.get('code') try: access_token = auth.get_access_token(code)[0] except urllib2.HTTPError: return redirect(auth.get_facebook_authorize_url()) request_data = GraphAPI(access_token).get_object('me') facebook_user, created = FacebookUser.objects.get_or_create( uid=request_data['id'], application=auth.application) facebook_user.access_token = access_token facebook_user.first_name = request_data['first_name'] facebook_user.last_name = request_data['last_name'] facebook_user.locale = request_data.get('locale') facebook_user.timezone = request_data.get('timezone') facebook_user.religion = request_data.get('religion') facebook_user.location = request_data.get('location', {}).get('name') facebook_user.gender = request_data.get('gender') facebook_user.email = request_data.get('email') facebook_user.save() authenticated_user = authenticate(facebook_user=facebook_user) if authenticated_user is None: # @todo import the profile and check if it has a foreignkey to # FacebookUser username = "".join(random.choice(BASE62_ALPHABET) for i in xrange(30)) user = User.objects.create_user(username=username, email=facebook_user.email) user.first_name = facebook_user.first_name[0:30] user.last_name = facebook_user.last_name[0:30] user.set_unusable_password() user.save() try: profile = user.get_profile() profile.facebook = facebook_user profile.save() authenticated_user = authenticate(facebook_user=facebook_user) except SiteProfileNotAvailable: user.delete() if authenticated_user is not None: if authenticated_user.is_active: login(request, authenticated_user) #@todo handle user not active. #@todo what should happen if the user doesn't get logged in? return redirectjs(auth.next)
def upload_to_facebook(img_path): # Takes image path config = ConfigParser() config.read('auth.ini') app_key = config.get('facebook_credentials', 'app_key') app_key_secret = config.get('facebook_credentials', 'app_key_secret') user_access_token = config.get('facebook_credentials', 'user_access_token') page_id = config.get('facebook_credentials', 'page_id') graph = GraphAPI(user_access_token) resp = graph.get('me/accounts') page_access_token = None for page in resp['data']: if page['id'] == page_id: page_access_token = page['access_token'] graph = GraphAPI(page_access_token) graph = GraphAPI(access_token=access_token, version="3.1") print('Uploading photo...') image = open(img_path, 'rb') graph.put_photo(image, message='Test caption')
def facebook_share_pre_post(request, facebook_access_token): if not facebook_access_token: raise ServiceError( "Can't share to your timeline if you haven't signed into Facebook yet." ) facebook_share = True try: associate_facebook_account(request.user, facebook_access_token, request=request) except ServiceError: papertrail.debug( u'associate_facebook_account failed inside facebook_share_pre_post: (user: {}, token: {}), raising InvalidFacebookAccessToken' .format(request.user.username, facebook_access_token)) facebook_share = False Metrics.facebook_error_during_publish.record(request) if request.app_version != '1.0.1': try: permissions = GraphAPI(facebook_access_token).get_object( 'me/permissions')['data'][0] except GraphAPIError as e: papertrail.debug( u'me/permissions failed inside facebook_share_pre_post: {} (user: {}, token: {}), raising InvalidFacebookAccessToken' .format(e.message, request.user.username, facebook_access_token)) raise InvalidFacebookAccessToken( "Invalid Facebook access token, please re-auth with Facebook.") except IOError as e: papertrail.debug( u'me/permissions failed inside facebook_share_pre_post with IOError: {} (user: {}), disabling facebook_share' .format(e.message, request.user.username)) facebook_share = False else: if permissions.get('installed') != 1 or permissions.get( 'publish_actions') != 1: papertrail.debug( u'me/permissions failed inside facebook_share_pre_post because insufficient permissions (user: {}), disabling facebook_share' .format(request.user.username)) facebook_share = False Metrics.facebook_insufficient_permissions_during_publish.record( request) return facebook_share
def authenticate(self, fb_id=None, access_token=None): if not (fb_id and access_token): return None UserModel = get_user_model() try: user = UserModel._default_manager.get(_fb_id=fb_id) except UserModel.DoesNotExist: return None else: try: g = GraphAPI(access_token) g.get('me', {}) except GraphAPIError: return None else: return user
def validate(self): rv = Form.validate(self) if not rv: return False #validate facebook credentials if FB auth is selected if self.auth_fb.data and AUTH_TYPE_SOCIAL: fb_appid = self.fb_appid.data or current_app.config['FB_APP_ID'] fb_app_secret = self.fb_app_secret.data or current_app.config[ 'FB_APP_SECRET'] try: access_token = GraphAPI().get_app_access_token( fb_appid, fb_app_secret) except: current_app.logger.exception( 'Exception while trying to get access_token with APP ID:%s Secret:%s' % (fb_appid, fb_app_secret)) self.fb_app_secret.errors.append( 'Incorrect APP ID or secret configured') return False if (self.auth_fb_like.data or self.auth_fb_post.data) and self.fb_page.data == '': self.fb_page.errors.append( 'Facebook Social action configured without Page URL') return False if self.auth_fb_post.data and self.fb_page.data: try: page = GraphAPI(access_token).get_object(self.fb_page.data, fields='location') except: current_app.logger.exception( 'Exception while trying to get page:%s for location' % (self.fb_page.data)) self.fb_page.errors.append('Incorrect page URL specified') return False if not page.get('location'): self.fb_page.errors.append( 'Given FB Page does not supports checkin') return False if self.enable_session_limit.data: try: int(self.daily_data_limit.data) except: self.daily_data_limit.errors.append( 'Please enter valid value for Session Limit') return False try: int(self.monthly_data_limit.data) except: self.monthly_data_limit.errors.append( 'Please enter valid value for Monthly Limit') return False try: int(self.session_timelimit.data) except: self.session_timelimit.errors.append( 'Please enter valid value for Session time') return False return True
def facebook_share_pre_post(request, facebook_access_token): if not facebook_access_token: raise ServiceError("Can't share to your timeline if you haven't signed into Facebook yet.") facebook_share = True try: associate_facebook_account(request.user, facebook_access_token, request=request) except ServiceError: papertrail.debug( u"associate_facebook_account failed inside facebook_share_pre_post: (user: {}, token: {}), raising InvalidFacebookAccessToken".format( request.user.username, facebook_access_token ) ) facebook_share = False Metrics.facebook_error_during_publish.record(request) if request.app_version != "1.0.1": try: permissions = GraphAPI(facebook_access_token).get_object("me/permissions")["data"][0] except GraphAPIError as e: papertrail.debug( u"me/permissions failed inside facebook_share_pre_post: {} (user: {}, token: {}), raising InvalidFacebookAccessToken".format( e.message, request.user.username, facebook_access_token ) ) raise InvalidFacebookAccessToken("Invalid Facebook access token, please re-auth with Facebook.") except IOError as e: papertrail.debug( u"me/permissions failed inside facebook_share_pre_post with IOError: {} (user: {}), disabling facebook_share".format( e.message, request.user.username ) ) facebook_share = False else: if permissions.get("installed") != 1 or permissions.get("publish_actions") != 1: papertrail.debug( u"me/permissions failed inside facebook_share_pre_post because insufficient permissions (user: {}), disabling facebook_share".format( request.user.username ) ) facebook_share = False Metrics.facebook_insufficient_permissions_during_publish.record(request) return facebook_share
def get_friends(): token = flockly.authpage.get_user_access_token(session['uid']) graph = GraphAPI(token) friends = [] res = graph.get('/me/friends') while res['data']: friends = friends + res['data'] if 'paging' in res and 'next' in res['paging']: res = json.loads(requests.get(res['paging']['next']).text) return friends
def auth_redirect(): f = FacebookAPI(config.API_KEY, config.API_SECRET, config.SITE_URL + "/auth_redirect") try: access_token = f.get_access_token(request.args.get('code', '')) graph = GraphAPI(access_token['access_token']) id = graph.get('me')['id'] save_user(id, access_token['access_token'], int(int(access_token['expires']) + time.time() - 3600)) session['uid'] = id return redirect('/') except FacebookClientError as e: return 'Authorization Failed:' + str(e)
def get_fb_page_access_token(): if settings.FACEBOOK_PAGE_ACCESS_TOKEN == "": params = {'client_id': settings.FACEBOOK_CLIENT_ID, 'client_secret': settings.FACEBOOK_CLIENT_SECRET, 'grant_type': 'client_credentials'} response = requests.get("https://graph.facebook.com/v2.8/oauth/access_token", params=params) user_access_token = response.json()["access_token"] user_graph = GraphAPI(user_access_token) accounts = user_graph.get("me/accounts") for page in accounts["data"]: if page["name"] == settings.FACEBOOK_PAGE_NAME: return page["access_token"] else: return settings.FACEBOOK_PAGE_ACCESS_TOKEN
def login_facebook(request): try: code = request.DATA['code'] except KeyError: ret = produceRetCode("fail", "code required") return Response(ret, status=status.HTTP_202_ACCEPTED) try: f = FacebookAPI(APP_ID, APP_SECRET, uri) res = f.get_access_token(code) # get long term token graph = GraphAPI(res['access_token']) # access GraphAPI of facebook personalInfo = graph.get('me') except Exception: ret = produceRetCode("fail", "facebook api error") return Response(ret, status=status.HTTP_202_ACCEPTED) university = University.objects.get(shortname = "Unknown") major = Major.objects.get(shortname = "Unknown") userData = { "first_name": personalInfo['first_name'], "last_name" : personalInfo['last_name'], "nick_name" : personalInfo['name'], "password" : "Unknown", "gender" : personalInfo['gender'], "image" : "Unknown", "tpa_type" : "facebook", "tpa_id" : "facebook" + personalInfo['id'], "tpa_token" : res['access_token'], "university": university.id, # default university id "major" : major.id, "email" : "*****@*****.**", "phone" : "Unknown" } try: user = User.objects.get(tpa_id=userData['tpa_id']) # user account exist, directly login token = produceLoginToken(userData['tpa_id']) ip = getIP(request) return setUserState(user.id, ip, token) except User.DoesNotExist: # create new account serializer = RegisterSerializer(data=userData) if serializer.is_valid(): serializer.save() user = User.objects.get(tpa_id=userData['tpa_id']) token = produceLoginToken(userData['tpa_id']) ip = getIP(request) return setUserState(user.id, ip, token) else: ret = produceRetCode('fail', 'login data from facebook error', serializer.errors) return Response(ret, status=status.HTTP_202_ACCEPTED)
def facebook_login(request): code = request.GET.get('code') f = FacebookAPI(APP_KEY, APP_SECRET, FACEBOOK_REDIRECT) access_token = f.get_access_token(code) final_access_token = access_token['access_token'] request.session['access_token'] = final_access_token graph = GraphAPI(final_access_token) try: me = graph.get('me') request.session['facebook_id'] = me['id'] request.session['first_name'] = me['first_name'] request.session['last_name'] = me['last_name'] if (len(FacebookUser.objects.filter(facebook_id=me['id'])) == 0): f = FacebookUser.create(me['id'],me['first_name'],me['last_name']) f.save() return redirect('/profile/') except FacebookClientError: return HttpResponse("Sorry, something went wrong.")
def validate(self): rv = Form.validate(self) if not rv: return False #validate facebook credentials if FB auth is selected if self.auth_fb.data and AUTH_TYPE_SOCIAL: fb_appid = self.fb_appid.data or current_app.config['FB_APP_ID'] fb_app_secret = self.fb_app_secret.data or current_app.config['FB_APP_SECRET'] try: access_token = GraphAPI().get_app_access_token(fb_appid,fb_app_secret) except: current_app.logger.exception('Exception while trying to get access_token with APP ID:%s Secret:%s'%(fb_appid,fb_app_secret)) self.fb_app_secret.errors.append('Incorrect APP ID or secret configured') return False if ( self.auth_fb_like.data or self.auth_fb_post.data ) and self.fb_page.data == '': self.fb_page.errors.append('Facebook Social action configured without Page URL') return False if self.auth_fb_post.data and self.fb_page.data: try: page = GraphAPI(access_token).get_object(self.fb_page.data,fields='location') except: current_app.logger.exception('Exception while trying to get page:%s for location'%(self.fb_page.data)) self.fb_page.errors.append('Incorrect page URL specified') return False if not page.get('location'): self.fb_page.errors.append('Given FB Page does not supports checkin') return False if self.enable_session_limit.data: try: int(self.daily_data_limit.data) except: self.daily_data_limit.errors.append('Please enter valid value for Session Limit') return False try: int(self.monthly_data_limit.data) except: self.monthly_data_limit.errors.append('Please enter valid value for Monthly Limit') return False try: int(self.session_timelimit.data) except: self.session_timelimit.errors.append('Please enter valid value for Session time') return False return True
class ChatSession(object): graph_api_class = GraphAPI local = threading.local() def __init__(self, user_id, chat_id=None): self.user_id = str(user_id) if not chat_id: chat, created = models.Chat.objects.get_or_create(fb_user_id=self.user_id) self.chat_id = chat.pk else: self.chat_id = chat_id self.lock_key = CACHE_PREFIX + '-lock-chat-with-%s' % user_id self.cache_key = CACHE_PREFIX + '-chat-session-%s' % user_id self.cache = caches['default'] self.cache_timeout = settings.CHAT_SESSION_TIMEOUT self.graph = GraphAPI(settings.FBBOT_PAGE_ACCESS_TOKEN) self.data = dict() self._session_usage = 0 if not hasattr(self.local, 'sessions'): self.local.sessions = dict() def save(self): self.cache.set(self.cache_key, self.data, self.cache_timeout) self.cache.close() def load(self): self.data = self.cache.get(self.cache_key, dict()) if not self.data: log.info('Start new chat session for u=%s' % self.user_id) if not self.data.get('user_profile', None): self.data['user_profile'] = self.graph.get(str(self.user_id)) @property def search_request(self): """ :rtype: ``FbSearchRequest`` """ if not self.data.get('search_request', None): log.info('Create new search_request for u=%s' % self.user_id) self.data['search_request'] = FbSearchRequest(self.user_id) return self.data['search_request'] @property def user_first_name(self): if 'first_name' in self.data['user_profile']: return self.data['user_profile']['first_name'] else: return self.data['user_profile']['name'].split(' ', 1)[0] def reply(self, text): return messenger_client.send_message(self.user_id, text) def attachment_reply(self, attachment): return messenger_client.send_attachment_reply(self.user_id, attachment) def send_typing_on(self): return messenger_client.messenger.send_typing_on(self.user_id) def send_typing_off(self): return messenger_client.messenger.send_typing_off(self.user_id) def send_mark_seen(self): return messenger_client.messenger.mark_seen(self.user_id) def __enter__(self): # Check session in local thread first local_session = self.local.sessions.get(self.user_id, None) if local_session: local_session._session_usage += 1 return local_session else: self.load() self.local.sessions[self.user_id] = self self._session_usage += 1 return self def __exit__(self, exc_type, exc_value, traceback): session = self.local.sessions.get(self.user_id, self) session._session_usage -= 1 if session._session_usage <= 0: session.local.sessions.pop(self.user_id, None) session.save()
import requests from facebook import GraphAPI graph = GraphAPI( "EAAacYxZBsn4sBAKlkiL421S4mRYwa8qgpAiXWgzVHg3K5B11KEbmJK15tb2MMjnrxTE3FA0iLXraIs0l6ZA35HdqwwQIBHAepn6QZCjB0nbhnZAZBcCvTjXVVrx3uugzZBfOgKJHAN0FHnUVu5LK2zGuvIxIZAon54YPFmcW9Tp5JI4ndiAY8tDv01ePoQVeRMZD" ) # graph = GraphAPI("access_token") try: print graph.get('me') except FacebookClientError: print "failed!! :("
def get_profile(): token = flockly.authpage.get_user_access_token(session['uid']) graph = GraphAPI(token) profile = graph.get('/me?fields=id,name,picture.type(large)&access_token=%s&' % (token)) return profile