Ejemplo n.º 1
0
def user_friends(request, username):
    """
    Returns list of friends for user on Facebook that exists in TangleOn    
    """    
    if request.app_user.username != username or not hasattr(request.app_user, 'fbuser'):
        return HttpResponseRedirect(reverse('app_user', args=[request.app_user.username]))
    
    fbuser = request.app_user.fbuser
    return_next = request.GET.get('next', reverse('app_index'))
    if request.method == 'GET':
        if fbuser.access_expiry < datetime.datetime.now():
            params = urllib.urlencode({'client_id': settings.FB_APP_ID,
                                   'response_type': 'code',
                                   'redirect_uri': request.build_absolute_uri(request.path),
                                   'state': return_next
                                   })        
            return HttpResponseRedirect(settings.FB_AUTH_URL + '?' + params)
            
        
        params = urllib.urlencode({'access_token': fbuser.access_token,
                                   'fields': 'id,username,name',
                                   'limit': '1000'})        
        try:
            friends_json = simplejson.loads(scraper.get_content(settings.FB_GRAPH_FRIENDS + '?' + params))['data']
            
            if not len(friends_json):
                return HttpResponseRedirect(request.GET.get('next', reverse('app_index')))
                            
            friendids = list(int(friend['id']) for friend in friends_json)
            friends = list(FbUser.objects.select_related('user').filter(fb_id__in=friendids))
            if len(friends):
                for follow in Follow.objects.filter(follower_id=request.app_user.user_id,following_id__in=list(friend.user_id for friend in friends)):
                    for friend in friends:
                        if friend.user_id == follow.following_id:
                            friend.follow = follow
                            break
                                    
                return render_response(request, 'app/friends.html', locals())
            
            return HttpResponseRedirect(return_next)
        except Exception as e:
            logger.exception(e)
            return render_response(request, 'app/friends.html', {'error': 'We are unable to load your friends list from your Facebook account, please try again later.'})
            
    return HttpResponseRedirect(reverse('app_index'))
Ejemplo n.º 2
0
def user_friends(request, username):
    """
    Returns list of friends for user on Facebook that exists in TangleOn    
    """
    if request.app_user.username != username or not hasattr(
            request.app_user, 'fbuser'):
        return HttpResponseRedirect(
            reverse('app_user', args=[request.app_user.username]))

    fbuser = request.app_user.fbuser
    return_next = request.GET.get('next', reverse('app_index'))
    if request.method == 'GET':
        if fbuser.access_expiry < datetime.datetime.now():
            params = urllib.urlencode({
                'client_id':
                settings.FB_APP_ID,
                'response_type':
                'code',
                'redirect_uri':
                request.build_absolute_uri(request.path),
                'state':
                return_next
            })
            return HttpResponseRedirect(settings.FB_AUTH_URL + '?' + params)

        params = urllib.urlencode({
            'access_token': fbuser.access_token,
            'fields': 'id,username,name',
            'limit': '1000'
        })
        try:
            friends_json = simplejson.loads(
                scraper.get_content(settings.FB_GRAPH_FRIENDS + '?' +
                                    params))['data']

            if not len(friends_json):
                return HttpResponseRedirect(
                    request.GET.get('next', reverse('app_index')))

            friendids = list(int(friend['id']) for friend in friends_json)
            friends = list(
                FbUser.objects.select_related('user').filter(
                    fb_id__in=friendids))
            if len(friends):
                for follow in Follow.objects.filter(
                        follower_id=request.app_user.user_id,
                        following_id__in=list(friend.user_id
                                              for friend in friends)):
                    for friend in friends:
                        if friend.user_id == follow.following_id:
                            friend.follow = follow
                            break

                return render_response(request, 'app/friends.html', locals())

            return HttpResponseRedirect(return_next)
        except Exception as e:
            logger.exception(e)
            return render_response(
                request, 'app/friends.html', {
                    'error':
                    'We are unable to load your friends list from your Facebook account, please try again later.'
                })

    return HttpResponseRedirect(reverse('app_index'))
