def get_fb_profile(self, user_id: int) -> Dict[str, Any]: fb_user = self.get_fb_user_by_django_user_id(user_id) if fb_user is None: return None access_token = fb_user.access_token try: graph = GraphAPI(access_token) graph.extend_access_token(FACEBOOK_APP_ID, FACEBOOK_APP_SECRET) profile = graph.get_object('me', fields='id,name,email,verified') profile['image'] = graph.get_object('me/picture')['url'] profile['image_thumb'] = graph.get_object('me/picture')['url'] return profile except GraphAPIError as ex: str_ex = str(ex) if 'Session has expired' in str_ex: return { 'id': fb_user.facebook_id, 'name': fb_user.name, 'email': fb_user.email, 'access_token': fb_user.access_token, 'verified': fb_user.verified, 'image': '', 'image_thumb': '', 'expired': True }
class FacebookAdapter(AbstractAdapter): access_token = "" graph_api = None def __init__(self, params): if "access_token" in params: self.access_token = params["access_token"] self.graph_api = GraphAPI(self.access_token) else: raise LookupError("access_token key was not found in parameter dictionary") pass def getAuthorizedPerson(self): user_object = self.graph_api.get_object("me") return FacebookPerson(self.graph_api, user_object) def getPerson(self, person_id): user_object = self.graph_api.get_object(person_id) return FacebookPerson(self.graph_api, user_object) def getServiceName(self): return "Facebook Social Network" def getServiceDescription(self): pass def getServiceUrl(self): pass
def sync_facebook(name): #import ipdb; ipdb.set_trace(); try: form_data = json.loads(request.data) except: return response_msg('error', 'data not correct') try: graph = GraphAPI(form_data['access_token']) try: # #import ipdb; ipdb.set_trace(); email = graph.get_object('me', fields='email')['email'] pic = graph.get_object('me/picture', width='400', height='400')['url'] print pic if email != form_data['fb_email']: return response_msg('error', 'incorrect facebook email') except: return response_msg('error', 'data not complete') except: return response_msg('error', 'invalid access token') try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == name).update({ 'fb_email': email, 'pic': pic }).run(connection) cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == name).run(connection) except: return response_msg('error', 'Could not connect to db') return response_msg('success', 'OK', data=cursor.items[0])
def verify_data(access_token, verification_id): print('VERIFY {}', verification_id) VERIFICATION_ATTR = ['first_name', 'last_name', 'email', 'birthday'] graph = GraphAPI(access_token=access_token, version='2.11') fb_data = graph.get_object(id='me', fields='first_name,last_name,email,birthday') verification = Verification.query.filter_by(id=verification_id).first() result = {} for attr in VERIFICATION_ATTR: result[attr] = getattr(verification, attr) == fb_data[attr] verification.fb_result = json.dumps(result) verification.fb_data = json.dumps(fb_data) fb_picture = graph.get_object(id='me/picture', type='large') filename = '{}/fb_pic_{}.jpg'.format(UPLOAD_FOLDER, verification_id) with open(filename, 'wb') as f: f.write(fb_picture['data']) verification.fb_picture = filename db.session.add(verification) db.session.commit() return verification_id
def getcontents(): from re import search result = get_user_from_cookie(cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET) graph = GraphAPI(ACCESS_TOKEN) url = request.form['url'] info = search(r""" ((?<=facebook.com/)(?P<page_name>\w*))/posts/(?P<post_id>\d*$) """, url).groupdict() page_id = graph.get_object(id=info['page_name'], fields=['id'])['id'] full_id = "%s_%s" % (page_id, info['post_id']) print(full_id) post = graph.get_object(id=full_id, fields=['attachments']) #print(post['message']) data = post['attachments']['data'][0] if data['type'] != 'album': return False img_urls = [] for subdata in data['subattachments']['data']: if subdata['type'] == 'photo': img_urls.append(subdata['media']['image']['src']) else: return "Invalid type" print(img_urls) get_contents(img_urls).apply_async()
def sync_facebook(name): #import ipdb; ipdb.set_trace(); try: form_data = json.loads(request.data) except: return response_msg('error', 'data not correct') try: graph = GraphAPI(form_data['access_token']) try: # #import ipdb; ipdb.set_trace(); email = graph.get_object('me', fields='email')['email'] pic = graph.get_object('me/picture', width='400', height='400')['url'] print pic if email != form_data['fb_email']: return response_msg('error', 'incorrect facebook email') except: return response_msg('error', 'data not complete') except: return response_msg('error', 'invalid access token') try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == name ).update({'fb_email': email, 'pic': pic} ).run(connection) cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == name ).run(connection) except: return response_msg('error', 'Could not connect to db') return response_msg('success', 'OK', data=cursor.items[0])
def get_current_user(): """Set g.user to the currently logged in user. Called before each request, get_current_user sets the global g.user variable to the currently logged in user. A currently logged in user is determined by seeing if it exists in Flask's session dictionary. If it is the first time the user is logging into this application it will create the user and insert it into the database. If the user is not logged in, None will be set to g.user. """ # Set the user in the session dictionary as a global g.user and bail out # of this function early. if session.get('user'): g.user = session.get('user') return # Attempt to get the short term access token for the current user. result = get_user_from_cookie(cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET) # If there is no result, we assume the user is not logged in. if result: graph = GraphAPI(result['access_token']) profile = graph.get_object('me') if 'link' not in profile: # Check to see if this user is already in our database. profile['link'] = "" user = User(result['uid'], name=profile['name'], profile_url=profile['link'], access_token=result['access_token']) user = user.check_user() if not user: # Not an existing user so get info graph = GraphAPI(result['access_token']) profile = graph.get_object('me') if 'link' not in profile: profile['link'] = "" # Create the user and insert it into the database ' user = User(result['uid'], profile['name'], profile['link'], result['access_token']) user.create_user() elif user['access_token'] != result['access_token']: # If an existing user, update the access token user['access_token'] = result['access_token'] # Add the user to the current session session['user'] = dict(name=profile['name'], profile_url=profile['link'], id=result['uid'], access_token=result['access_token']) # Commit changes to the database and set the user as a global g.user g.user = session.get('user', None)
def facebook_callback(request): graph = GraphAPI() # Получаем Long Term Access Token if request.GET.get('code'): access_token = graph.get_access_token_from_code( request.GET.get('code'), host_url('autoposting-facebook-callback'), settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET) else: access_token = graph.get_app_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET) graph.access_token = access_token['access_token'] access_token_response = graph.extend_access_token( settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET) access_token = access_token_response['access_token'] access_token_expires_at = datetime.datetime.now() + datetime.timedelta( seconds=int(access_token_response.get('expires', 60 * 60 * 24 * 60))) # Получаем список access_token для каждой из групп, что у нас есть в настройках graph = GraphAPI(access_token=access_token) group_access_tokens = {} after = None while True: if after: objects = graph.get_object('me/accounts', limit=25, after=after) else: objects = graph.get_object('me/accounts', limit=25) for group in objects['data']: if group['category'] == 'Community': group_access_tokens[group['id']] = group['access_token'] if objects['paging'].get('next'): after = objects['paging']['cursors']['after'] else: break facebook_autoposting = FacebookAutoposting.objects.all() for fb_autoposting in facebook_autoposting: if not group_access_tokens.get(fb_autoposting.page_id): messages.error(request, 'Access Token for %s not found' % fb_autoposting) continue fb_autoposting.access_token = group_access_tokens.get( fb_autoposting.page_id) fb_autoposting.access_token_expires_at = access_token_expires_at fb_autoposting.save() return redirect( reverse('admin:autoposting_facebookautoposting_changelist'))
def enrich_via_facebook(user): # todo: only enrich if new user social_user = user.social_auth.filter(provider='facebook').first() if not social_user: return fb_api = GraphAPI(social_user.extra_data['access_token']) fb_uid = social_user.extra_data['id'] picture = fb_api.get_object('{}/picture?type=large'.format(fb_uid)) user.picture.save(name=None, content=ContentFile(picture['data']), save=False) avatar = fb_api.get_object('{}/picture?type=small'.format(fb_uid)) user.avatar.save(name=None, content=ContentFile(avatar['data']), save=False) user.save()
def get_fb_graph_api(): FACEBOOK_USER_TOKEN = os.getenv('FACEBOOK_USER_TOKEN') api = GraphAPI(FACEBOOK_USER_TOKEN) try: api.get_object('me') except GraphAPIError as e: print e print "Update and source your .secret file" sys.exit() return api
def get_fb_graph_api(): FACEBOOK_USER_TOKEN = os.getenv('FACEBOOK_USER_TOKEN') api = GraphAPI(FACEBOOK_USER_TOKEN) try: api.get_object('me') except GraphAPIError as e: print e print "Update and source your .secret file" sys.exit() return api
def magic(oauth, latlong, dist=1000, limit=5, verbose=False): g = GraphAPI(oauth) # search a bunch of stuff, until no more results # https://graph.facebook.com/search?type=location¢er=[lat],[long]&distance=[dist]&access_token=[oauth] search = [] params = {"type":"location", "center":latlong, "distance":dist, "access_token":oauth} while limit > 0: res = g.request("search", params) if len(res.keys()) == 0 or not res.get("paging"): break search += res["data"] params = dict(urlparse.parse_qsl(res["paging"]["next"].split("?")[1])) limit -= 1 if verbose == True: pp.pprint(search) # filter places = g.fql("SELECT name, location, type, page_id FROM page where page_id in (%s)" % string.join([i["place"]["id"] for i in search], ", ")) desired_place_types = ["RESTAURANT/CAFE", "BAR", "CLUB", "FOOD/BEVERAGES", "LOCAL BUSINESS"] limit = 1; filtered_places = {} for i in places: if i["type"].upper() in desired_place_types: name = i["name"] filtered_places[name] = i filtered_places[name]["data"] = [] page = g.get_object(str(i["page_id"]) + "/picture", width="600") if page.get("url"): filtered_places[name]["photo_url"] = page["url"] del i["name"] if verbose == True: pp.pprint(filtered_places) # sort by places for i in search: if i["place"]["name"] in filtered_places: filtered_places[i["place"]["name"]]["data"].append(i) del i["place"] # get fb picture urls if can if i["type"] == "photo": photo = g.get_object(i["id"]) if photo.get("images"): i["photo_url"] = photo["images"] if verbose == True: pp.pprint(filtered_places) return filtered_places
def test_token(): graph = GraphAPI(token) print("Testando token") try: graph.get_object('me', retry=2) print("Token válido") config_write() except: print("Erro:") print("Token inválido ou sem internet") Gtk.Statusbar.push(status, 0, 'Erro: Token inválido ou sem internet') global token_validity token_validity = 0
def process_response(self, request, response): result = None # Hoo! Active cookies, verify that user cookie isn't stale if request.COOKIES: try: result = get_user_from_cookie( cookies=request.COOKIES, app_id=settings.FB_APP_ID, app_secret=settings.FB_APP_SECRET ) except: pass # If there is no result, we assume the user is not logged in. if result: # Check to see if this user is already in our database. graph = GraphAPI(result['access_token']) profile = dict() user = User.objects.filter(id=result.get('uid')).first() if not user: # User doesn't exist in datastore so get info profile = graph.get_object('/me') # Create the user and insert it into the database user = User( id=str(profile.get('id')), name=profile.get('name'), profile_url=profile.get('link'), access_token=result.get('access_token') ) elif not user.has_valid_access_token(result.get('access_token')): # If an existing user, update the access token user.access_token = result.get('access_token') graph_query_result = graph.get_object('/me/picture') profile['link'] = graph_query_result['url'] if user.profile_url is not profile['link']: user.profile_url = profile['link'] user.active = True # Add the user to the current session request.session['user'] = dict( name=user.name, profile_url=user.profile_url, id=user.id, access_token=user.access_token, is_authenticated=user.is_authenticated() ) user.save() return response
def get(self, request, *args, **kwargs): # qs = Employee.objects.all() # form.fields['Paymode'].queryset = Account.objects.filter(Username=request.session["Username"]) # objects1 = graph.get_object("me", fields="accounts") # user = graph.get_object("me", fields="id,name") # print(user) # userid = user['id'] # graph = GraphAPI( \ access_token="EAAnaWYZCIV5oBAA7pmub8W8g6xnPptF5l6SC2UqVpdYyGmwEYSQOAXnc7xXSzwMAU4aZBXdmInfcczQXZAnutO9vaZBED41ZBso0XQZCQ8zgIRtmZCIcpggC3XlQjHR1oCQ9W67XStkpoGZAJlK6YNzRCVGfdllCg4e3Kv61rr7UhgZDZD") objects1 = graph.get_object("me", fields="accounts") user = graph.get_object("me", fields="id,name") print(user) print("pggg") userid = user['id'] context = {} dict = {} # context=0 for page in objects1['accounts']['data']: # print(page) page_access_token = page['access_token'] pageid = page['id'] pagename = page['name'] pagecategory = page['category'] api = pyfacebook.Api(app_id="2773352989611930", app_secret="a5ceb9b7b928c55fd1f7922dc3737a33", short_token=page_access_token) print(page_access_token, pageid, pagename, pagecategory) print(api.get_page_info(page_id=pageid, return_json=True)) print("aaa111") # q=pgdtl.objects.all() q = pgdtl.objects.filter(pageid=pageid).count() # print("Hi") # print("Active:", qs.isActive) if ((q == 0)): # def post(self, request, *args, **kwargs): qs1 = pgdtl.objects.create(pagename=pagename, pageid=pageid, pagecategory=pagecategory) qs1.save() print("aaaaaaaasave") qs = pgdtl.objects.all() context['viewpgdtl'] = qs return render(request, self.template_name, context)
def harvest_facebook_profile(self): harvest_profile_d = Deferred() logging.info('Facebook Service - Getting users Facebook Profile') graph = GraphAPI(self.facebook_access_token_long) profile = graph.get_object("me") timestamp = str(datetime.datetime.now().isoformat('T')).split(".")[0] uniq_id = "facebook_profile_for_me" object_to_insert = { "@id": uniq_id, "app_object": app_id, "timestamp": timestamp, "facebook_profile": profile } #now need to perform the asnc def insert_cb(re): logging.debug( "Facebook Service - Found Facebook Profile information, Added To INDX {0} profile items" .format(len(profile))) harvest_profile_d.callback(True) def insert_cb_fail(re): harvest_profile_d.callback(True) self.insert_object_to_indx(object_to_insert).addCallbacks( insert_cb, insert_cb_fail) return harvest_profile_d
class FaceBookAccount(OAuthAccount): """OAuth impl for FaceBook""" AUTH_URL = "https://graph.facebook.com/oauth/authorize" TOKEN_URL = "https://graph.facebook.com/oauth/access_token" def __init__(self, g): OAuthAccount.__init__( self, g, "1081088951917470", "ea23cb30c9fabf0a99901ee845161ae5", self.AUTH_URL, self.TOKEN_URL, ) self.graph = None def get_user(self): "Returns the user using the Graph API" if not self.accessToken(): return None if not self.graph: self.graph = GraphAPI((self.accessToken())) try: user = self.graph.get_object("me") return dict(first_name=user['first_name'], last_name=user['last_name'], username=user['id']) except GraphAPIError: self.session.token = None self.graph = None return None
def post(self, *args, **kwargs): try: graph = GraphAPI(access_token=self.request.data['access_token'], version=settings.FACEBOOK_APP_VERSION) graph_data = graph.get_object(id='me', fields='email,first_name,last_name') except GraphAPIError: raise ParseError(detail='Invalid Facebook access token') data = { **graph_data, 'password': get_user_model().objects.make_random_password() } user, created = get_user_model().objects.get_or_create( email=data['email']) signup_ser = SignUpSerializer(instance=user, data=data) signup_ser.is_valid(raise_exception=True) user = signup_ser.save(is_active=True) token_ser = JSONWebTokenSerializer(data={ 'email': data['email'], 'password': data['password'] }) token_ser.is_valid(raise_exception=True) HistoryRecord.objects.create_history_record( user, None, HISTORY_RECORD_USER_SIGNUP_FACEBOOK) return Response( {'token': token_ser.object.get('token')}, status=status.HTTP_201_CREATED if created else status.HTTP_200_OK)
def get_current_user(): if session.get('user'): g.user = session.get('user') return # Attempt to get the short term access token for the current user. result = get_user_from_cookie(cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET) if result: user = User.query.filter(User.id == result['uid']).first() if not user: graph = GraphAPI(result['access_token']) profile = graph.get_object('me') # Create the user and insert it into the database user = User(id=str(profile['id']), name=profile['name'], profile_url=profile['link'], access_token=result['access_token']) db.session.add(user) elif user.access_token != result['access_token']: user.access_token = result['access_token'] session['user'] = dict(name=user.name, profile_url=user.profile_url, id=user.id, access_token=user.access_token) db.session.commit() g.user = session.get('user', None)
def check_user_logged_in(): if session.get('user'): g.user = session.get('user') return result = get_user_from_cookie(cookies=request.cookies, app_id=app.config["FB_APP_ID"], app_secret=app.config["FB_APP_SECRET"]) if result: user = UserActions.find_by_id(result['uid']) if not user: graph = GraphAPI(result['access_token']) args = {'fields': 'birthday, name, email'} profile = graph.get_object('me', **args); UserActions.new_facebook_user(profile, result) elif user.access_token != result['access_token']: user.access_token = result['access_token'] user = UserActions.find_by_id(result['uid']) session['user'] = dict(name=user.name, profile_url=user.profile_url, id=user.id, access_token=user.access_token) db.session.commit() g.user = session.get('user', None)
def validate_fb_email(email, access_token): # check if user is has synced fb email try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['fb_email'] == email).run(connection) except: return response_msg('error', 'Could not connect to db') if len(cursor.items) == 0: return response_msg('error', 'facebook not synced or user not registered') # if user has already synced fb email # check whether access token and email is valid try: graph = GraphAPI(access_token) profile = graph.get_object('me', fields='email') fb_email = profile['email'] except GraphAPIError as e: return response_msg('error', e) except: return response_msg('error', 'Could not connect to facebook') if fb_email == email: return response_msg('success', 'OK') else: return response_msg('error', 'invalid fb details')
def list_fb_pages(): token = config("FB_PYTHON_ACCESSTOKEN", default=None) if token != None: graph = GraphAPI(token) groups = graph.get_object("me/groups") return groups return []
class FaceBookAccount(OAuthAccount): """OAuth impl for FaceBook""" AUTH_URL="https://graph.facebook.com/oauth/authorize" TOKEN_URL="https://graph.facebook.com/oauth/access_token" def __init__(self, g): OAuthAccount.__init__(self, g, "231547190343989", "05003c7c704ca6d524fbd84ac0a1dd46", self.AUTH_URL, self.TOKEN_URL, ) self.graph = None def get_user(self): "Returns the user using the Graph API" if not self.accessToken(): return None if not self.graph: self.graph = GraphAPI((self.accessToken())) try: user = self.graph.get_object("me") return dict(first_name = user['first_name'], last_name = user['last_name'], username = user['id']) except GraphAPIError: self.session.token = None self.graph = None return None
def index(name="index", *args, **kawrgs): if request.is_xhr: return "", 400 if g.user: # try: graph = GraphAPI(g.user['access_token']) args = {'fields': 'birthday, name, email'} facebook_friends = graph.get_object('me/friends', **args) user = UserActions.find_by_id(g.user['id']) for facebook_friend in facebook_friends['data']: friend = UserActions.new(facebook_friend) FriendRelationshipActions.create(user, friend) relations = FriendRelationshipActions.find_by_user(user) return render_template("index.html", app_id=app.config["FB_APP_ID"], user=user, relations=relations) # except Exception: # return redirect(url_for('logout')) return render_template("login.html", app_id=app.config["FB_APP_ID"])
def get_details_for_profile_from_user(self, requesting_user, **kwargs): ''' For the details, we need: 1. Cover pic 2. Profile pic 3. Location if available More details about usage from core.models ''' access_token = self.social_auth.get( provider="facebook").extra_data.get("access_token") graph = GraphAPI(access_token) details_dict = {} try: info = graph.get_object("me", fields="picture, cover, location") details_dict['picture'] = info.get('picture', {}).get('data', {}).get('url', None) details_dict['cover'] = info.get('cover', {}).get('source', None) details_dict['location'] = info.get('location', {}).get('name', None) return details_dict except: logger.error( "accounts.models.BanyanUser:get_details_for_profile_from_user {}{} access_token:{}" .format(sys.exc_info()[0], sys.exc_info()[1], access_token)) return []
def check_user_logged_in(): if session.get('user'): g.user = session.get('user') return result = get_user_from_cookie(cookies=request.cookies, app_id=app.config["FB_APP_ID"], app_secret=app.config["FB_APP_SECRET"]) if result: user = UserActions.find_by_id(result['uid']) if not user: graph = GraphAPI(result['access_token']) args = {'fields': 'birthday, name, email'} profile = graph.get_object('me', **args) UserActions.new_facebook_user(profile, result) elif user.access_token != result['access_token']: user.access_token = result['access_token'] user = UserActions.find_by_id(result['uid']) session['user'] = dict(name=user.name, profile_url=user.profile_url, id=user.id, access_token=user.access_token) db.session.commit() g.user = session.get('user', None)
def fix_facebook_ids(): """ Retroactively adds Facebook IDs to Facebook table """ db = dataset.connect(app_config.POSTGRES_URL) table = db['facebook'] min_created_time_result = list(db.query('select min(created_time) as min_created_time from facebook')) min_created_time = min_created_time_result[0]['min_created_time'] graph = GraphAPI(SECRETS['FACEBOOK_TOKEN']) profile = graph.get_object(FACEBOOK_USER) posts = graph.get_connections(profile['id'], 'posts') done = False while not done: print 'processing batch of 25' for post in posts['data']: created_time = parser.parse(post['created_time'], ignoretz=True) if created_time < min_created_time: done = True break if 'link' not in post.keys(): print 'skipping %s (no link)' % post['id'] continue link = post['link'].split('?')[0] print 'updating %s (%s)' % (link, post['id']) table.update({ 'facebook_id': post['id'], 'link_url': link, }, ['link_url']) posts = requests.get(posts['paging']['next']).json()
def validate_fb_email(email, access_token): # check if user is has synced fb email try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['fb_email'] == email ).run(connection) except: return response_msg('error', 'Could not connect to db') if len(cursor.items) == 0: return response_msg('error', 'facebook not synced or user not registered') # if user has already synced fb email # check whether access token and email is valid try: graph = GraphAPI(access_token) profile = graph.get_object('me', fields='email') fb_email = profile['email'] except GraphAPIError as e: return response_msg('error', e) except: return response_msg('error', 'Could not connect to facebook') if fb_email == email: return response_msg('success', 'OK') else: return response_msg('error', 'invalid fb details')
def hello(): access_token = 'access_token_here' graph = GraphAPI(access_token) friends = graph.get_object('me/friends') friendsList = [] me_picture = graph.get_object('me/picture')['url'] me_name = graph.get_object('me')['name'] for friend in friends['data']: friend_picture = graph.get_object(friend['id']+'/picture')['url'] friendsList.append({'name': friend['name'], 'id': friend['id'], 'profile_thumbnail': friend_picture}) return render_template('choose_friends.html', me_name=me_name, me_picture=me_picture, friendsList=friendsList)
def login(request): ret = None if request.method == 'POST': form = FacebookConnectForm(request.POST) if form.is_valid(): token = form.cleaned_data['access_token'] g = GraphAPI(token) data = g.get_object("me") email = valid_email_or_none(data.get('email')) social_id = data['id'] try: account = FacebookAccount.objects.get(social_id=social_id) except FacebookAccount.DoesNotExist: account = FacebookAccount(social_id=social_id) account.link = data['link'] account.name = data['name'] #adding the storing of users accesstoken account.access_token = token if account.pk: account.save() data = dict(email=email,facebook_me=data) ret = complete_social_login(request, data, account) if not ret: ret = render_authentication_error(request) return ret
def get_current_user(): if not session.get('user'): result = get_user_from_cookie(cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET) if result: graph = GraphAPI(result['access_token']) profile = graph.get_object('me', fields='link,name,id') access_token = graph.extend_access_token( FB_APP_ID, FB_APP_SECRET)['access_token'] user = User.get_by_id(result['uid']) if not user: user = User.create(id=profile['id'], name=profile['name'], profile_url=profile['link'], access_token=access_token) clear_friends_cache(user) user.add_default_tag() g.new_user = True else: user.access_token = access_token user.update() session['user'] = user.id g.uid = session.get('user') g.user = User.get_by_id(g.uid) if g.uid else None if not g.user: session['user'] = ''
class FaceBookAccount(OAuthAccount): """ OAuth impl for Facebook""" AUTH_URL="https://graph.facebook.com/oauth/authorize" TOKEN_URL="https://graph.facebook.com/oauth/access_token" def __init__(self,g): OAuthAccount.__init__(self,g,CLIENT_ID,CLIENT_SECRET,self.AUTH_URL,self.TOKEN_URL, scope='public_profile,email') self.graph=None def get_user(self): ''' Returns the user using the Graph api''' if not self.accessToken(): return None if not self.graph: self.graph=GraphAPI((self.accessToken())) user=None try: args = {'fields' : 'id,first_name,last_name,email' } user=self.graph.get_object("me",**args) except GraphAPIError, e: self.session.token=None self.graph =None if user: print user return dict(first_name=user['first_name'], last_name=user['last_name'], username=user['id'],email=user['email'],password='******')
class FaceBookAccount(OAuthAccount): """OAuth impl for FaceBook""" AUTH_URL = "https://graph.facebook.com/oauth/authorize" TOKEN_URL = "https://graph.facebook.com/oauth/access_token" def __init__(self, g, db): OAuthAccount.__init__( self, g, CLIENT_ID, CLIENT_SECRET, self.AUTH_URL, self.TOKEN_URL, scope='publish_actions, publish_stream, user_likes') self.graph = None self.db = db def get_user(self): '''Returns the user using the Graph API. ''' db = self.db if not self.accessToken(): return None if not self.graph: self.graph = GraphAPI((self.accessToken())) user = None try: user = self.graph.get_object("me") except GraphAPIError, e: self.session.token = None self.graph = None if user: return dict(first_name=user['first_name'], last_name=user['last_name'], username=user['id'])
def room(request, name, slug): """ Show a room. """ if request.user.username == name: c = {} c.update(csrf(request)) context = {"room": get_object_or_404(Call, slug=slug)} #print request.user #template="space/room.html" owner=request.user try: owner.token = UserSocialAuth.objects.get(user__username=owner.username, provider='facebook').extra_data['access_token'] owner.uid = UserSocialAuth.objects.get(user__username=owner.username, provider='facebook').uid graph = GraphAPI(owner.token) friends = graph.get_connections(owner.uid, "friends", fields="installed,id,name")['data'] me = graph.get_object("me") except: uid = '' token = '' friends = '' me = '' return render_to_response('space/room.html',context, RequestContext(request,{'owner': owner, 'me': me})) #return render(request, template, context) else: raise Http404
def getFBPosts(station,function): """ Gets the most recent posts from a Facebook page since the last run :param station: (int) id of the station :param function: (int) id of the function :return: """ ##Gets the url after the bot has been added url = StationhasBots.query.filter(StationhasBots.fk_radio_station_id==station,StationhasBots.fk_bot_function_id==function).first() # Gets an access token to allow us to fetch information from FB pages r = requests.get('https://graph.facebook.com/oauth/access_token?client_id='+FB_APP_ID+'&client_secret='+FB_APP_SECRET+'&grant_type=client_credentials') access_token = r.text[13:] graph = GraphAPI(access_token) linkCut(url.source_url) profile = graph.get_object(linkCut(url.source_url)) # Gets the last info that was introduced into the database last_bot_info = Bothasinfo.query.filter(Bothasinfo.fk_station_has_bots_radio_station_id == station, Bothasinfo.fk_station_has_bots_bot_function_id == function).order_by(Bothasinfo.created_at.desc()).first() if last_bot_info == None: last_info_date = datetime.now() - timedelta(days=7) else: last_info_date = last_bot_info.created_at posts = graph.get_connections(profile['id'], 'posts') for post in posts['data']: # This condition grants that we only get info from posts if 'message' in post: if datetime.strptime(post['created_time'], "%Y-%m-%dT%H:%M:%S+%f") > last_info_date: info = validate_sms(post['message']) new_info = Bothasinfo(created_at = post['created_time'], fk_station_has_bots_radio_station_id = station , fk_station_has_bots_bot_function_id = function, info = info) db.session.add(new_info) db.session.commit()
def get(self): import facebookoauth from facebookoauth import FBUser import pprint, StringIO co2=100 aaa="" pg=self.request.get('pg') if pg: pg = int(pg) else: pg=0 hout = "" prid=self.request.get('id') args = dict(grant_type="client_credentials", client_id=FACEBOOK_APP_ID, client_secret=FACEBOOK_APP_SECRET) response = cgi.parse_qs(urllib.urlopen("https://graph.facebook.com/oauth/access_token?" +urllib.urlencode(args)).read()) access_token = response["access_token"][-1] #print access_token errorjson = False profile = {'id': 0} try: graph = GraphAPI(access_token) profile = graph.get_object(prid) except Exception, e: errorjson = True errtext = cgi.escape(str(sys.exc_info()[0])) + ' ' + cgi.escape(str(sys.exc_info()[1])) + ' ' + cgi.escape(str(sys.exc_info()[2]))
def get_url_info(url): ''' Capture opengraph data from links. It tries to get everything from Facebook. TO DO: Have a default image when no image is found ''' token = settings.FACEBOOK_TOKEN fb_graph = GraphAPI(access_token=token, version='2.10') fb_info = fb_graph.get_object( id=quote(url), fields=['engagement,og_object{image,description,title,updated_time}']) if fb_info: try: return dict(thumbnail=fb_info['og_object']['image'][0]['url'], facebook_shares=fb_info['engagement']['share_count'], title=fb_info['og_object']['title'], description=fb_info['og_object']['description'], source=url.split('/')[2]) except KeyError: from webpreview import web_preview metadata = web_preview(url) return dict(thumbnail=metadata[2], facebook_shares=fb_info['engagement']['share_count'], title=metadata[0], description=metadata[1], source=url.split('/')[2]) else: return dict(thumbnail='', facebook_shares=0, title='', description='', source=url.split('/')[2])
def login(request): ret = None if request.method == 'POST': form = FacebookConnectForm(request.POST) if form.is_valid(): try: token = form.cleaned_data['access_token'] g = GraphAPI(token) facebook_me = g.get_object("me") email = valid_email_or_none(facebook_me.get('email')) social_id = facebook_me['id'] try: account = FacebookAccount.objects.get(social_id=social_id) except FacebookAccount.DoesNotExist: account = FacebookAccount(social_id=social_id) data = dict(email=email, facebook_access_token=token, facebook_me=facebook_me) # some facebook accounts don't have this data data.update((k,v) for (k,v) in facebook_me.items() if k in ['username', 'first_name', 'last_name']) # Don't save partial/temporary accounts that haven't # gone through the full signup yet, as there is no # User attached yet. if account.pk: account.sync(data) ret = complete_social_login(request, data, account) except (GraphAPIError, IOError): pass if not ret: ret = render_authentication_error(request) return ret
class FaceBookAccount(OAuthAccount): """OAuth impl for FaceBook""" AUTH_URL="https://graph.facebook.com/oauth/authorize" TOKEN_URL="https://graph.facebook.com/oauth/access_token" def __init__(self, g): OAuthAccount.__init__(self, g, CLIENT_ID, CLIENT_SECRET, self.AUTH_URL, self.TOKEN_URL, scope='user_photos,friends_photos') self.graph = None def get_user(self): '''Returns the user using the Graph API.''' if not self.accessToken(): return None if not self.graph: self.graph = GraphAPI((self.accessToken())) user = None try: user = self.graph.get_object("me") except GraphAPIError, e: self.session.token = None self.graph = None if user: return dict(first_name = user['first_name'], last_name = user['last_name'], username = user['id'])
def login(request): ret = None if request.method == 'POST': form = FacebookConnectForm(request.POST) if form.is_valid(): token = form.cleaned_data['access_token'] g = GraphAPI(token) facebook_me = g.get_object("me") email = valid_email_or_none(facebook_me.get('email')) social_id = facebook_me['id'] try: account = FacebookAccount.objects.get(social_id=social_id) except FacebookAccount.DoesNotExist: account = FacebookAccount(social_id=social_id) account.link = facebook_me['link'] account.name = facebook_me['name'] if account.pk: account.save() data = dict(email=email, facebook_me=facebook_me) # some facebook accounts don't have this data data.update((k, v) for (k, v) in facebook_me.items() if k in ['username', 'first_name', 'last_name']) ret = complete_social_login(request, data, account) if not ret: ret = render_authentication_error(request) return ret
def login(request): ret = None if request.method == 'POST': form = FacebookConnectForm(request.POST) if form.is_valid(): try: token = form.cleaned_data['access_token'] g = GraphAPI(token) facebook_me = g.get_object("me") email = valid_email_or_none(facebook_me.get('email')) social_id = facebook_me['id'] try: account = FacebookAccount.objects.get(social_id=social_id) except FacebookAccount.DoesNotExist: account = FacebookAccount(social_id=social_id) data = dict(email=email, facebook_access_token=token, facebook_me=facebook_me) # some facebook accounts don't have this data data.update((k, v) for (k, v) in facebook_me.items() if k in ['username', 'first_name', 'last_name']) # Don't save partial/temporary accounts that haven't # gone through the full signup yet, as there is no # User attached yet. if account.pk: account.sync(data) ret = complete_social_login(request, data, account) except (GraphAPIError, IOError): pass if not ret: ret = render_authentication_error(request) return ret
def login(request): ret = None if request.method == 'POST': form = FacebookConnectForm(request.POST) if form.is_valid(): token = form.cleaned_data['access_token'] g = GraphAPI(token) facebook_me = g.get_object("me") email = valid_email_or_none(facebook_me.get('email')) social_id = facebook_me['id'] try: account = FacebookAccount.objects.get(social_id=social_id) except FacebookAccount.DoesNotExist: account = FacebookAccount(social_id=social_id) account.link = facebook_me['link'] account.name = facebook_me['name'] if account.pk: account.save() data = dict(email=email, facebook_me=facebook_me) # some facebook accounts don't have this data data.update((k,v) for (k,v) in facebook_me.items() if k in ['username', 'first_name', 'last_name']) ret = complete_social_login(request, data, account) if not ret: ret = render_authentication_error(request) return ret
def on_authenticate_facebook(self, response): try: access_token, expires_in = \ response['accessToken'], response['expiresIn'] signed_request = parse_signed_request( response['signedRequest'], app.config['FACEBOOK_SECRET'], expires_in ) if not signed_request: return None, None graph = GraphAPI(access_token) profile = graph.get_object('me') user = User.get_by_facebook(profile['id']) if not user or user.status == User.NOT_REGISTERED_YET: if not user: user = User() user.facebook_account = FacebookAccount() user.email = profile['email'] user.facebook_account.name = user.nickname = profile['name'] user.facebook_account.uid = profile['id'] user.status = User.NORMAL db.session.add(user) db.session.commit() self.online_users[self] = self.session['user_id'] = user.id self.facebook_access_token = access_token, signed_request['expires_at'] return None, user.to_json() except GraphAPIError, e: return {'_type': 'GraphAPIError', 'msg': str(GraphAPIError)},
def get_current_user(): if session.get('user'): g.user = session.get('user') return result = get_user_from_cookie(cookies=request.cookies, app_id=APP_ID, app_secret=SECRET_KEY) if result: user = User.query.filter(User.id == result['uid']).first() if not user: graph = GraphAPI(result['access_token']) profile = graph.get_object('me?fields=email,first_name,last_name,name,link,id,gender') user = User(id=str(profile['id']), name=profile['name'], first_name=profile['first_name'], last_name=profile['last_name'], email=profile['email'], gender=profile['gender'], link=profile['link'], access_token=result['access_token']) db.session.add(user) elif user.access_token != result['access_token']: user.access_token = result['access_token'] session['user'] = dict(id=user.id, name=user.name, access_token=user.access_token) db.session.commit() g.user = session.get('user', None)
class FaceBookAccount(OAuthAccount): AUTH_URL="https://graph.facebook.com/oauth/authorize" TOKEN_URL="https://graph.facebook.com/oauth/access_token" def __init__(self): OAuthAccount.__init__(self, client_id=CLIENT_ID, client_secret=CLIENT_SECRET, auth_url=self.AUTH_URL, token_url=self.TOKEN_URL, scope='user_photos,friends_photos') self.graph = None def get_user(self): if not self.accessToken(): return None if not self.graph: self.graph = GraphAPI((self.accessToken())) user = None try: user = self.graph.get_object("me") except GraphAPIError, e: self.session.token = None self.graph = None if user: return dict(first_name = user['first_name'], last_name = user['last_name'], username = user['id'])
def signin(): uid = request.args.get('uid', '') print("uid =", uid) query = {'id': uid} user = db.users.find_one(query) print(user) if not user: # Not an existing user so get info requestAccessToken = request.args.get('access_token', '') print("token=", requestAccessToken) graph = GraphAPI(requestAccessToken) profile = graph.get_object('me') if 'link' not in profile: profile['link'] = "" print(profile) # Create the user and insert it into the database db.users.insert({ 'id': uid, 'profile_url': profile['link'], 'created_time': datetime.utcnow, 'name': profile['name'], 'access_token': requestAccessToken }) elif user.access_token != requestAccessToken: # If an existing user, update the access token user.access_token = requestAccessToken response = jsonify({user}) response.status_code = 200 return response
def load_facebook_events(nodes, token=os.environ.get('FACEBOOK_TOKEN')): """ Load events from Facebook pages to the events file. ..important: In order for this function to work, you need to to provide a valid Facebook Graph API token. You can get yours easily on https://developers.facebook.com/tools/explorer :param nodes: Facebook nodes to load public events from. :param token: Facebook Graph API token. """ graph = GraphAPI(access_token=token) with open('data/events.yml', 'r') as events_file: existing_events = yaml.load(events_file) # Get facebook metadata on existing entries facebook_ids = {entry.get('facebook_id') for entry in existing_events} fetched_events = [] for node in nodes: event_node = "{}/events".format(node) # XXX: Ideally we would follow subrequests, but a large limit # should work as a simple solution. node_events = graph.get_object(event_node, limit=1000) for event in node_events['data']: # If event already exists, just ignore if event['id'] in facebook_ids: continue # We need to reshape datetimes to events format format_date = datetime.strptime(event['start_time'], '%Y-%m-%dT%H:%M:%S%z') fetched_events.append({ 'name': event['name'], 'url': 'https://facebook.com/{}'.format(event['id']), 'local': event.get('place', {}).get('name', ''), 'date': format_date.strftime('%d-%m-%Y'), 'facebook_id': str(event['id']) }) # Pretty print new entries on the events file with open('data/events.yml', 'a') as events_file: for entry in fetched_events: events_file.write('\n') yaml.dump([entry], events_file, default_flow_style=False, allow_unicode=True)
def get_current_user(): if not session.get('user'): result = get_user_from_cookie(cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET) if result: graph = GraphAPI(result['access_token']) profile = graph.get_object('me', fields='link,name,id') access_token = graph.extend_access_token(FB_APP_ID, FB_APP_SECRET)['access_token'] user = User.get_by_id(result['uid']) if not user: user = User.create(id=profile['id'], name=profile['name'], profile_url=profile['link'], access_token=access_token) clear_friends_cache(user) user.add_default_tag() g.new_user = True else: user.access_token = access_token user.update() session['user'] = user.id g.uid = session.get('user') g.user = User.get_by_id(g.uid) if g.uid else None if not g.user: session['user'] = ''
def id2page(iden): token = g.user['access_token'] graph = GraphAPI(token) pages = graph.get_object('me/accounts') for page in pages['data']: if iden == page['id']: return page
def signup(request): if request.method == "POST": data = json.loads(request.body) try: if data['type'] == 'facebook': try: access_token = request.META['HTTP_FB_ACCESS_TOKEN'] fb_id = data['fb_id'] g_id = -1 try: graph = GraphAPI(access_token) profile = graph.get_object('me', fields='email') fb_graph_id = profile['id'] except GraphAPIError as e: return response('error', e) if fb_id != fb_graph_id: return response("error", "facebook auth failed", ("error_type", "fb_error")) return check_and_add_user(data,fb_id,g_id) except: return response("error", "Incomplete data sent", ("error_type","Incomplete_data")) elif data['type'] == 'google': pass else: return response("error", "Invalid signup type") except: return response("error", "Invalid signup type") else: return response("error", "Not a post request")
def process_response(self, request, response): result = None # Hoo! Active cookies, verify that user cookie isn't stale if request.COOKIES: try: result = get_user_from_cookie( cookies=request.COOKIES, app_id=settings.FB_APP_ID, app_secret=settings.FB_APP_SECRET) except: pass # If there is no result, we assume the user is not logged in. if result: # Check to see if this user is already in our database. graph = GraphAPI(result['access_token']) profile = dict() user = User.objects.filter(id=result.get('uid')).first() if not user: # User doesn't exist in datastore so get info profile = graph.get_object('/me') # Create the user and insert it into the database user = User(id=str(profile.get('id')), name=profile.get('name'), profile_url=profile.get('link'), access_token=result.get('access_token')) elif not user.has_valid_access_token(result.get('access_token')): # If an existing user, update the access token user.access_token = result.get('access_token') graph_query_result = graph.get_object('/me/picture') profile['link'] = graph_query_result['url'] if user.profile_url is not profile['link']: user.profile_url = profile['link'] user.active = True # Add the user to the current session request.session['user'] = dict( name=user.name, profile_url=user.profile_url, id=user.id, access_token=user.access_token, is_authenticated=user.is_authenticated()) user.save() return response
def get_current_user(): """Set g.user to the currently logged in user. Called before each request, get_current_user sets the global g.user variable to the currently logged in user. A currently logged in user is determined by seeing if it exists in Flask's session dictionary. If it is the first time the user is logging into this application it will create the user and insert it into the database. If the user is not logged in, None will be set to g.user. """ # Set the user in the session dictionary as a global g.user and bail out # of this function early. if session.get("user"): g.user = session.get("user") return # Attempt to get the short term access token for the current user. result = get_user_from_cookie(cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET) # If there is no result, we assume the user is not logged in. if result: # Check to see if this user is already in our database. user = User.query.filter(User.id == result["uid"]).first() if not user: # Not an existing user so get info graph = GraphAPI(result["access_token"]) profile = graph.get_object("me") if "link" not in profile: profile["link"] = "" # Create the user and insert it into the database user = User( id=str(profile["id"]), name=profile["name"], profile_url=profile["link"], access_token=result["access_token"], ) db.session.add(user) elif user.access_token != result["access_token"]: # If an existing user, update the access token user.access_token = result["access_token"] # Add the user to the current session session["user"] = dict( name=user.name, profile_url=user.profile_url, id=user.id, access_token=user.access_token, ) # Commit changes to the database and set the user as a global g.user db.session.commit() g.user = session.get("user", None)
def get_current_user(): """Set g.user to the currently logged in user. Called before each request, get_current_user sets the global g.user variable to the currently logged in user. A currently logged in user is determined by seeing if it exists in Flask's session dictionary. If it is the first time the user is logging into this application it will create the user and insert it into the database. If the user is not logged in, None will be set to g.user. """ # Set the user in the session dictionary as a global g.user and bail out # of this function early. if session.get("user"): g.user = session.get("user") return # Attempt to get the short term access token for the current user. result = get_user_from_cookie( cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET ) # If there is no result, we assume the user is not logged in. if result: # Check to see if this user is already in our database. user = User.query.filter(User.id == result["uid"]).first() if not user: # Not an existing user so get info graph = GraphAPI(result["access_token"]) profile = graph.get_object("me") if "link" not in profile: profile["link"] = "" # Create the user and insert it into the database user = User( id=str(profile["id"]), name=profile["name"], profile_url=profile["link"], access_token=result["access_token"], ) db.session.add(user) elif user.access_token != result["access_token"]: # If an existing user, update the access token user.access_token = result["access_token"] # Add the user to the current session session["user"] = dict( name=user.name, profile_url=user.profile_url, id=user.id, access_token=user.access_token, ) # Commit changes to the database and set the user as a global g.user db.session.commit() g.user = session.get("user", None)
def get_current_user(): """Set g.user to the currently logged in user. Called before each request, get_current_user sets the global g.user variable to the currently logged in user. A currently logged in user is determined by seeing if it exists in Flask's session dictionary. If it is the first time the user is logging into this application it will create the user and insert it into the database. If the user is not logged in, None will be set to g.user. """ # Set the user in the session dictionary as a global g.user and bail out # of this function early. if session.get('user', False): app.logger.debug('session.get(\'user\') returns true') g.user = session.get('user') return # Attempt to get the short term access token for the current user. result = get_user_from_cookie(cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET) # If there is no result, we assume the user is not logged in. if result: app.logger.debug('get_user_from_cookie returns true') # Check to see if this user is already in our database. user = User.query.filter(User.id == result['uid']).first() if not user: # Not an existing user so get info graph = GraphAPI(result['access_token']) profile = graph.get_object(id='me', fields='id,name,email,link') if 'link' not in profile: profile['link'] = "" if 'email' not in profile: profile['email'] = "" # Create the user and insert it into the database user = User(id=str(profile['id']), name=profile['name'], email=profile['email'], profile_url=profile['link'], access_token=result['access_token']) db.session.add(user) elif user.access_token != result['access_token']: # If an existing user, update the access token user.access_token = result['access_token'] # Add the user to the current session session['user'] = dict(name=user.name, profile_url=user.profile_url, id=user.id, access_token=user.access_token) # Log in user using flask-login app.logger.debug('Logging in user: '******'user', None)
def post_to_fb(): if current_user.fb_token: current_app.logger.debug('User {} already has token: {}'.format( current_user.username, current_user.fb_token)) user_graph = GraphAPI(current_user.fb_token, version='2.11') elif request.args.get('code'): current_app.logger.debug('Fetching Facebook token for user {}'.format( current_user.username)) current_app.logger.debug(request.args) result = get_user_from_cookie( cookies=request.cookies, app_id=current_app.config['FB_APP_ID'], app_secret=current_app.config['FB_APP_SECRET']) if result: user_graph = GraphAPI(result['access_token']) else: flash( "Ekki tókst að senda póst á Facebook! Ertu búinn að logga þig inn?" ) return redirect(url_for('admin.news_index')) else: current_app.logger.error( "Not able to send post to Facebook for user {}".format( current_user.username)) current_app.logger.error(request.args) flash("Ekki tókst að senda póst á Facebook!") return redirect(url_for('admin.news_index')) accounts = user_graph.get_object('me/accounts') for d in accounts['data']: if d['id'] == current_app.config['FB_PAGE_ID']: page_access_token = d['access_token'] break else: current_app.logger.error('Not able to find the page_access_token') current_app.logger.error(accounts) current_app.logger.error(current_app.config['FB_PAGE_ID']) flash("Ekki tókst að senda póst á Facebook!") return redirect(url_for('admin.news_index')) lnk = session.pop('link', None) msg = session.pop('body', None) page_graph = GraphAPI(page_access_token, version='2.11') page_graph.put_object(parent_object=current_app.config['FB_PAGE_ID'], connection_name='feed', message=msg, link=lnk) return redirect(url_for('admin.news_index'))
def get_current_user(): """Set g.user to the currently logged in user. Called before each request, get_current_user sets the global g.user variable to the currently logged in user. A currently logged in user is determined by seeing if it exists in Flask's session dictionary. If it is the first time the user is logging into this application it will create the user and insert it into the database. If the user is not logged in, None will be set to g.user. """ # A/B test value g.ab = _ab() # Set the user in the session dictionary as a global g.user and bail out # of this function early. if session.get('user'): user = session.get('user') user = User.query.filter(User.id == user['id']).first() g.user = user return # Attempt to get the short term access token for the current user. result = get_user_from_cookie(cookies=request.cookies, app_id=app.config['FB_APP_ID'], app_secret=app.config['FB_SECRET']) # If there is no result, we assume the user is not logged in. if result: # Check to see if this user is already in our database. user = User.query.filter(User.id == result['uid']).first() if not user: # Not an existing user so get info graph = GraphAPI(result['access_token']) profile = graph.get_object('me') # Create the user and insert it into the database user = User(id=str(profile['id']), name=profile['name'], profile_url=profile['link'], access_token=result['access_token']) db.session.add(user) elif user.access_token != result['access_token']: # If an existing user, update the access token user.access_token = result['access_token'] # Add the user to the current session session['user'] = dict(name=user.name, profile_url=user.profile_url, id=user.id, access_token=user.access_token, admin=user.admin) # Commit changes to the database and set the user as a global g.user db.session.commit() g.user = session.get('user', None) else: g.user = None
def get_from_fb_token(token): graph = GraphAPI(token) profile = graph.get_object('me') user_id = FBUserMapping.find(profile['id']).get('user_id') if user_id: user = User.find(user_id) if user and user.get('password'): del user['password'] return user