Example #1
0
    def current_user(self):
        logging.info('########### BaseHandler:: current_user ###########')

        cookie = facebook.get_user_from_cookie(
            self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET
        )
        #Sam - checking to see if we have a FB cookie
        # If the user is logged out of FB - set the _current_user to None
        if not cookie:
            self._current_user = None
            
        if not hasattr(self, "_current_user"):
            self._current_user = None
            cookie = facebook.get_user_from_cookie(
                self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
            if cookie:
                # Store a local instance of the user data so we don't need
                # a round-trip to Facebook on every request
                user = models.User.get_by_key_name(cookie["uid"])
                if not user: # Build a User
                    logging.info("Building a user")
                    user = getUser(
                            facebook.GraphAPI(cookie["access_token"]),
                            cookie)
                    logging.info("User built: " + user.name)
                elif user.access_token != cookie["access_token"]:
                    user.access_token = cookie["access_token"]
                    user.put()
                self._current_user = user
        return self._current_user
Example #2
0
def login_view(request):
  if request.method == 'POST':
    userprofile = UserProfile.objects.filter(fb_id = request.POST['fb_user_id'])
    if not userprofile:
      fbuser = facebook.get_user_from_cookie(request.COOKIES, settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET)
      if fbuser: # fb user logged in and exists
        graph = facebook.GraphAPI(fbuser["access_token"])
        fbprofile = graph.get_object("me")
        fbfriends = graph.get_connections("me", "friends")

        # log user into site
        hashed_password = hashlib.sha1(settings.HASH_PHRASE + request.POST['fb_user_id']).hexdigest()
        fname = fbprofile['first_name']
        lname = fbprofile['last_name']
        username = '******'.join([fname,lname,request.POST['fb_user_id']])
        user = User.objects.create_user(username=username, email=fbprofile['email'], password = hashed_password)
        userprofile = UserProfile(fb_id = fbprofile['id'], user=user, fb_token=fbuser["access_token"],first_name=fbprofile['first_name'],
            last_name=fbprofile['last_name'],gender = fbprofile['gender'],
            birthyear = datetime.datetime.strptime(fbprofile['birthday'],'%m/%d/%Y').year)
        userprofile.save()
        enterSchoolUser(fbprofile["education"],userprofile)
        enterFriends(fbfriends,userprofile)

        new_user = authenticate(username=username,password=hashed_password)
        login(request, new_user) 
        
        # redirect to check instagram id
        RedirectURI = 'http://'+request.get_host()+reverse('Instagram:redirect')
        IGUrl = IGauth+settings.IG_CLIENT_ID+'&redirect_uri='+RedirectURI+'&state=login'
        return HttpResponseRedirect(IGUrl)
      else:
        pass
        # point to FB error page
    else:
      userprofile = userprofile[0]
      userprofile.fb_token = request.POST['fb_user_token']
      userprofile.save()
      user = userprofile.user
      password = hashlib.sha1(settings.HASH_PHRASE + userprofile.fb_id).hexdigest()
      new_user = authenticate(username=user.username,password=password)
      fbuser = facebook.get_user_from_cookie(request.COOKIES, settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET)
      graph = facebook.GraphAPI(fbuser["access_token"])
      fbprofile = graph.get_object("me")
      login(request, new_user) 
    if 'next_url' in request.POST:
      return HttpResponseRedirect(reverse('Instagram:check')+'?state=login&next='+request.POST['next_url'])
    else:
      return HttpResponseRedirect(reverse('Instagram:check')+'?state=login&next=none')
  else:
    if 'next' in request.GET:
      next_url = request.GET['next']
      context = {'next_url':next_url}
    else:
      context = {"FACEBOOK_APP_ID": settings.FACEBOOK_APP_ID,'FBPermissions': settings.FACEBOOK_PERMISSIONS}
    return render(request,"SiteUsers/login.html",context)
Example #3
0
    def parse_auth(self):
        """
        looks for a request param or cookie in order to decode a facebook object
        
        the returned value can then be used to do something like:
        
            graph = facebook.GraphAPI(cookie["access_token"])
            profile = graph.get_object("me")
            
        """
        signed_request = self.request.REQUEST.get("signed_request", None)

        if signed_request:
            signed_request = decode_signed_request(signed_request, self.facebook_app_secret)

            if signed_request and "uid" in signed_request:
                return signed_request

        else:
            if self.allow_cookie_auth:
                return facebook.get_user_from_cookie(
                    self.request.COOKIES, self.facebook_app_id, self.facebook_app_secret
                )

        return None
 def get_fb_user_cookie(self, request):
     """ Attempt to find a facebook user using a cookie. """
     fb_user = facebook.get_user_from_cookie(request.COOKIES,
         settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY)
     if fb_user:
         fb_user['method'] = 'cookie'
     return fb_user
Example #5
0
File: views.py Project: Taaag/taaag
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'] = ''
Example #6
0
def session_from_facebook():
    """
    uses the facebook session cookie to create a site specific session.

    it will also fetch profile information from facebook and add
    the user to the datastore if it does not exist yet
    """
    import facebook
    # get facebook user id and token from facebook cookie
    fb_user = facebook.get_user_from_cookie(request.cookies,
                                            app.config['FACEBOOK_APPLICATION_ID'],
                                            app.config['FACEBOOK_APPLICATION_SECRET'])

    if fb_user:
        # check whether the user is already in the datastoreg
        user = User.all().filter('facebook_id =', str(fb_user['uid'])).get()

        if user is None:
            # if not we fetch his profile information via the facebook graph api
            graph = facebook.GraphAPI(fb_user["access_token"])
            profile = graph.get_object("me")

            # now we can put the user in the datastore
            user = User(key_name=generate_key(),
                        facebook_id=str(profile['id']),
                        facebook_token=request.values.get('access_token'),
                        email=profile['email'],
                        name=profile['name'])
            user.save()

        # last but not least we add the user's key to the session cookie
        session['user_key'] = user.key().name()
    return "ok"
Example #7
0
def user_login(request, context):
  print "user login"
  user = facebook.get_user_from_cookie(request.COOKIES, '438894882828939', 
    '484028122fe1f70d55ea6d9be63859f2')

  print "after user"
  if user:
    graph = facebook.GraphAPI(user["access_token"])
    print "after graph"
    profile = graph.get_object("me")
    print "after profile"
    context['id'] = profile['id']
    print "after id"
    context['name'] = profile['name']
    print "after name"
    context['picture'] = graph.get_object("me/picture", type='large')['url']
    print "after picture"
    context['location'] = 'Philadelphia, PA'
    print "after location"
    context['school'] = 'University of Pennsylvania'
    print "after school"
    if User.objects.filter(user=context['id']).exists():
        print "beginning of if"
        pass
    else:
        print "beginning of else"
        u = User(user = context['id'], email = context['id'] + "@example.com",
            current_city = context['location'], current_location = context['school'],
            image = context['picture'])
        print "before save"
        u.save()
    print "before return"
    return graph
  else:
    return redirect('/')
Example #8
0
def get_more_community_photos(request):
    data = []
    try:
        cookie = facebook.get_user_from_cookie(
            request.COOKIES, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
        if cookie:
            created_date = request.GET.get('created_date');
            fb_user = FB_User.objects.get(fid=int(cookie["uid"]))
            created_date = datetime.fromtimestamp(float(created_date))
            photos = Photo.objects.filter(active=True, pending=False, portrit_photo=True, public=True, created_date__lt=created_date).order_by('-created_date')[:15]

            photo_data = [ ]
            for photo in photos:
                try:
                    temp = photo.get_portrit_photo()
                    portrit_user = photo.get_portrit_user()
                    photo_obj = photo.get_portrit_photo()
                    if photo_obj['crop'] != None:
                        photo_data.append({
                            'user_fid': portrit_user.fb_user.fid,
                            'name': portrit_user.name,
                            'photo': photo_obj,
                            'album_id': photo.album.id,
                            'create_datetime': time.mktime(photo.created_date.utctimetuple()),
                        })
                except:
                    pass
            data = photo_data
    except:
        pass
    data = json.dumps(data)
    return HttpResponse(data, mimetype='text/html')
    def authenticate(self, request, user=None):
        cookie = facebook.get_user_from_cookie(request.COOKIES,
                                               FACEBOOK_APP_ID,
                                               FACEBOOK_SECRET_KEY)
        if cookie:
            uid = cookie['uid']
            access_token = cookie['access_token']
        else:
            # if cookie does not exist
            # assume logging in normal way
            params = {}
            params["client_id"] = FACEBOOK_APP_ID
            params["client_secret"] = FACEBOOK_SECRET_KEY
            params["redirect_uri"] = '%s://%s%s' % (
                         'https' if request.is_secure() else 'http',
                         Site.objects.get_current().domain,
                         reverse("socialauth_facebook_login_done"))
            params["code"] = request.GET.get('code', '')

            url = ("https://graph.facebook.com/oauth/access_token?"
                   + urllib.urlencode(params))
            from cgi import parse_qs
            userdata = urllib.urlopen(url).read()
            res_parse_qs = parse_qs(userdata)
            # Could be a bot query
            if not res_parse_qs.has_key('access_token'):
                return None
                
            access_token = res_parse_qs['access_token'][-1]
            
            graph = facebook.GraphAPI(access_token)
            uid = graph.get_object('me')['id']
            
        try:
            fb_user = FacebookUserProfile.objects.get(facebook_uid=uid)
            return fb_user.user

        except FacebookUserProfile.DoesNotExist:
            
            # create new FacebookUserProfile
            graph = facebook.GraphAPI(access_token) 
            fb_data = graph.get_object("me")

            if not fb_data:
                return None

            username = uid
            if not user:
                user = User.objects.create(username=username)
                user.first_name = fb_data['first_name']
                user.last_name = fb_data['last_name']
                user.email = username + '@socialauth+facebook'
                user.save()
                
            fb_profile = FacebookUserProfile(facebook_uid=uid, user=user)
            fb_profile.save()
            
            auth_meta = AuthMeta(user=user, provider='Facebook').save()
                
            return user
Example #10
0
    def invite_friends_fb(self, registration):
        # we don't do fb invitations if university is not created
        if registration.location is None:
            redirect(registration.url(action='invite_friends'))

        # handle facebook callback
        ids = request.params.get('ids[]')
        if ids:
            registration.invited_fb_ids = ids
            meta.Session.commit()
            redirect(registration.url(action='invite_friends'))

        # render page
        fb_user = facebook.get_user_from_cookie(request.cookies,
                      config['facebook.appid'], config['facebook.secret'])
        c.has_facebook = fb_user is not None
        if c.has_facebook:
            try:
                graph = facebook.GraphAPI(fb_user['access_token'])
                friends = graph.get_object("me/friends")
                friend_ids = [f['id'] for f in friends['data']]
                friend_users = meta.Session.query(User)\
                        .filter(User.facebook_id.in_(friend_ids))\
                        .filter(User.location == registration.location).all()
                c.exclude_ids = ','.join(str(u.facebook_id) for u in friend_users)
            except facebook.GraphAPIError:
                c.has_facebook = False

        c.active_step = 'invite_friends'
        return render('registration/invite_friends_fb.mako')
Example #11
0
def change_user_permissions(request):
    data = False
    cookie = facebook.get_user_from_cookie(
        request.COOKIES, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
    if cookie:
        permission = request.POST.get('permission')
        check = request.POST.get('check')
        user = Portrit_User.objects.get(fb_user__fid=int(cookie["uid"]))
        
        if permission == 'fb_auto_post':
            if check == 'true':
                user.allow_notifications = True
            else:
                user.allow_notifications = False
        elif permission == 'portrit_album':
            if check == 'true':
                user.allow_winning_fb_album = True
            else:
                user.allow_winning_fb_album = False
            
        user.save()
        data = True
        
    data = simplejson.dumps(data)
    return HttpResponse(data, mimetype='application/json')
Example #12
0
    def invite_friends_fb(self):
        # handle facebook callback
        ids = request.params.get('ids[]')
        if ids:
            ids = map(int, ids.split(','))
            invited = make_facebook_invitations(ids, c.user, c.user.location)
            meta.Session.commit()
            if invited:
                h.flash(ungettext('Invited %(num)d friend.',
                                  'Invited %(num)d friends.',
                                  len(invited)) % dict(num=len(invited)))

            redirect(url(controller='profile', action='home'))

        # render page
        fb_user = facebook.get_user_from_cookie(request.cookies,
                      config['facebook.appid'], config['facebook.secret'])
        c.has_facebook = fb_user is not None
        if c.has_facebook:
            try:
                graph = facebook.GraphAPI(fb_user['access_token'])
                friends = graph.get_object("me/friends")
                friend_ids = [f['id'] for f in friends['data']]
                friend_users = meta.Session.query(User)\
                        .filter(User.facebook_id.in_(friend_ids))\
                        .filter(User.location == c.user.location).all()
                c.exclude_ids = ','.join(str(u.facebook_id) for u in friend_users)
            except facebook.GraphAPIError:
                c.has_facebook = False

        return render('profile/invite_friends_fb.mako')
Example #13
0
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)
Example #14
0
    def invite_fb(self, group):
        # Handle POST.
        invited = request.params.get('ids[]')
        if invited:
            ids = invited.split(',')
            for facebook_id in ids:
                group.create_pending_fb_invitation(int(facebook_id), c.user)
            make_facebook_invitations(ids, c.user, group.location)
            meta.Session.commit()
            h.flash(ungettext('Invited %(num)d friend.',
                              'Invited %(num)d friends.',
                              len(ids)) % dict(num=len(ids)))
            redirect(c.group.url(action='members'))

        # Render page.
        fb_user = facebook.get_user_from_cookie(request.cookies,
                         config['facebook.appid'], config['facebook.secret'])
        c.has_facebook = fb_user is not None
        if c.has_facebook:
            try:
                graph = facebook.GraphAPI(fb_user['access_token'])
                friends = graph.get_object("me/friends")
            except facebook.GraphAPIError:
                c.has_facebook = False
        if not c.has_facebook:
            # Ask to log on to facebook.
            return render('group/invite.mako')

        friend_ids = [f['id'] for f in friends['data']]
        friend_users = meta.Session.query(User).filter(
                            User.facebook_id.in_(friend_ids)).all()
        c.exclude_ids = ','.join(str(u.facebook_id) for u in friend_users
                                 if c.group.is_member(u))
        return render('group/invite.mako')
def getProfileJSONBundle(self):
    facebookUser = facebook.get_user_from_cookie(self.request.cookies, facebook_APP_ID, facebook_APP_SECRET)
    #if not facebookUser:
    #    graph = facebook.GraphAPI(self.request.get('accesstoken'))
    #    facebookUser = 1
    jsonBundle = {}
    if facebookUser:
        #if facebookUser != 1:
        graph = facebook.GraphAPI(facebookUser['access_token'])
        
        
        profile = graph.get_object('me')
        items = ['first_name', 'last_name', 'gender']
        for item in items:
            jsonBundle[item] = profile[item]
        #jsonBundle['picture'] = graph.get_connections("me", "picture")
        picture_url = "http://graph.facebook.com/" + profile['id'] +"/picture"
        jsonBundle['picture'] = picture_url
        
        query = database.members.gql("WHERE fid = :fid", fid = profile['id'])
        result = query.fetch(1)[0]
        
        if result:
            jsonBundle['isMember'] = True
            jsonBundle['depart_id'] = result.depart_id
            jsonBundle['school_id'] = result.school_id
        else:
            jsonBundle['isMember'] = False
    else:
        jsonBundle['error']= "Couldn't find cookie."

    
    return jsonBundle
	def authenticate(self,verification_code=None,cookies=[]):
		access_token = None
		fb_profile = None
		if(cookies):
			access_token = facebook.get_user_from_cookie(cookies, APP_ID, APP_SECRET)
			if 'fbs_' + APP_ID in cookies and datetime.fromtimestamp(float(access_token['expires'])) > datetime.now():
				graph = facebook.GraphAPI(access_token['access_token'])
				fb_profile = graph.get_object('me')

			id = access_token['uid']

		elif verification_code:
			ur = 'http://'+settings.HOST+'/fb/fb-auth/'
			args = dict(client_id=APP_ID, redirect_uri=ur)
			args["client_secret"] = APP_SECRET
			args["code"] = verification_code

			ur = "https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args)

			response = urllib2.urlopen(ur).read()
			atoken = response.split('&')[0].split('=')[-1]
			access_token = urllib2.unquote(atoken)

			graph = facebook.GraphAPI(access_token)
			fb_profile = graph.get_object('me')
			id = fb_profile['id']
		
		if(fb_profile):	
			fb_user = self.updateDb(fb_profile,access_token)
			return fb_user.user
		else:
			return None
Example #17
0
def facebook_events(request):
    fb_user = facebook.get_user_from_cookie(request.COOKIES, settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET)

    if fb_user:
        graph = facebook.GraphAPI(fb_user["access_token"])

        if request.method == "POST" and request.is_ajax():
            form =  EventForm(request.POST)
            if form.is_valid():
                graph.put_object('me', 'events', name=request.POST['name'],
                                 start_time=request.POST['start_time'],
                                 end_time=request.POST['end_time'])
                return HttpResponse(json.dumps({'status': 'saved'}), mimetype="application/json")
            else:
                
                return HttpResponse(json.dumps({'status': 'error'}), mimetype="application/json")

        else:

            feed = graph.get_connections('me', 'events')
            feed_list = []
            for entry in feed['data']:
                if entry.has_key('name'):
                    feed_list.append(entry['name'])

            return HttpResponse(mark_safe(render_to_string('feed.html', {'feeds':feed_list})))

    else:
        return None
Example #18
0
def set_fb(request):

        data = request.POST.get('data')

        try:
            data = simplejson.loads(data)
        except ValueError:
            data = None

        gender = request.POST.get('gender')
        image = compose_image(data, gender)

        image_filename = "%s.%s" % (str(uuid.uuid4()), 'png')
        image_path = "%s/%s" % (settings.MEDIA_ROOT, image_filename)
        image.save(image_path)

        access_token = request.POST.get('token')

        if not access_token:
            user = facebook.get_user_from_cookie(request.COOKIES, settings.FB_APP_ID, settings.FB_APP_SECRET)
            access_token = user["access_token"]

        if access_token:
            graph = facebook.GraphAPI(access_token)
            response = graph.put_photo(open(image_path))
            return HttpResponse(simplejson.dumps(response))
        return HttpResponseBadRequest()
Example #19
0
 def current_user(self):
     """Returns the active user, or None if the user has not logged in."""
     if not hasattr(self, "_current_user"):
         self._current_user = None
         cookie = facebook.get_user_from_cookie(
             self.request.COOKIES, settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET)
         if cookie:
             # Store a local instance of the user data so we don't need
             # a round-trip to Facebook on every request
             try:
                 user = FacebookUser.objects.get(uid=cookie["uid"])
             except FacebookUser.DoesNotExist:
                 graph = facebook.GraphAPI(cookie["access_token"])
                 profile = graph.get_object("me")
                 user = FacebookUser(pk=str(profile["id"]),
                                     name=profile["name"],
                                     profile_url=profile["link"],
                                     access_token=cookie["access_token"])
                 user.save()
             else:
                 if user.access_token != cookie["access_token"]:
                     user.access_token = cookie["access_token"]
                     user.save()
             self._current_user = user
     return self._current_user
Example #20
0
    def land_fb(self):
        fb_user = facebook.get_user_from_cookie(request.cookies,
                         config['facebook.appid'], config['facebook.secret'])

        if not fb_user or 'uid' not in fb_user or 'access_token' not in fb_user:
            h.flash(_("Failed to link Facebook account"))
            redirect(url('frontpage'))

        facebook_id = int(fb_user['uid'])
        fb_access_token = fb_user['access_token']
        registration = meta.Session.query(UserRegistration).\
                filter_by(completed=False, facebook_id=facebook_id).first()

        if registration is None:
            h.flash(_("Your invitation has expired."))
            redirect(url('frontpage'))

        name, email = self._facebook_name_and_email(facebook_id, fb_access_token)
        if not email:
            h.flash(_("Facebook did not provide your email address."))
            redirect(url('frontpage'))

        registration.fullname = name
        registration.email = registration.facebook_email = email
        registration.email_confirmed = True
        registration.update_logo_from_facebook()
        meta.Session.commit()

        redirect(registration.url(action='university_info'))
Example #21
0
def contact_portrit(request):
    cookie = facebook.get_user_from_cookie(
        request.COOKIES, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
    if cookie:
        try:
            from_email = request.POST.get('email')
            reason = request.POST.get('reason')
            message = request.POST.get('message')
        
            to_email_dict = {
                '1': '*****@*****.**',
                '2': '*****@*****.**',
                '3': '*****@*****.**',
                '4': '*****@*****.**',
                '5': '*****@*****.**',
                '6': '*****@*****.**',
            }
            to_email = to_email_dict[reason]
        
            from django.core.mail import EmailMessage
            subject = 'Contact Form'
            html_content = from_email + '\n\n' + message
        
            msg = EmailMessage(subject, html_content, '*****@*****.**', [to_email,])
            msg.send()
        
        except Exception, err:
            print err
Example #22
0
def get_graph(request):
    cookie = facebook.get_user_from_cookie(request.COOKIES,
                                               'undefined',
                                               FACEBOOK_SECRET_KEY)
    if cookie:
            uid = cookie['uid']
            access_token = cookie['access_token']
    else:
        # if cookie does not exist
        # assume logging in normal way
        params = {}
        params["client_id"] = FACEBOOK_APP_ID
        params["client_secret"] = FACEBOOK_SECRET_KEY
        #params["redirect_uri"] = '%s://%s%s' % (
        #             'https' if request.is_secure() else 'http',
        #             Site.objects.get_current().domain,
        #             reverse("socialauth_facebook_login_done"))
        params["redirect_uri"] = "http://apps.facebook.com/cineight/"
        params["code"] = request.GET.get('code', '')

        url = ("https://graph.facebook.com/oauth/access_token?"
               + urllib.urlencode(params))
        from cgi import parse_qs
        userdata = urllib.urlopen(url).read()
        res_parse_qs = parse_qs(userdata)
        # Could be a bot query
        if not res_parse_qs.has_key('access_token'):
            return None
                
        access_token = res_parse_qs['access_token'][-1]
        #graph = facebook.GraphAPI(access_token)
        #uid = graph.get_object('me')['id']
    return facebook.GraphAPI(access_token)
 def authenticate(self, cookies):
     APP_ID = settings.FACEBOOK_APP_ID
     SECRET_KEY = settings.FACEBOOK_SECRET_KEY
     NS = settings.FACEBOOK_USER_NAMESPACE
     try:
         access_token = facebook.get_user_from_cookie(cookies, APP_ID, SECRET_KEY)
         token_not_expired = datetime.fromtimestamp(float(access_token['expires'])) > datetime.now()
         if 'fbs_' + APP_ID in cookies and token_not_expired:
             graph = facebook.GraphAPI(access_token['access_token'])
             user_info = graph.get_object('me')
             try:
                 facebook_data = Facebook.objects.get(uid=user_info['id'])
                 return facebook_data.user
             except Facebook.DoesNotExist:
                 try:
                     email = user_info['email']
                 except:
                     email = user_info['id'] + '@dummyfbemail.com'
                 user = User.objects.create(username=NS + user_info['id'], 
                                            email=email)
                 user.first_name = user_info['first_name']
                 user.last_name = user_info['last_name']
                 user.save()
                 # New users get an unusable password.
                 if settings.FACEBOOK_SET_UNUSABLE_PASSWORD:
                     user.set_unusable_password()
                 facebook_data = Facebook(uid=user_info['id'], 
                                          url=user_info['link'], user=user)
                 facebook_data.save()
                 return user
         else:
             return None
     except:
         return None
Example #24
0
def fb_logout(cookies, response):
    fb_info = facebook.get_user_from_cookie(cookies, settings.FACEBOOK_APPLICATION_ID, settings.FACEBOOK_APPLICATION_SECRET)
    if fb_info:
        fb_info['uid'] = ""
        fb_info['access_token'] = ""

        ###########
        ### just reverse facebook.get_user_from_cookie.
        ### Original get_user_from_cookie is from Facebook Python SDK
        ### Copyright 2010 Facebook
        ### Licensed under the Apache License, Version 2.0 (the "License")
        ### Modified for set by Almad
        ##########

        response['P3P'] = 'CP="NOI DSP COR NID ADMa OPTa OUR NOR"'
        
        expire_time = time() - 86400

        args = copy(fb_info)
        args['expires'] = str(int(expire_time))
        payload = "".join([k + "=" + fb_info[k] for k in sorted(args.keys()) if k != "sig"])
        
        args['sig'] = md5(payload+settings.FACEBOOK_APPLICATION_SECRET).hexdigest()

        response.set_cookie('fbs_%s' % settings.FACEBOOK_APPLICATION_ID , urlencode(args), expires=expire_time, domain=settings.SESSION_COOKIE_DOMAIN)
def login(request):
    facebook_user = facebook.get_user_from_cookie(request.COOKIES,
        settings.FACEBOOK_APPID, settings.FACEBOOK_SECRET)
    next = request.GET.get("next", None)
    if facebook_user:
        access_token = facebook_user["access_token"]
        graph = facebook.GraphAPI(access_token)
        facebook_user = graph.get_object("me")
        email = facebook_user["email"]
        if graph:
            try:
                user = User.objects.get(email=email)
            except User.DoesNotExist:
                username = hashlib.md5(email).hexdigest()[:30]
                user = User.objects.create_user(username, email, "")
                user.first_name = facebook_user["first_name"]
                user.last_name = facebook_user["last_name"]
                user.save()
            is_new_user = "******" in locals()
            profile = user.get_profile()
            profile.facebook_access_token = access_token
            if is_new_user:
                profile.facebook_connect_only = True
            profile.save()
            user = auth.authenticate(username=profile.user.email, is_facebook_connect=True)
            logged_in.send(sender=None, request=request, user=user, is_new_user=is_new_user)
            auth.login(request, user)
            return redirect(next or "index")
    messages.error(request, "Facebook login credentials could not be verified, please try again.")
    return redirect(next or "login")
Example #26
0
    def current_user(self):
        """
        :returns object: User object or None
        """
        if not hasattr(self, "_current_user"):
            logging.info("not hasattr")
            self._current_user = None
            cookie = facebook.get_user_from_cookie(
                self.request.cookies,
                self.app.config.get("FACEBOOK_APP_ID", ""),
                self.app.config.get("FACEBOOK_APP_SECRET", ""))
            logging.info(str(self.request.cookies))
            if cookie:
                logging.info("if cookie")
                # Store a local instance of the user data so we don't need
                # a round-trip to Facebook on every request
                user = User.get_by_key_name(cookie["uid"])
                if not user:
                    logging.info("if not user")
                    graph = facebook.GraphAPI(cookie["access_token"])
                    profile = graph.get_object("me")
                    user = User(key_name=str(profile["id"]),
                                id=str(profile["id"]),
                                name=profile["name"],
                                profile_url=profile["link"],
                                access_token=cookie["access_token"])
                    user.put()
                elif user.access_token != cookie["access_token"]:
                    logging.info("elif user.access_token")
                    user.access_token = cookie["access_token"]
                    user.put()
                self._current_user = user
#             else:
#                 return None
        return self._current_user
Example #27
0
 def current_user(self):
     if self.session.get("user"):
         # User is logged in
         return self.session.get("user")
     else:
         # Either used just logged in or just saw the first page
         # We'll see here
         cookie = facebook.get_user_from_cookie(self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
         if cookie:
             # Okay so user logged in.
             # Now, check to see if existing user
             user = User.get_by_key_name(cookie["uid"])
             if not user:
                 # Not an existing user so get user info
                 graph = facebook.GraphAPI(cookie["access_token"])
                 profile = graph.get_object("me")
                 user = User(
                     key_name=str(profile["id"]),
                     id=str(profile["id"]),
                     name=profile["name"],
                     profile_url=profile["link"],
                     access_token=cookie["access_token"],
                 )
                 user.put()
             elif user.access_token != cookie["access_token"]:
                 user.access_token = cookie["access_token"]
                 user.put()
             # User is now logged in
             self.session["user"] = dict(
                 name=user.name, profile_url=user.profile_url, id=user.id, access_token=user.access_token
             )
             return self.session.get("user")
     return None
Example #28
0
	def current_user( self ) :
		if not hasattr( self, '_current_user' ) :
			self._current_user = None
			cookie = facebook.get_user_from_cookie(
				self.request.cookies,
				FACEBOOK_APP_ID,
				FACEBOOK_APP_SECRET
			)
			if cookie :
				# Store a local instance of the user data so we don't need
				# a round-trip to Facebook on every request
				user = User.get_by_key_name( cookie['uid'] )
				if not user :
					graph = facebook.GraphAPI( cookie['access_token'] )
					profile = graph.get_object( 'me' )
					user = User(
						key_name = str( profile['id'] ),
						id = str( profile['id'] ),
						name = profile['name'],
						profile_url = profile['link'],
						access_token = cookie['access_token'],
					)
					user.put()
				elif user.access_token != cookie['access_token'] :
					user.access_token = cookie['access_token']
					user.put()
				self._current_user = user
		return self._current_user
    def authenticate(self, request=None):
        fb_info = facebook.get_user_from_cookie(request.COOKIES, settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET)

        if fb_info and 'uid' in fb_info:
            return get_user_model().objects.get_by_facebook_id(uid=fb_info['uid'])

        return None
def facebook_connect(request, template='socialregistration/facebook.html',
    extra_context=dict()):
    """
    View to handle connecting existing django accounts with facebook
    """

    fb_user = facebook.get_user_from_cookie(request.COOKIES,
        settings.FACEBOOK_API_KEY, settings.FACEBOOK_SECRET_KEY)
    
    if fb_user is None or request.user.is_authenticated() is False:
        extra_context.update(dict(error=FB_ERROR))
        return render_to_response(template, extra_context,
            context_instance=RequestContext(request))
    graph = facebook.GraphAPI(fb_user['access_token']).get_object(fb_user['uid'])

    try:
        profile = SocialProfile.objects.get(uid=fb_user['uid'],soc_type = ST_FACEBOOK)
    except SocialProfile.DoesNotExist:
        profile = SocialProfile.objects.create(user=request.user,
            uid=fb_user['uid'],
            username='******' %(graph['first_name'], graph['last_name']),
            avatar='http://graph.facebook.com/%s/picture' % fb_user['uid'],
            soc_type = ST_FACEBOOK)
    else:
        profile.username='******' %(graph['first_name'], graph['last_name']),
        profile.save()

    return HttpResponseRedirect(_get_next(request))
Example #31
0
def facebook_login(track_id):
    ''' Function to called if the site is configured for advanced facebook authentication.
    
    '''
    #fbtrackform = FacebookTrackForm()
    auth_like = None
    auth_post = None
    #if fbtrackform.validate_on_submit():
    if request.method == 'POST':
        auth_like = request.form['authlike']
        auth_post = request.form['authpost']
    #Validate track id and get all the needed variables
    guest_track = Guesttrack.query.filter_by(track_id=track_id).first()
    if not guest_track:
        current_app.logger.error(
            "Called authorize_guest with wrong track ID:%s" % track_id)
        abort(404)

    #validate session associated with this track ID
    guest_session = Guestsession.query.filter_by(
        id=guest_track.session_id).first()
    if not guest_session:
        current_app.logger.error(
            "Called authorize_guest with wrong Session from track ID:%s" %
            track_id)
        abort(404)
    guest_device = Device.query.filter_by(id=guest_session.device_id).first()
    landing_site = Wifisite.query.filter_by(id=guest_session.site_id).first()
    if not guest_device or not landing_site:
        current_app.logger.error(
            "Called authorize_guest with wrong Session/Device/Wifisite from track ID:%s"
            % track_id)
        abort(404)

    # Attempt to get the short term access token for the current user.
    current_app.logger.debug(
        'Wifiguest Log - Site ID:%s facebook_login for track ID:%s' %
        (guest_track.site_id, guest_track.id))
    if auth_like != '1':  #ensure this is first time visit, not the visit after like/post
        fb_appid = landing_site.fb_appid or current_app.config['FB_APP_ID']
        fb_app_secret = landing_site.fb_app_secret or current_app.config[
            'FB_APP_SECRET']
        check_user_auth = get_user_from_cookie(cookies=request.cookies,
                                               app_id=fb_appid,
                                               app_secret=fb_app_secret)
        if not check_user_auth or not check_user_auth['uid']:
            #
            #User is not logged into DB app, redirect to social login page
            current_app.logger.debug(
                'Wifiguest Log - Site ID:%s facebook_login  Used not logged in, redirecting to social_login for track ID:%s'
                % (guest_track.site_id, guest_track.id))
            return redirect(url_for('guest.social_login', track_id=track_id),
                            code=302)

        #check this FB profile already added into our DB,else add it
        profile_check = Facebookauth.query.filter(
            and_(Facebookauth.profile_id == check_user_auth['uid'],
                 Facebookauth.site_id == landing_site.id)).first()
        if not profile_check:

            profile_check = Facebookauth()
            profile_check.profile_id = check_user_auth['uid']
            profile_check.token = check_user_auth['access_token']
            profile_check.site = landing_site
            db.session.add(profile_check)
            db.session.commit
            current_app.logger.debug(
                'Wifiguest Log - Site ID:%s facebook_login  adding new FB profile ID:%s for track ID:%s'
                % (guest_track.site_id, profile_check.id, guest_track.id))

        #profile already added to DB, check if the user had already authorized the site
        guest_check = Guest.query.filter(
            and_(Guest.site_id == guest_session.site_id,
                 Guest.fb_profile == profile_check.id)).first()
        if not guest_check:
            #Guest entry for this user is not available in DB,add the same.
            try:
                graph = GraphAPI(check_user_auth['access_token'])
                profile = graph.get_object(
                    profile_check.profile_id +
                    '?locale=en_US&fields=name,email,first_name,last_name')
            except:
                #Exception while calling graph API, redirect user to same page to try again
                current_app.logger.exception(
                    'Wifiguest Log - Site ID:%s facebook_login  exception while API FB profile ID:%s for track ID:%s'
                    % (guest_track.site_id, guest_track.id, profile_check.id))
                return redirect(url_for('guest.facebook_login',
                                        track_id=track_id),
                                code=302)
            else:
                guest_check = Guest()
                guest_check.firstname = profile.get('first_name')
                guest_check.lastname = profile.get('last_name')
                guest_check.email = profile.get('email')
                guest_check.site_id = guest_session.site_id
                guest_check.facebookauth = profile_check
                profile_check.guests.append(guest_check)
                db.session.add(guest_check)
                db.session.commit()
                #New guest added create task for API export
                celery_export_api.delay(guest_check.id)
                current_app.logger.debug(
                    'Wifiguest Log - Site ID:%s facebook_login  adding new Guest:%s for track ID:%s'
                    % (guest_track.site_id, guest_check.id, guest_track.id))
        #
        #even if guest entry was already added, assign the guest to device
        guest_device.guest = guest_check
        guest_check.devices.append(guest_device)
        db.session.commit()
    else:
        guest_check = Guest.query.filter_by(id=guest_device.guest_id).first()
        if not guest_check:
            #
            #User is not logged into DB app, redirect to social login page
            current_app.logger.debug(
                'Wifiguest Log - Site ID:%s facebook_login  Used not logged in after like/post, redirecting to social_login for track ID:%s'
                % (guest_track.site_id, guest_track.id))
            return redirect(url_for('guest.social_login', track_id=track_id),
                            code=302)

    if landing_site.auth_fb_like == 1:
        if guest_track.fb_liked != 1:
            if guest_check.fb_liked:
                # if the guest has liked the page already, mark guesttrack as liked
                current_app.logger.debug(
                    'Wifiguest Log - Site ID:%s facebook_login  guest already liked for track ID:%s'
                    % (guest_track.site_id, guest_track.id))
                guest_track.fb_liked = 1
                db.session.commit()
            elif auth_like == '1':
                #quick hack to test for liking and posting, guest has skipped the liking, allow
                #internet for now and ask next time
                current_app.logger.debug(
                    'Wifiguest Log - Site ID:%s facebook_login  guest decided to skip  like for track ID:%s'
                    % (guest_track.site_id, guest_track.id))
                guest_track.fb_liked = 1
                db.session.commit()
            elif auth_like == '2':
                #user has liked the page mark track and guest as liked
                current_app.logger.debug(
                    'Wifiguest Log - Site ID:%s facebook_login  guest liked now for track ID:%s'
                    % (guest_track.site_id, guest_track.id))
                guest_track.fb_liked = 1
                guest_check.fb_liked = 1
                db.session.commit()
            else:
                # show page asking user to like
                current_app.logger.debug(
                    'Wifiguest Log - Site ID:%s facebook_login  new guest show page to like for track ID:%s'
                    % (guest_track.site_id, guest_track.id))
                landing_page = Landingpage.query.filter_by(
                    id=landing_site.default_landing).first()
                fb_page = landing_site.fb_page or current_app.config[
                    'FB_PAGE_URL']
                return render_template("guest/%s/fb_like.html" %
                                       landing_site.template,
                                       landing_page=landing_page,
                                       font_list=font_list,
                                       app_id=fb_appid,
                                       track_id=track_id,
                                       fb_page=fb_page)

    #mark sessions as authorized
    guest_session.state = SESSION_AUTHORIZED
    guest_track.state = GUESTRACK_NEW_AUTH
    if guest_check.fb_liked == 1:  # if guest has full filled all the social login criterias,mark the device as authed
        guest_device.state = DEVICE_AUTH
    db.session.commit()
    return redirect(url_for('guest.authorize_guest',
                            track_id=guest_track.track_id),
                    code=302)
Example #32
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)
Example #33
0
def login_view(request):
    if request.method == 'POST':
        userprofile = UserProfile.objects.filter(
            fb_id=request.POST['fb_user_id'])
        if not userprofile:
            fbuser = facebook.get_user_from_cookie(
                request.COOKIES, settings.FACEBOOK_APP_ID,
                settings.FACEBOOK_APP_SECRET)
            if fbuser:  # fb user logged in and exists
                graph = facebook.GraphAPI(fbuser["access_token"])
                fbprofile = graph.get_object("me")
                fbfriends = graph.get_connections("me", "friends")

                # log user into site
                hashed_password = hashlib.sha1(
                    settings.HASH_PHRASE +
                    request.POST['fb_user_id']).hexdigest()
                fname = fbprofile['first_name']
                lname = fbprofile['last_name']
                username = '******'.join([fname, lname, request.POST['fb_user_id']])
                user = User.objects.create_user(username=username,
                                                email=fbprofile['email'],
                                                password=hashed_password)
                userprofile = UserProfile(fb_id=fbprofile['id'],
                                          user=user,
                                          fb_token=fbuser["access_token"],
                                          first_name=fbprofile['first_name'],
                                          last_name=fbprofile['last_name'],
                                          gender=fbprofile['gender'],
                                          birthyear=datetime.datetime.strptime(
                                              fbprofile['birthday'],
                                              '%m/%d/%Y').year)
                userprofile.save()
                enterSchoolUser(fbprofile["education"], userprofile)
                enterFriends(fbfriends, userprofile)

                new_user = authenticate(username=username,
                                        password=hashed_password)
                login(request, new_user)

                # redirect to check instagram id
                RedirectURI = 'http://' + request.get_host() + reverse(
                    'Instagram:redirect')
                IGUrl = IGauth + settings.IG_CLIENT_ID + '&redirect_uri=' + RedirectURI + '&state=login'
                return HttpResponseRedirect(IGUrl)
            else:
                pass
                # point to FB error page
        else:
            userprofile = userprofile[0]
            userprofile.fb_token = request.POST['fb_user_token']
            userprofile.save()
            user = userprofile.user
            password = hashlib.sha1(settings.HASH_PHRASE +
                                    userprofile.fb_id).hexdigest()
            new_user = authenticate(username=user.username, password=password)
            fbuser = facebook.get_user_from_cookie(
                request.COOKIES, settings.FACEBOOK_APP_ID,
                settings.FACEBOOK_APP_SECRET)
            graph = facebook.GraphAPI(fbuser["access_token"])
            fbprofile = graph.get_object("me")
            login(request, new_user)
        if 'next_url' in request.POST:
            return HttpResponseRedirect(
                reverse('Instagram:check') + '?state=login&next=' +
                request.POST['next_url'])
        else:
            return HttpResponseRedirect(
                reverse('Instagram:check') + '?state=login&next=none')
    else:
        if 'next' in request.GET:
            next_url = request.GET['next']
            context = {'next_url': next_url}
        else:
            context = {
                "FACEBOOK_APP_ID": settings.FACEBOOK_APP_ID,
                'FBPermissions': settings.FACEBOOK_PERMISSIONS
            }
        return render(request, "SiteUsers/login.html", context)
Example #34
0
def register(request):
    if request.method == 'POST':  # If the form has been submitted...

        form = UserForm(request.POST)  # A form bound to the POST data
        if form.is_valid():  # All validation rules pass
            form_data = form.cleaned_data
            fbuser = facebook.get_user_from_cookie(
                request.COOKIES, settings.FACEBOOK_APP_ID,
                settings.FACEBOOK_APP_SECRET)
            if fbuser:
                graph = facebook.GraphAPI(fbuser["access_token"])
                fbprofile = graph.get_object("me")
                fbfriends = graph.get_connections("me", "friends")
                fbuser_exists = UserProfile.objects.filter(
                    fb_id=fbprofile['id']).count() > 0
                if fbuser_exists == False:
                    user = User.objects.create_user(form_data['username'],
                                                    form_data['email'],
                                                    form_data['password'])
                    location = enterLocation(fbprofile['location'])
                    userprofile = UserProfile(
                        fb_id=fbprofile['id'],
                        user=user,
                        fb_token=fbuser["access_token"],
                        first_name=fbprofile['first_name'],
                        last_name=fbprofile['last_name'],
                        location=location,
                        gender=fbprofile['gender'],
                        birthyear=datetime.datetime.strptime(
                            fbprofile['birthday'], '%m/%d/%Y').year)
                    userprofile.save()
                    enterSchoolUser(fbprofile["education"], userprofile)
                    enterFriends(fbfriends, userprofile)

                    # log user in
                    new_user = authenticate(username=form_data['username'],
                                            password=form_data['password'])
                    login(request, new_user)

                    # send user to verify instagram
                    RedirectURI = 'http://' + request.get_host() + reverse(
                        'Instagram:redirect')
                    IGUrl = IGauth + settings.IG_CLIENT_ID + '&redirect_uri=' + RedirectURI + '&state=register'
                    return HttpResponseRedirect(IGUrl)
                else:  #fb user already assigned to a user
                    return HttpResponse('FB already assigned')
            else:  #fb denied
                HttpResponse('you denied fb')
        else:  #form not valid

            user_form = UserForm()
            context = {
                "FACEBOOK_APP_ID": settings.FACEBOOK_APP_ID,
                'FBPermissions': settings.FACEBOOK_PERMISSIONS,
                'user_form': user_form
            }
            return HttpResponse(form.is_valid())
    else:
        user_form = UserForm()
        context = {
            "FACEBOOK_APP_ID": settings.FACEBOOK_APP_ID,
            'FBPermissions': settings.FACEBOOK_PERMISSIONS,
            'user_form': user_form,
            'IG': (False, '')
        }
        return render(request, "SiteUsers/register.html", context)
Example #35
0
 def initialize(self, request, response):
     """ Check cookies, load user session before handling requests. Necessary here? can be merged into POST or GET.
     """
     webapp.RequestHandler.initialize(self, request, response)
     if self.request.get('use') == 'gift':
         self.authorize()
         return
     sr = self.request.get('signed_request')
     if sr:
         data = parse_signed_request(sr, FACEBOOK_APP_SECRET)
         logging.debug('FacebookRequest.initialize: signed_request = %s' %
                       data)
         if data:
             if 'oauth_token' not in data:
                 logging.debug(
                     'FacebookRequest.initialize: signed_request has no oauth_token, redirect to oauth/authorize'
                 )
                 self.authorize()
                 return
             else:
                 logging.debug('FacebookRequest.initialize: ready to login')
                 self.login(data['user_id'], data['oauth_token'])
         else:
             logging.debug(
                 'FacebookRequest.initialize: Bad signed_request, return home page without login'
             )
     else:
         fbcookie = facebook.get_user_from_cookie(self.request.cookies,
                                                  FACEBOOK_APP_ID,
                                                  FACEBOOK_APP_SECRET)
         if fbcookie:
             logging.debug('FacebookRequest.initialize: fbcookie = %s' %
                           fbcookie)
             self.login(fbcookie['uid'], fbcookie['access_token'])
         else:
             code = self.request.get('code')
             if code:
                 logging.debug(
                     'FacebookRequest.initialize: got code from oauth-authorize exchange for access_token'
                 )
                 aargs = {
                     'client_id': FACEBOOK_APP_ID,
                     'client_secret': FACEBOOK_APP_SECRET,
                     'code': code,
                     'redirect_uri': self.request.path_url
                 }
                 response = cgi.parse_qs(
                     urllib.urlopen(
                         "https://graph.facebook.com/oauth/access_token?" +
                         urllib.urlencode(aargs)).read())
                 logging.debug(
                     'FacebookRequest.initialize: response from oauth/access_token: %s'
                     % response)
                 if response and 'access_token' in response:
                     access_token = response["access_token"][-1]
                     graph = facebook.GraphAPI(access_token)
                     profile = graph.get_object('me')
                     logging.debug(
                         'FacebookRequest.initialize: got graph profile of me:%s'
                         % profile)
                     self.login(profile['id'], access_token)
                 else:
                     logging.debug(
                         'FacebookRequest.initialize: Bad result from oauth/access_token, return home page without login'
                     )
             else:
                 logging.debug(
                     'FacebookRequest.initialize: no code, try oauth/authorize'
                 )
                 self.authorize()
Example #36
0
def fb_login_check(trackid, guesttrack, wifisite, guestdevice, fbconfig,
                   loginauth):
    '''End point for validating guest's FB login

    '''
    code = request.args.get('code')
    access_token = None
    fb_appid = fbconfig.fb_appid
    fb_app_secret = fbconfig.fb_app_secret
    if code:
        #URL called after OAuth
        redirect_uri = url_for('unifispot.modules.facebook.fb_login_check',
                               trackid=trackid,
                               _external=True)
        try:
            at = GraphAPI().get_access_token_from_code(code, redirect_uri,
                                                       fb_appid, fb_app_secret)
            access_token = at['access_token']
            graph = GraphAPI(access_token)
            profile = graph.get_object(
                "me",
                fields=
                'name,email,first_name,last_name,gender,birthday,age_range')
            if not profile:
                #
                #User is not logged into DB app, redirect to social login page
                guestlog_warn(
                    'guestdevice MAC:%s facebook_login  empty profile, \
                    should be redirected to login ' % guestdevice.devicemac,
                    wifisite, guesttrack)
                return redirect_guest(wifisite, guesttrack)
        except:
            guestlog_exception(
                'guestdevice MAC:%s facebook_login  exception , \
                    should be redirected to login ' % guestdevice.devicemac,
                wifisite, guesttrack)
            return redirect_guest(wifisite, guesttrack)
    else:
        #URL could be called by JS, check for cookies
        #
        try:
            check_user_auth = get_user_from_cookie(cookies=request.cookies,
                                                   app_id=fb_appid,
                                                   app_secret=fb_app_secret)
            access_token = check_user_auth['access_token']
            graph = GraphAPI(access_token)
            profile = graph.get_object(
                "me",
                fields=
                'name,email,first_name,last_name,gender,birthday,age_range')
            if not check_user_auth or not check_user_auth['uid'] or not profile:
                #
                #User is not logged into DB app, redirect to social login page
                guestlog_warn(
                    'guestdevice MAC:%s facebook_login  empty profile, \
                    should be redirected to login ' % guestdevice.devicemac,
                    wifisite, guesttrack)
                return redirect_guest(wifisite, guesttrack)
        except:
            guestlog_exception(
                'guestdevice MAC:%s facebook_login  exception , \
                    should be redirected to login ' % guestdevice.devicemac,
                wifisite, guesttrack)
            return redirect_guest(wifisite, guesttrack)
    #create FB AUTH
    loginauth.fbprofileid = profile['id']
    loginauth.fbtoken = access_token
    loginauth.save()

    #add/update guest
    newguest = assign_guest_entry(wifisite, guesttrack, fbprofile=profile)

    #update guesttrack

    #update guestdevice
    guestdevice.guestid = newguest.id
    guestdevice.save()
    #update guest
    newguest.demo = guesttrack.demo
    newguest.devices.append(guestdevice)
    newguest.save()

    #check if either checkin/like configured
    if fbconfig.auth_fb_post == 1:
        return redirect(
            url_for('unifispot.modules.facebook.fb_checkin', trackid=trackid))
    elif fbconfig.auth_fb_like == 1 and newguest.fbliked != 1:
        return redirect(
            url_for('unifispot.modules.facebook.fb_like', trackid=trackid))
    else:
        loginauth.populate_auth_details(fbconfig)
        loginauth.reset()
        loginauth.reset_lastlogin()
        loginauth.state = LOGINAUTH_FIRST
        loginauth.save()
        #neither configured, authorize guest
        guesttrack.state = GUESTTRACK_POSTLOGIN
        guesttrack.loginauthid = loginauth.id
        guesttrack.updatestat('auth_facebook', 1)
        return redirect_guest(wifisite, guesttrack)
Example #37
0
    cookies = None
    try:
        cookies = Cookie.BaseCookie(os.environ.get('HTTP_COOKIE', ''))
    except Cookie.CookieError, error:
        logging.debug("Ignoring Cookie Error, skipping Facebook login: '******'" %
                      error)

    if cookies is None:
        return None

    morsel_key = "fbs_" + App.facebook_app_id
    morsel = cookies.get(morsel_key)
    if morsel:
        fb_user_dict = facebook.get_user_from_cookie(
            {morsel_key: morsel.value}, App.facebook_app_id,
            App.facebook_app_secret)
        if fb_user_dict:
            return get_profile_from_fb_token(fb_user_dict["access_token"])

    return None


def get_profile_from_fb_token(access_token):

    if App.facebook_app_secret is None:
        return None

    if not access_token:
        logging.debug("Empty access token")
        return None
Example #38
0
def facebook_login():
    """
    Handle Facebook login.

    When a user logs in with Facebook, all of the authentication happens on the
    client side with Javascript.  Since all authentication happens with
    Javascript, we *need* to force a newly created and / or logged in Facebook
    user to redirect to this view.

    What this view does is:

        - Read the user's session using the Facebook SDK, extracting the user's
          Facebook access token.
        - Once we have the user's access token, we send it to Stormpath, so that
          we can either create (or update) the user on Stormpath's side.
        - Then we retrieve the Stormpath account object for the user, and log
          them in using our normal session support (powered by Flask-Login).

    Although this is slighly complicated, this gives us the power to then treat
    Facebook users like any other normal Stormpath user -- we can assert group
    permissions, authentication, etc.

    The location this view redirects users to can be configured via
    Flask-Stormpath settings.
    """
    # First, we'll try to grab the Facebook user's data by accessing their
    # session data.
    facebook_user = get_user_from_cookie(
        request.cookies,
        current_app.config['STORMPATH_SOCIAL']['FACEBOOK']['app_id'],
        current_app.config['STORMPATH_SOCIAL']['FACEBOOK']['app_secret'],
    )

    # Now, we'll try to have Stormpath either create or update this user's
    # Stormpath account, by automatically handling the Facebook Graph API stuff
    # for us.
    try:
        account = User.from_facebook(facebook_user['access_token'])
    except StormpathError as err:
        social_directory_exists = False

        # If we failed here, it usually means that this application doesn't have
        # a Facebook directory -- so we'll create one!
        for asm in current_app.stormpath_manager.application.account_store_mappings:

            # If there is a Facebook directory, we know this isn't the problem.
            if (
                getattr(asm.account_store, 'provider') and
                asm.account_store.provider.provider_id == Provider.FACEBOOK
            ):
                social_directory_exists = True
                break

        # If there is a Facebook directory already, we'll just pass on the
        # exception we got.
        if social_directory_exists:
            raise err

        # Otherwise, we'll try to create a Facebook directory on the user's
        # behalf (magic!).
        dir = current_app.stormpath_manager.client.directories.create({
            'name': current_app.stormpath_manager.application.name + '-facebook',
            'provider': {
                'client_id': current_app.config['STORMPATH_SOCIAL']['FACEBOOK']['app_id'],
                'client_secret': current_app.config['STORMPATH_SOCIAL']['FACEBOOK']['app_secret'],
                'provider_id': Provider.FACEBOOK,
            },
        })

        # Now that we have a Facebook directory, we'll map it to our application
        # so it is active.
        asm = current_app.stormpath_manager.application.account_store_mappings.create({
            'application': current_app.stormpath_manager.application,
            'account_store': dir,
            'list_index': 99,
            'is_default_account_store': False,
            'is_default_group_store': False,
        })

        # Lastly, let's retry the Facebook login one more time.
        account = User.from_facebook(facebook_user['access_token'])

    # Now we'll log the new user into their account.  From this point on, this
    # Facebook user will be treated exactly like a normal Stormpath user!
    login_user(account, remember=True)

    return redirect(request.args.get('next') or current_app.config['STORMPATH_REDIRECT_URL'])
Example #39
0
def get_current_user():

    print("start")

    if session.get("id") is not None:

        # Set the user in the session dictionary as a global g.user and bail out
        # of this function early.
        if session.get("user"):
            print("revisit")
            g.user = session.get("user")
            print("g.user: "******"got g.user from session[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)
        print("result: " + str(result))
        # result: none - means there are no cookies from fb so user is not logged into fb

        #?      # see if user already has access_token for elif statement below
        #rows = db.execute("SELECT * FROM users WHERE id = :id", id=session["id"])

        # if there is no result, we assume the user is not logged into facebook
        if result:
            print("app user logged in to fb but it's not stored in session")

            # Check to see if there is already a row in database with that  user is already in FB by using result from cookie parsing
            # test id is '1139085602941741'
            user = db.execute("SELECT * FROM users WHERE user_id = :uid",
                              uid=result["uid"])
            print("user: "******"--fb id is already in db so check to see if access_token in db is valid--"
                )

                # when there's time, add a colum to db that has when the access_token expires and check to see if that that has passed before updating.
                # why? we can only extend the access token once a day so if we trade an extended for a short that's silly.
                # reference: https://groups.google.com/forum/#!searchin/pythonforfacebook/expired|sort:date/pythonforfacebook/Y-0DMMlSnFQ/wlYol5F3EXAJ

                if user[0]["access_token"] != result["access_token"]:
                    # fb user is already in db but new access_token does not match with one on file, so update
                    print(
                        "app user, " + str(session["id"]) +
                        ", HAS logged in w/ fb before but access_token is old so we've updated"
                    )

                    # If an existing user, update the access token
                    print("old access token: " + str(user[0]["access_token"]))
                    print("new access token: " + str(result["access_token"]))

                    # extend new access token
                    result["access_token"] = extend(result["access_token"],
                                                    FB_APP_ID, FB_APP_SECRET)

                    db.execute(
                        "UPDATE users SET access_token = :access WHERE id = :id",
                        access=result["access_token"],
                        id=session["id"])

            # user's fb id is not in db so get thier fbid and access token and add to the row associated with their app id
            else:
                print("first login w this fb id")
                graph = GraphAPI(result["access_token"])
                profile = graph.get_object("me")
                if "link" not in profile:
                    profile["link"] = ""

                # update database entry that exists for currently logged in user to store their fb info
                #if session.get('id'):
                old = db.execute("SELECT * FROM users WHERE id = :id",
                                 id=session["id"])
                print("User before update:" + str(old))
                db.execute(
                    "UPDATE users SET user_id = :uid, access_token = :access, profile_url = :profile, name = :name WHERE id = :id",
                    uid=str(profile["id"]),
                    access=extend(result["access_token"], FB_APP_ID,
                                  FB_APP_SECRET),
                    profile=profile["link"],
                    name=profile["name"],
                    id=session["id"])  # returns unique "id" of the user

            # else if statement to handle users with multiple app accounts (i.e. have many rows in db)

            # store user in session
            #if user:
            # select the user based on app_id so we can add them to a session
            user = db.execute("SELECT * FROM users WHERE id = :app_id",
                              app_id=session["id"])

            session["user"] = dict(
                name=user[0]["name"],
                profile_url=user[0]["profile_url"],
                user_id=user[0]["user_id"],
                access_token=user[0]["access_token"],
            )

        # If there is no result, we check if user is logging in from new computer
        '''
        elif rows[0]['access_token'] != None:
            print("inside user has an account and is on new device")
            session["user"] = dict(
                name=rows[0]["name"],
                profile_url=rows[0]["profile_url"],
                user_id=rows[0]["user_id"],
                access_token=rows[0]["access_token"],
            )
        '''
        # we assume the user is not logged in and set g.user to None or log in and set equal to user
        g.user = session.get("user", None)
        print(g.user)

    print("at end of get_current_user method")
Example #40
0
 def get_fb_args(self):
   if not hasattr(self, 'fb_args'):
     self.fb_args = facebook.get_user_from_cookie(
         self.request.cookies, config.FACEBOOK_APP_ID,
         config.FACEBOOK_APP_SECRET)
   return self.fb_args
Example #41
0
def getFacebookUserObj(request):
    return facebook.get_user_from_cookie(request.cookies,
                                         app.config['FACEBOOK_APP_ID'],
                                         app.config['FACEBOOK_APP_SECRET'])
Example #42
0
    def authenticate(self, request, user=None):
        cookie = facebook.get_user_from_cookie(request.COOKIES,
                                               FACEBOOK_APP_ID,
                                               FACEBOOK_SECRET_KEY)
        if cookie:
            uid = cookie['uid']
            access_token = cookie['access_token']
        else:
            # if cookie does not exist
            # assume logging in normal way
            params = {}
            params["client_id"] = FACEBOOK_APP_ID
            params["client_secret"] = FACEBOOK_SECRET_KEY
            params["redirect_uri"] = reverse(
                "socialauth_facebook_login_done")[1:]
            params["code"] = request.GET.get('code', '')

            url = ("https://graph.facebook.com/oauth/access_token?" +
                   urllib.urlencode(params))
            from cgi import parse_qs
            userdata = urllib.urlopen(url).read()
            res_parse_qs = parse_qs(userdata)
            # Could be a bot query
            if not res_parse_qs.has_key('access_token'):
                return None

            parse_data = res_parse_qs['access_token']
            uid = parse_data['uid'][-1]
            access_token = parse_data['access_token'][-1]

        try:
            fb_user = FacebookUserProfile.objects.get(facebook_uid=uid)
            return fb_user.user

        except FacebookUserProfile.DoesNotExist:

            # create new FacebookUserProfile
            graph = facebook.GraphAPI(access_token)
            fb_data = graph.get_object("me")

            if not fb_data:
                return None

            username = uid
            if not user:
                user = User.objects.create(username=username)
                user.first_name = fb_data['first_name']
                user.last_name = fb_data['last_name']
                user.email = fb_data.get('email')
                user.save()

            picture_url = 'http://graph.facebook.com/%s/picture' % uid
            fb_profile = FacebookUserProfile(
                facebook_uid=uid,
                user=user,
                profile_image_url=picture_url,
                profile_image_url_small=picture_url + '?type=small',
                profile_image_url_big=picture_url + '?type=large',
                about_me=fb_data.get('about'),
                url=fb_data.get('website'),
            )
            if 'location' in fb_data:
                fb_profile.location = fb_data['location']['name']

            fb_profile.save()

            auth_meta = AuthMeta(user=user, provider='Facebook').save()

            return user