Ejemplo n.º 3
0
def facebook_login(request):
    """
    Login user through Facebook
    """
    if request.method == 'POST':
        params = urllib.urlencode({
            'client_id':
            settings.FB_APP_ID,
            'response_type':
            'code',
            'redirect_uri':
            request.build_absolute_uri(request.path),
            'state':
            request.POST.get('next',
                             reverse('app_index')),  # redirect uri for user
            'scope':
            'email'
        })

        return HttpResponseRedirect(settings.FB_AUTH_URL + '?' + params)

    code = request.GET.get('code', None)
    if not code:
        error = request.GET.get('error', None)
        error_reason = request.GET.get('error_reason', None)
        if error == 'access_denied' and error_reason == 'user_denied':
            return render_response(
                request, 'app/facebook_login.html', {
                    'error':
                    'You must allow TangleOn to access your basic information from Facebook.'
                })

        logger.error('Error occurred while signing user through Facebook.\n' +
                     str(request))
        return render_response(
            request, 'app/facebook_login.html', {
                'error':
                'We encounter some error while logging you in through Facebook.'
            })

    return_url = request.GET['state']
    code = request.GET['code']
    params = urllib.urlencode({
        'client_id':
        settings.FB_APP_ID,
        'client_secret':
        settings.FB_APP_SECRET,
        'redirect_uri':
        request.build_absolute_uri(request.path),
        'code':
        code
    })

    try:
        access_content = scraper.get_content(settings.FB_ACCESS_TOKEN + '?' +
                                             params)
        access_content = dict(urlparse.parse_qsl(access_content))
        access_token = access_content['access_token']
        access_expiry = datetime.datetime.now() + datetime.timedelta(
            seconds=int(access_content['expires']))
        request.session['facebook_access_token'] = access_token
        params = urllib.urlencode({
            'access_token': access_token,
            'fields': 'id,username,email,name'
        })

        fb_user = scraper.get_content(settings.FB_GRAPH_ME + '?' + params)
        fb_user = simplejson.loads(fb_user)
        try:
            if request.app_user.is_authenticated():
                user = request.app_user
                created = FbUser.connect_user(user, fb_user['id'],
                                              fb_user['name'],
                                              fb_user['username'],
                                              fb_user.get('email', user.email),
                                              access_token, access_expiry)
                if created:
                    FlashMessage.add_success(
                        'Your Facebook account is successfully connected.',
                        user)
            else:
                if not 'email' in fb_user:
                    raise TangleOnError(
                        'You need to allow TangleOn for access of your email address on Facebook, please read our privacy <a href="%s">policy</a> for any concern.'
                        % reverse('app_policy'))
                created, user = FbUser.get_user_or_create(
                    fb_user['id'], fb_user['name'], fb_user['username'],
                    fb_user['email'], access_token, access_expiry)
                if not user.is_active:
                    raise TangleOnError(
                        'Your account has been disabled. We apologize for any inconvenience! If this is a mistake please contact our <a href="mailto:[email protected]">support</a>.'
                    )
                login_user(request, user)
                if created:
                    FlashMessage.add_success(
                        'You have successfully signed up with Facebook account.',
                        user)
                else:
                    FlashMessage.add_info('Welcome back, ' + user.username,
                                          user)

            if created:
                return HttpResponseRedirect(
                    reverse('app_user_friends', args=[user.username]) + '?' +
                    urllib.urlencode({'next': return_url}))

            return HttpResponseRedirect(return_url)
        except TangleOnError as e:
            return render_response(request, 'app/facebook_login.html',
                                   {'error': e.message})
    except Exception as e:
        logger.exception(e)
        return render_response(
            request, 'app/facebook_login.html', {
                'error':
                'We encounter some error while logging you in through Facebook.'
            })

    return HttpResponseRedirect(reverse('app_index'))
Ejemplo n.º 4
0
def facebook_login(request):
    """
    Login user through Facebook
    """
    if request.method == 'POST':
        params = urllib.urlencode({'client_id': settings.FB_APP_ID,
                                   'response_type': 'code',
                                   'redirect_uri': request.build_absolute_uri(request.path),
                                   'state': request.POST.get('next', reverse('app_index')), # redirect uri for user
                                   'scope': 'email'
                                   })
        
        return HttpResponseRedirect(settings.FB_AUTH_URL + '?' + params)
    
    code = request.GET.get('code', None)
    if not code:
        error = request.GET.get('error', None)
        error_reason = request.GET.get('error_reason', None)
        if error == 'access_denied' and error_reason == 'user_denied':
            return render_response(request, 'app/facebook_login.html', {'error': 'You must allow TangleOn to access your basic information from Facebook.'})
            
        logger.error('Error occurred while signing user through Facebook.\n' + str(request))    
        return render_response(request, 'app/facebook_login.html', {'error': 'We encounter some error while logging you in through Facebook.'})
            
    return_url = request.GET['state']
    code = request.GET['code']
    params = urllib.urlencode({'client_id': settings.FB_APP_ID, 
                               'client_secret': settings.FB_APP_SECRET,
                               'redirect_uri': request.build_absolute_uri(request.path),
                               'code': code })
    
    try:        
        access_content = scraper.get_content(settings.FB_ACCESS_TOKEN + '?' + params)    
        access_content = dict(urlparse.parse_qsl(access_content))
        access_token = access_content['access_token']
        access_expiry = datetime.datetime.now() + datetime.timedelta(seconds=int(access_content['expires']))
        request.session['facebook_access_token'] = access_token      
        params = urllib.urlencode({'access_token': access_token,
                                   'fields': 'id,username,email,name'})
        
        fb_user = scraper.get_content(settings.FB_GRAPH_ME + '?' + params)
        fb_user = simplejson.loads(fb_user)
        try:
            if request.app_user.is_authenticated():
                user = request.app_user
                created = FbUser.connect_user(user, fb_user['id'], fb_user['name'], fb_user['username'], fb_user.get('email', user.email), access_token, access_expiry)
                if created:
                    FlashMessage.add_success('Your Facebook account is successfully connected.', user)
            else:
                if not 'email' in fb_user:
                    raise TangleOnError('You need to allow TangleOn for access of your email address on Facebook, please read our privacy <a href="%s">policy</a> for any concern.' % reverse('app_policy'))
                created, user = FbUser.get_user_or_create(fb_user['id'], fb_user['name'], fb_user['username'], fb_user['email'], access_token, access_expiry)
                if not user.is_active:
                    raise TangleOnError('Your account has been disabled. We apologize for any inconvenience! If this is a mistake please contact our <a href="mailto:[email protected]">support</a>.')
                login_user(request, user)
                if created:
                    FlashMessage.add_success('You have successfully signed up with Facebook account.', user)
                else:
                    FlashMessage.add_info('Welcome back, ' + user.username, user)

            if created:        
                return HttpResponseRedirect(reverse('app_user_friends', args=[user.username]) + '?' + urllib.urlencode({ 'next': return_url}))        
            
            return HttpResponseRedirect(return_url)            
        except TangleOnError as e:
            return render_response(request, 'app/facebook_login.html', {'error': e.message })
    except Exception as e:
        logger.exception(e)
        return render_response(request, 'app/facebook_login.html', {'error': 'We encounter some error while logging you in through Facebook.' })
    
    return HttpResponseRedirect(reverse('app_index'))