def get_likes(request): if 'data' in request.POST: data = _parse_json(request.POST.get('data')) user, created = FBUser.objects.get_or_create(id=int(data.get('id', 0))) graph = get_graph(request) user.get_from_facebook(graph=graph, save=True) try: response = graph.request('me/likes') except facebook.GraphAPIError as e: return HttpResponse('no permission: %s' % e) likes = response['data'] for entry in likes: val = entry.get('created_time', None) if val: if '+' in val: # ignore timezone for now ... val = val[:-5] created_time = datetime.strptime(val, "%Y-%m-%dT%H:%M:%S") else: created_time = datetime.now() like, c = Like.objects.get_or_create(user=user, content_id=int( entry.get('id', 0))) like._name = entry.get('name', '') like._category = entry.get('category', '') like._id = entry.get('id', None) like._created_time = created_time like.save() return HttpResponse('thank you') return HttpResponse('no data: %s' % request.POST)
def get_likes(request): if 'data' in request.POST: data = _parse_json(request.POST.get('data')) user, created = FBUser.objects.get_or_create(id=int(data.get('id', 0 ))) graph = get_graph(request) user.get_from_facebook(graph=graph, save=True) try: response = graph.request('me/likes') except facebook.GraphAPIError as e: return HttpResponse('no permission: %s' % e) likes = response['data'] for entry in likes: val = entry.get('created_time', None) if val: if '+' in val: # ignore timezone for now ... val = val[:-5] created_time = datetime.strptime(val, "%Y-%m-%dT%H:%M:%S") else: created_time = datetime.now() like, c = Like.objects.get_or_create(user=user, content_id=int(entry.get('id',0))) like._name = entry.get('name', '') like._category = entry.get('category', '') like._id = entry.get('id', None ) like._created_time = created_time like.save() return HttpResponse('thank you') return HttpResponse('no data: %s' % request.POST)
def get_context(self, request, signed_request, *args, **kwargs): try: page_id = signed_request['page']['id'] except KeyError: page_id = None if page_id: page, created = FBPage.objects.get_or_create(id=int(page_id)) if created: graph = get_graph(request) page.get_from_facebook(graph, save=True) url = page._link self.context.update({'url' : url , 'page' : page_id }) return self.context
def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, app_name=None): fb_app = get_app_dict(app_name) try: graph = get_graph(request, app_name=app_name) except IOError: graph = None redirect_to = request.REQUEST.get(redirect_field_name, '') # Because we override the login, we should check for POST data, #to give priority to the django auth view if request.method == 'GET' and graph and graph.via not in ( 'application', ): # Light security check on redirect_to (lifted from django.contrib.auth.views) netloc = urlparse.urlparse(redirect_to)[1] if not redirect_to or netloc != request.get_host(): redirect_to = fb_app['REDIRECT-URL'] """ # TODO: Check only if the domain is in 'DOMAIN' or 'facebook.com' but without the protocol elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to): redirect_to = fb_app['REDIRECT-URL'] """ new_user = authenticate(graph=graph) logger.debug('new user: %s' % new_user) # Authentication might still fail -- new_user might be an # instance of AnonymousUser. if new_user and new_user.is_authenticated(): auth_login(request, new_user) if 'registration' in settings.INSTALLED_APPS: from registration import signals signals.user_registered.send(sender='facebook_login', user=new_user, request=request) return redirect(redirect_to) return auth_views.login(request, template_name, redirect_field_name, authentication_form)
def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, app_name=None): fb_app = get_app_dict(app_name) try: graph = get_graph(request, app_name=app_name) except IOError: graph = None redirect_to = request.REQUEST.get(redirect_field_name, '') # Because we override the login, we should check for POST data, #to give priority to the django auth view if request.method == 'GET' and graph and graph.via not in ('application',): # Light security check on redirect_to (lifted from django.contrib.auth.views) netloc = urlparse.urlparse(redirect_to)[1] if not redirect_to or netloc != request.get_host(): redirect_to = fb_app['REDIRECT-URL'] """ # TODO: Check only if the domain is in 'DOMAIN' or 'facebook.com' but without the protocol elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to): redirect_to = fb_app['REDIRECT-URL'] """ new_user = authenticate(graph=graph) logger.debug('new user: %s' %new_user) # Authentication might still fail -- new_user might be an # instance of AnonymousUser. if new_user and new_user.is_authenticated(): auth_login(request, new_user) if 'registration' in settings.INSTALLED_APPS: from registration import signals signals.user_registered.send(sender='facebook_login', user=new_user, request=request) return redirect(redirect_to) return auth_views.login(request, template_name, redirect_field_name, authentication_form)
def connect(request, redirect_field_name=REDIRECT_FIELD_NAME, app_name=None): """ Connects the Facebook Account to the current logged-in user. """ fb_app = get_app_dict(app_name) graph = get_graph(request, app_name=app_name) redirect_to = request.REQUEST.get(redirect_field_name, fb_app['REDIRECT-URL']) if request.user.is_authenticated(): try: me = graph.get_object("me") except facebook.GraphAPIError as e: return redirect('fb_login') # if the user has already a facebook connection, abort and show # error message if hasattr(request.user, 'user'): logger.debug('The logged in user is already connected.') # check if the django user and FB user match: if graph.user_id <> request.user.user.id: logger.debug( 'User %s already connected with Facebook account %s' % (request.user.get_full_name, request.user.user._name)) auth_views.logout(request, next_page=reverse('fb_app')) # Otherwise redirect return redirect(redirect_to) else: # The User has no Facebook account attached. Connect him. try: # if that facebook user already exists, abort and show error message fb_user = FacebookUser.objects.get(id=graph.user_id) except FacebookUser.DoesNotExist: fb_user = FacebookUser(id=graph.user_id) fb_user.get_from_facebook(graph=graph, save=True) else: if isinstance(fb_user.user, User): auth_views.logout(request, next_page=reverse('fb_login')) else: fb_user.user = request.user fb_user.save() finally: return redirect(redirect_to) else: # The user is not logged in # -> redirect to login page return redirect('fb_login')
def connect(request, redirect_field_name=REDIRECT_FIELD_NAME, app_name=None): """ Connects the Facebook Account to the current logged-in user. """ fb_app = get_app_dict(app_name) graph = get_graph(request, app_name=app_name) redirect_to = request.REQUEST.get(redirect_field_name, fb_app['REDIRECT-URL']) if request.user.is_authenticated(): try: me = graph.get_object("me") except facebook.GraphAPIError as e: return redirect('fb_login') # if the user has already a facebook connection, abort and show # error message if hasattr(request.user, 'user'): logger.debug('The logged in user is already connected.') # check if the django user and FB user match: if graph.user_id <> request.user.user.id: logger.debug('User %s already connected with Facebook account %s' % (request.user.get_full_name, request.user.user._name)) auth_views.logout(request, next_page=reverse('fb_app')) # Otherwise redirect return redirect(redirect_to) else: # The User has no Facebook account attached. Connect him. try: # if that facebook user already exists, abort and show error message fb_user = FacebookUser.objects.get(id=graph.user_id) except FacebookUser.DoesNotExist: fb_user = FacebookUser(id=graph.user_id) fb_user.get_from_facebook(graph=graph, save=True) else: if isinstance(fb_user.user, User): auth_views.logout(request, next_page=reverse('fb_login')) else: fb_user.user = request.user fb_user.save() finally: return redirect(redirect_to) else: # The user is not logged in # -> redirect to login page return redirect('fb_login')
def input(request, action): """ method to save a graph-object query, that is retrieved client side """ json = request.POST.get('json', None) graph = get_graph(request) if action == 'user': if json: user, created = User.objects.get_or_create(id=json['id']) user.access_token = graph.access_token user.save_from_facebook(json) else: user, created = User.objects.get_or_create(id=graph.user_id) user.get_from_facebook(request) user.access_token = graph.access_token user.save() return HttpResponse('ok') elif action == 'friends': if json == None: return HttpResponseBadRequest( 'Facebook Graph JSON response is required as "json" attribute') user, created = User.objects.get_or_create(id=graph.user_id) user.save_friends(json) return HttpResponse('ok') elif action == 'user-friends-once': user, created = User.objects.get_or_create(id=graph.user_id) if created or not user.access_token: user.get_friends(save=True, request=request) user.access_token = graph.access_token user.get_from_facebook(request) user.save() return HttpResponse('ok') return HttpResponseBadRequest('action %s not implemented' % action)
def get_from_facebook(self, graph=None, save=False): if self.access_token: graph = get_graph() graph.access_token = self.access_token super(Event, self).get_from_facebook(graph, save) if getattr(graph, 'access_token', None): params = urllib.urlencode( {'type': 'large', 'access_token': graph.access_token}) url = 'https://graph.facebook.com/%s/picture/?%s' % ( self.id, params) try: image = urllib2.urlopen(url).read() except urllib2.HTTPError as e: self.graph['image'] = e.__str__() self.save() return img_temp = NamedTemporaryFile(delete=True) img_temp.write(image) img_temp.flush() self.image.save('%s.jpg' % self.slug, File(img_temp))
def get_context(self, request, *args, **kwargs): upcoming = Event.objects.upcoming() graph = get_graph(request) # TODO: this: """ try: me = graph.user query = "SELECT eid, rsvp_status FROM event_member WHERE uid = %s" % me rsvp_events = get_FQL(query, graph.access_token) events = {} for e in rsvp_events: events.update({e['eid'].encode('utf-8'): e['rsvp_status'].encode('utf-8')}) self.context.update({ 'rsvp_events' : events }) logger.debug('rsvp_events: %s' %rsvp_events) except AttributeError: pass """ self.context.update({'events': upcoming, 'access_token': graph.access_token }) return self.context
def input(request, action): """ method to save a graph-object query, that is retrieved client side """ json = request.POST.get('json', None) graph = get_graph(request) if action == 'user': if json: user, created = User.objects.get_or_create(id=json['id']) user.access_token = graph.access_token user.save_from_facebook(json) else: user, created = User.objects.get_or_create(id=graph.user_id) user.get_from_facebook(request) user.access_token = graph.access_token user.save() return HttpResponse('ok') elif action == 'friends': if json == None: return HttpResponseBadRequest('Facebook Graph JSON response is required as "json" attribute') user, created = User.objects.get_or_create(id=graph.user_id) user.save_friends(json) return HttpResponse('ok') elif action == 'user-friends-once': user, created = User.objects.get_or_create(id=graph.user_id) if created or not user.access_token: user.get_friends(save=True, request=request) user.access_token = graph.access_token user.get_from_facebook(request) user.save() return HttpResponse('ok') return HttpResponseBadRequest('action %s not implemented' % action)
def get_from_facebook(self, graph=None, save=False): if self.access_token: graph = get_graph() graph.access_token = self.access_token super(Event, self).get_from_facebook(graph, save) if getattr(graph, 'access_token', None): params = urllib.urlencode({ 'type': 'large', 'access_token': graph.access_token }) url = 'https://graph.facebook.com/%s/picture/?%s' % (self.id, params) try: image = urllib2.urlopen(url).read() except urllib2.HTTPError as e: self.graph['image'] = e.__str__() self.save() return img_temp = NamedTemporaryFile(delete=True) img_temp.write(image) img_temp.flush() self.image.save('%s.jpg' % self.slug, File(img_temp))
def access_token(request): graph = get_graph(request) return mark_safe(graph.access_token)
def save_model(self, request, obj, form, change): graph = get_graph(request, app_name="fh-admin") obj.get_from_facebook(graph=graph, save=True)
def save_model(self, request, obj, form, change): graph = get_graph(request, app_name='fh-admin') obj.get_from_facebook(graph=graph, save=True)
def access_token(request, app_name=None): graph = get_graph(request, app_name=app_name) return mark_safe(graph.access_token)