def twitter(request):
	"""
	Actually setup/login an account relating to a twitter user after the oauth 
	process is finished successfully
	"""
	client = OAuthTwitter(
		request, settings.TWITTER_CONSUMER_KEY,
		settings.TWITTER_CONSUMER_SECRET_KEY,
		settings.TWITTER_REQUEST_TOKEN_URL,
	)
	
	user_info = client.get_user_info()

	user = authenticate(twitter_id=user_info['id'])
	if user is None:
		profile = TwitterProfile(twitter_id=user_info['id'])
		user = User(username='******')
		request.session['socialregistration_profile'] = profile
		request.session['socialregistration_user'] = user
		request.session['next'] = _get_next(request)
		return HttpResponseRedirect(reverse('socialregistration_setup'))
	
	login(request, user)
	
	return HttpResponseRedirect(getattr(settings, 'LOGIN_REDIRECT_URL', _get_next(request)))
Beispiel #2
0
def twitter(request):
    """
    Actually setup/login an account relating to a twitter user after the oauth 
    process is finished successfully
    """
    client = OAuthTwitter(
        request,
        settings.TWITTER_CONSUMER_KEY,
        settings.TWITTER_CONSUMER_SECRET_KEY,
        settings.TWITTER_REQUEST_TOKEN_URL,
    )

    user_info = client.get_user_info()

    user = authenticate(twitter_id=user_info['id'])

    if user is None:
        profile = TwitterProfile(twitter_id=user_info['id'], )
        user = User()
        request.session['socialregistration_profile'] = profile
        request.session['socialregistration_user'] = user
        request.session['next'] = _get_next(request)
        return HttpResponseRedirect(reverse('socialregistration_setup'))

    login(request, user)

    return HttpResponseRedirect(_get_next(request))
def twitter(request, account_inactive_template='socialregistration/account_inactive.html',
    extra_context=dict()):
    """
    Actually setup/login an account relating to a twitter user after the oauth 
    process is finished successfully
    """
    client = OAuthTwitter(
        request, settings.TWITTER_CONSUMER_KEY,
        settings.TWITTER_CONSUMER_SECRET_KEY,
        settings.TWITTER_REQUEST_TOKEN_URL,
    )
    
    user_info = client.get_user_info()

    user = authenticate(twitter_id=user_info['id'])
    
    if user is None:
        profile = TwitterProfile(twitter_id=user_info['id'],
                                 )
        user = User()
        request.session['socialregistration_profile'] = profile
        request.session['socialregistration_user'] = user
        request.session['next'] = _get_next(request)
        return HttpResponseRedirect(reverse('socialregistration_setup'))
    
    if not user.is_active:
        return render_to_response(
            account_inactive_template,
            extra_context,
            context_instance=RequestContext(request)
        )
    
    login(request, user)
    
    return HttpResponseRedirect(_get_next(request))
def twitter(request, account_inactive_template='socialregistration/account_inactive.html', extra_context=dict()):
    """
    Actually setup/login an account relating to a twitter user after the oauth
    process is finished successfully
    """
    client = OAuthTwitter(
        request, settings.TWITTER_CONSUMER_KEY,
        settings.TWITTER_CONSUMER_SECRET_KEY,
        settings.TWITTER_REQUEST_TOKEN_URL,
    )

    user_info = client.get_user_info()

    if request.user.is_authenticated():
        # Handling already logged in users connecting their accounts
        try:
            profile = TwitterProfile.all().filter('twitter_id = ',user_info['id']).fetch(1)[0]
        except IndexError: # There can only be one profile!
            profile = TwitterProfile(user=request.user, 
                twitter_id=user_info['id'], 
                username=user_info['screen_name'], 
                real_name=user_info['name'],
                pic_url = user_info['profile_image_url'],
            )
            profile.save()

        return HttpResponseRedirect(_get_next(request))

    user = authenticate(twitter_id=user_info['id'])

    if user is None:
        profile = TwitterProfile(                
            twitter_id=user_info['id'], 
            username=user_info['screen_name'], 
            real_name=user_info['name'],
            pic_url = user_info['profile_image_url'],
        )

        user = User(username=profile.real_name)
        request.session['social_suggested_username'] = user_info['screen_name']
        request.session['socialregistration_profile'] = profile
        request.session['socialregistration_user'] = user
        request.session['next'] = _get_next(request)
        return HttpResponseRedirect(reverse('socialregistration_setup'))

    if not user.is_active:
        return render_to_response(
            account_inactive_template,
            extra_context,
            context_instance=RequestContext(request)
        )

    login(request, user)

    return HttpResponseRedirect(_get_next(request))
def twitter(request, account_inactive_template='socialregistration/account_inactive.html',
    extra_context=dict()):
    """
    Actually setup/login an account relating to a twitter user after the oauth
    process is finished successfully
    """
    client = OAuthTwitter(
        request, settings.TWITTER_CONSUMER_KEY,
        settings.TWITTER_CONSUMER_SECRET_KEY,
        settings.TWITTER_REQUEST_TOKEN_URL,
    )

    user_info = client.get_user_info()

    try:
        profile = SocialProfile.objects.get(uid=user_info['id'], soc_type = ST_TWITTER)
    except SocialProfile.DoesNotExist: # There can only be one profile!
        profile = SocialProfile(
                uid=user_info['id'],
                username=user_info['screen_name'],
                avatar=user_info['profile_image_url'],
                soc_type=ST_TWITTER)
    else:
        profile.avatar = user_info['profile_image_url']
        profile.save()

    if request.user.is_authenticated():

        return HttpResponseRedirect(_get_next(request))

    user = authenticate(uid=user_info['id'], soc_type=ST_TWITTER)

    if user is None:
        name = user_info['name'].split(' ')
        user = User(first_name=name[0], last_name=name.pop())
        request.session['socialregistration_profile'] = profile
        request.session['socialregistration_user'] = user
        request.session['next'] = _get_next(request)
        return HttpResponseRedirect(reverse('socialregistration_setup'))

    if not user.is_active:
        return render_to_response(
            account_inactive_template,
            extra_context,
            context_instance=RequestContext(request)
        )

    login(request, user)

    return HttpResponseRedirect(_get_next(request))
def get_avatar(request, profile):
    avatar_url = None
    if profile.__class__.__name__ == 'FacebookProfile':
        avatar_url = request.facebook.users.getInfo([profile.uid], ['pic_square_with_logo'])[0]['pic_square_with_logo']
    elif profile.__class__.__name__ == 'TwitterProfile':
        client = OAuthTwitter(
            request, settings.TWITTER_CONSUMER_KEY,
            settings.TWITTER_CONSUMER_SECRET_KEY,
            settings.TWITTER_REQUEST_TOKEN_URL,
            )

        user_info = client.get_user_info()
        avatar_url = user_info['profile_image_url']

    return avatar_url
def twitter(request, account_inactive_template='socialregistration/account_inactive.html',
    extra_context=dict()):
    """
    Actually setup/login an account relating to a twitter user after the oauth
    process is finished successfully
    """
    client = OAuthTwitter(
        request, settings.TWITTER_CONSUMER_KEY,
        settings.TWITTER_CONSUMER_SECRET_KEY,
        settings.TWITTER_REQUEST_TOKEN_URL,
    )

    if not client.get_access_token_or_none():
        return HttpResponseRedirect(_get_next(request))

    user_info = client.get_user_info()

    if request.user.is_authenticated():
        # Handling already logged in users connecting their accounts
        try:
            profile = TwitterProfile.objects.get(twitter_id=user_info['id'])
        except TwitterProfile.DoesNotExist: # There can only be one profile!
            profile = TwitterProfile.objects.create(user=request.user,
                                                    twitter_id=user_info['id'])

        return successful_account_link(request, profile)

    user = authenticate(twitter_id=user_info['id'])

    if user is None:
        profile = TwitterProfile(twitter_id=user_info['id'],
                                 username=user_info['screen_name'])
        user = User()
        request.session['socialregistration_profile'] = profile
        request.session['socialregistration_user'] = user
        request.session['next'] = _get_next(request)
        return HttpResponseRedirect(reverse('socialregistration_setup'))

    if not user.is_active:
        return render_to_response(
            account_inactive_template,
            extra_context,
            context_instance=RequestContext(request)
        )

    login(request, user)

    return HttpResponseRedirect(_get_next(request))
Beispiel #8
0
def twitter(
        request,
        account_inactive_template='socialregistration/account_inactive.html',
        extra_context=None):
    """
    Actually setup/login an account relating to a twitter user after the oauth
    process is finished successfully
    """

    client = OAuthTwitter(
        request,
        settings.TWITTER_CONSUMER_KEY,
        settings.TWITTER_CONSUMER_SECRET_KEY,
        settings.TWITTER_REQUEST_TOKEN_URL,
    )

    user_info = client.get_user_info()

    if request.user.is_authenticated():
        # Handling already logged in users connecting their accounts
        try:
            profile = TwitterProfile.objects.get(twitter_id=user_info['id'])
        except TwitterProfile.DoesNotExist:  # There can only be one profile!
            profile = TwitterProfile.objects.create(user=request.user,
                                                    twitter_id=user_info['id'])

        return HttpResponseRedirect(_get_next(request))

    user = authenticate(twitter_id=user_info['id'])

    if user is None:
        profile = TwitterProfile(twitter_id=user_info['id'])
        user = User()
        request.session['socialregistration_profile'] = profile
        request.session['socialregistration_user'] = user
        request.session['next'] = _get_next(request)
        return HttpResponseRedirect(reverse('socialregistration_setup'))

    if not user.is_active:
        return render_to_response(account_inactive_template,
                                  extra_context,
                                  context_instance=RequestContext(request))

    login(request, user)

    return HttpResponseRedirect(_get_next(request))
def twitter(request, account_inactive_template='socialregistration/account_inactive.html',
    extra_context=dict()):
    """
    Actually setup/login an account relating to a twitter user after the oauth 
    process is finished successfully
    """
    client = OAuthTwitter(
        request, settings.TWITTER_CONSUMER_KEY,
        settings.TWITTER_CONSUMER_SECRET_KEY,
        settings.TWITTER_REQUEST_TOKEN_URL,
    )
    
    user_info = client.get_user_info()
    
    if request.user.is_authenticated():
        # Handling already logged in users connecting their accounts
        try:
            profile, created = TwitterProfile.objects.get_or_create(user=request.user, twitter_id=user_info['id'])
        except IntegrityError:
            request.user.message_set.create(message=_('This twitter account has already been connected to a user.'))
        return HttpResponseRedirect(_get_next(request))
    
    user = authenticate(twitter_id=user_info['id'])
    
    if user is None:
        profile = TwitterProfile(twitter_id=user_info['id'])
        user = User()
        request.session['socialregistration_profile'] = profile
        request.session['socialregistration_user'] = user
        request.session['next'] = _get_next(request)
        return HttpResponseRedirect(reverse('socialregistration_setup'))
    
    if not user.is_active:
        return render_to_response(
            account_inactive_template,
            extra_context,
            context_instance=RequestContext(request)
        )
    
    login(request, user)
    
    return HttpResponseRedirect(_get_next(request))
def twitter(request, account_inactive_template="socialregistration/account_inactive.html", extra_context=dict()):
    """
    Actually setup/login an account relating to a twitter user after the oauth
    process is finished successfully
    """
    client = OAuthTwitter(
        request,
        get_setting_for_current_site("TWITTER_CONSUMER_KEY"),
        get_setting_for_current_site("TWITTER_CONSUMER_SECRET_KEY"),
        get_setting_for_current_site("TWITTER_REQUEST_TOKEN_URL"),
    )

    user_info = client.get_user_info()

    if request.user.is_authenticated():
        # Handling already logged in users connecting their accounts
        try:
            profile = TwitterProfile.objects.get(twitter_id=user_info["id"])
        except TwitterProfile.DoesNotExist:  # There can only be one profile!
            profile = TwitterProfile.objects.create(user=request.user, twitter_id=user_info["id"])

        return HttpResponseRedirect(_get_next(request))

    user = authenticate(twitter_id=user_info["id"])

    if user is None:
        profile = TwitterProfile(twitter_id=user_info["id"])
        user = User()
        request.session["socialregistration_profile"] = profile
        request.session["socialregistration_user"] = user
        request.session["next"] = _get_next(request)
        return HttpResponseRedirect(reverse("socialregistration_setup"))

    if not user.is_active:
        return render_to_response(account_inactive_template, extra_context, context_instance=RequestContext(request))

    login(request, user)

    return HttpResponseRedirect(_get_next(request))
def socialregistration_friends(request,
    template_name='socialregistration/friends.html', extra_context=None):
    context = {}

    friends = []
    conditions = []
    user = request.user
    
    for facebookprofile in user.facebookprofile_set.all():
        print facebookprofile
        friendlist = request.facebook.graph.request(request.facebook.user['uid'] + '/friends')
        facebook_ids = [x['id'] for x in friendlist['data']]
        conditions.append(Q(facebookprofile__uid__in=facebook_ids))

    if user.twitterprofile_set.count():
        client = OAuthTwitter(
            request, settings.TWITTER_CONSUMER_KEY,
            settings.TWITTER_CONSUMER_SECRET_KEY,
            settings.TWITTER_REQUEST_TOKEN_URL,
        )
    for twitterprofile in user.twitterprofile_set.all():
        res = simplejson.loads(client.query('http://api.twitter.com/1/statuses/friends.json'))
        twitter_ids = [x['id'] for x in res]
        conditions.append(Q(twitterprofile__twitter_id__in=twitter_ids))

    for gfcprofile in user.gfcprofile_set.all():
        container = gfc.my_opensocial_container(request)
        res = container.fetch_friends()
        gfc_ids = [x['id'] for x in res]
        conditions.append(Q(gfcprofile__uid__in=gfc_ids))

    context['friends'] = User.objects.filter(reduce(operator.or_,conditions))
    context['follows'] = [f.actor for f in user.follow_set.all()]

    context.update(extra_context or {})
    return shortcuts.render_to_response(template_name, context,
        context_instance=template.RequestContext(request))
def twitter(request):
    """
    Actually setup/login an account relating to a twitter user after the oauth 
    process is finished successfully
    """
    client = OAuthTwitter(
        request, settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET_KEY, settings.TWITTER_REQUEST_TOKEN_URL
    )

    user_info = client.get_user_info()

    user = authenticate(twitter_id=user_info["id"])

    if user is None:
        profile = TwitterProfile(twitter_id=user_info["id"])
        user = User()
        request.session["socialregistration_profile"] = profile
        request.session["socialregistration_user"] = user
        request.session["next"] = _get_next(request)
        return HttpResponseRedirect(reverse("socialregistration_setup"))

    login(request, user)

    return HttpResponseRedirect(_get_next(request))
def twitter(
    request,
    account_inactive_template='socialregistration/account_inactive.html',
    extra_context=dict()):
    """
    Actually setup/login an account relating to a twitter user after the oauth
    process is finished successfully
    """

    client = OAuthTwitter(
        request,
        settings.TWITTER_CONSUMER_KEY,
        settings.TWITTER_CONSUMER_SECRET_KEY,
        settings.TWITTER_REQUEST_TOKEN_URL,
    )

    user_info = client.get_user_info()

    try:
        oauth_token = request.session['oauth_api.twitter.com_access_token'][
            'oauth_token']
    except KeyError:
        try:
            oauth_token = request.session['oauth_twitter.com_access_token'][
                'oauth_token']
        except:
            oauth_token = ''
    try:
        oauth_token_secret = request.session[
            'oauth_api.twitter.com_access_token']['oauth_token_secret']
    except KeyError:
        try:
            oauth_token_secret = request.session[
                'oauth_twitter.com_access_token']['oauth_token_secret']
        except:
            oauth_token_secret = ''

    if 'socialregistration_connect_object' in request.session and request.session[
            'socialregistration_connect_object'] != None:
        # this exists so that social credentials can be attached to any arbitrary object using the same callbacks.
        # Under normal circumstances it will not be used. Put an object in request.session named 'socialregistration_connect_object' and it will be used instead.
        # After the connection is made it will redirect to request.session value 'socialregistration_connect_redirect' or settings.LOGIN_REDIRECT_URL or /
        try:
            # get the profile for this Twitter ID and type of connected object
            profile = TwitterProfile.objects.get(
                twitter_id=user_info['id'],
                content_type=ContentType.objects.get_for_model(
                    request.session['socialregistration_connect_object'].
                    __class__),
                object_id=request.session['socialregistration_connect_object'].
                pk)
        except TwitterProfile.DoesNotExist:
            TwitterProfile.objects.create(content_object=request.session['socialregistration_connect_object'], twitter_id=user_info['id'], \
                screenname=user_info['screen_name'], consumer_key=oauth_token, consumer_secret=oauth_token_secret)

        del request.session['socialregistration_connect_object']
    else:
        if request.user.is_authenticated():
            # Handling already logged in users connecting their accounts
            try:
                profile = TwitterProfile.objects.get(
                    twitter_id=user_info['id'],
                    content_type=ContentType.objects.get_for_model(User))
            except TwitterProfile.DoesNotExist:  # There can only be one profile!
                profile = TwitterProfile.objects.create(
                    content_object=request.user,
                    twitter_id=user_info['id'],
                    screenname=user_info['screen_name'],
                    consumer_key=oauth_token,
                    consumer_secret=oauth_token_secret)

            return HttpResponseRedirect(_get_next(request))

        user = authenticate(twitter_id=user_info['id'])

        if user is None:
            request.session['socialregistration_profile'] = TwitterProfile(
                twitter_id=user_info['id'],
                screenname=user_info['screen_name'],
                consumer_key=oauth_token,
                consumer_secret=oauth_token_secret)
            request.session['socialregistration_user'] = User()
            request.session['next'] = _get_next(request)
            return HttpResponseRedirect(reverse('socialregistration_setup'))

        if not user.is_active:
            return render_to_response(account_inactive_template,
                                      extra_context,
                                      context_instance=RequestContext(request))

        login(request, user)

    return HttpResponseRedirect(_get_next(request))
def twitter(request, account_inactive_template='socialregistration/account_inactive.html',
    extra_context=dict()):
    """
    Actually setup/login an account relating to a twitter user after the oauth
    process is finished successfully
    """

    client = OAuthTwitter(
        request, settings.TWITTER_CONSUMER_KEY,
        settings.TWITTER_CONSUMER_SECRET_KEY,
        settings.TWITTER_REQUEST_TOKEN_URL,
    )

    user_info = client.get_user_info()

    try:
        oauth_token = request.session['oauth_api.twitter.com_access_token']['oauth_token']
    except KeyError:
        try:
            oauth_token = request.session['oauth_twitter.com_access_token']['oauth_token']
        except:
            oauth_token = ''
    try:
        oauth_token_secret = request.session['oauth_api.twitter.com_access_token']['oauth_token_secret']
    except KeyError:
        try:
            oauth_token_secret = request.session['oauth_twitter.com_access_token']['oauth_token_secret']
        except:
            oauth_token_secret = ''

    if 'socialregistration_connect_object' in request.session and request.session['socialregistration_connect_object'] != None:
        # this exists so that social credentials can be attached to any arbitrary object using the same callbacks.
        # Under normal circumstances it will not be used. Put an object in request.session named 'socialregistration_connect_object' and it will be used instead.
        # After the connection is made it will redirect to request.session value 'socialregistration_connect_redirect' or settings.LOGIN_REDIRECT_URL or /
        try:
            # get the profile for this Twitter ID and type of connected object
            profile = TwitterProfile.objects.get(twitter_id=user_info['id'], content_type=ContentType.objects.get_for_model(request.session['socialregistration_connect_object'].__class__), object_id=request.session['socialregistration_connect_object'].pk)
        except TwitterProfile.DoesNotExist:
            TwitterProfile.objects.create(content_object=request.session['socialregistration_connect_object'], twitter_id=user_info['id'], \
                screenname=user_info['screen_name'], consumer_key=oauth_token, consumer_secret=oauth_token_secret)

        del request.session['socialregistration_connect_object']
    else:
        if request.user.is_authenticated():
            # Handling already logged in users connecting their accounts
            try:
                profile = TwitterProfile.objects.get(twitter_id=user_info['id'], content_type=ContentType.objects.get_for_model(User))
            except TwitterProfile.DoesNotExist: # There can only be one profile!
                profile = TwitterProfile.objects.create(content_object=request.user, twitter_id=user_info['id'], screenname=user_info['screen_name'], consumer_key=oauth_token, consumer_secret=oauth_token_secret)

            return HttpResponseRedirect(_get_next(request))

        user = authenticate(twitter_id=user_info['id'])

        if user is None:
            request.session['socialregistration_profile'] = TwitterProfile(twitter_id=user_info['id'], screenname=user_info['screen_name'], consumer_key=oauth_token, consumer_secret=oauth_token_secret)
            request.session['socialregistration_user'] = User()
            request.session['next'] = _get_next(request)
            return HttpResponseRedirect(reverse('socialregistration_setup'))

        if not user.is_active:
            return render_to_response(
                account_inactive_template,
                extra_context,
                context_instance=RequestContext(request)
            )

        login(request, user)

    return HttpResponseRedirect(_get_next(request))
def socialregistration_userdata(request, form_class=UserDataForm,
    template_name='socialregistration/userdata.html', extra_context=None):
    context = {}

    if 'socialregistration_profile' in request.session:
        profile = request.session['socialregistration_profile']
        user = request.session['socialregistration_user']
    elif request.user.is_authenticated():
        if request.user.facebookprofile_set.count():
            profile = request.user.facebookprofile_set.all()[0]
        elif request.user.twitterprofile_set.count():
            profile = request.user.twitterprofile_set.all()[0]
        if request.user.gfcprofile_set.count():
            profile = request.user.gfcprofile_set.all()[0]
        user = request.user
    else:
        return http.HttpResponseRedirect(urlresolvers.reverse(
            'acct_signup'))

    if request.method == 'POST':
        form = form_class(request.POST)
        if form.is_valid():
            request.session['socialregistration_userdata'] = form.cleaned_data
            
            user = request.session['socialregistration_user']
            profile = request.session['socialregistration_profile']
            userdata = request.session['socialregistration_userdata']

            user.first_name = userdata.get('first_name', '')
            user.last_name = userdata.get('last_name', '')
            user.email = userdata.get('email', '')
            user_slug = defaultfilters.slugify('%s %s' % (
                user.first_name,
                user.last_name
            ))
            if User.objects.filter(username=user_slug).count() > 0:
                i = 1
                user_slug_test = user_slug + unicode(i)
                while User.objects.filter(username=user_slug_test).count() >0:
                    i += 1
                    user_slug_test = user_slug + str(i)
                user.username = user_slug_test
            else:
                user.username = user_slug
            user.save()

            user.playlistprofile.user_location = userdata.get('location', '')
            user.playlistprofile.avatar_url = userdata.get('avatar_url', '')
            user.playlistprofile.user = user
            user.playlistprofile.save()

            profile.user = user
            profile.avatar_url = userdata.get('avatar_url', '')
            profile.url = userdata.get('url', '')
            profile.nick = userdata.get('nick', '')
            profile.save()

            if 'socialregistration_user' in request.session: 
                del request.session['socialregistration_user']
            if 'socialregistration_profile' in request.session: 
                del request.session['socialregistration_profile']
            if 'socialregistration_userdata' in request.session: 
                del request.session['socialregistration_userdata']

            user = profile.authenticate()
            auth.login(request, user)
            request.user = user

            if not user:
                logger.info('NOT USER IN REGISTRATION!')
                return shortcuts.render_to_response('socialregistration/fail.html', context,
                    context_instance=template.RequestContext(request))

            friends = []
            conditions = []
            
            for facebookprofile in user.facebookprofile_set.all():
                print facebookprofile
                friendlist = request.facebook.graph.request(request.facebook.user['uid'] + '/friends')
                facebook_ids = [x['id'] for x in friendlist['data']]
                conditions.append(Q(facebookprofile__uid__in=facebook_ids))

            if user.twitterprofile_set.count():
                client = OAuthTwitter(
                    request, settings.TWITTER_CONSUMER_KEY,
                    settings.TWITTER_CONSUMER_SECRET_KEY,
                    settings.TWITTER_REQUEST_TOKEN_URL,
                )
            for twitterprofile in user.twitterprofile_set.all():
                res = simplejson.loads(client.query('http://api.twitter.com/1/statuses/friends.json'))
                twitter_ids = [x['id'] for x in res]
                conditions.append(Q(twitterprofile__twitter_id__in=twitter_ids))

            for gfcprofile in user.gfcprofile_set.all():
                container = gfc.my_opensocial_container(request)
                res = container.fetch_friends()
                gfc_ids = [x['id'] for x in res]
                conditions.append(Q(gfcprofile__uid__in=gfc_ids))
            
            for u in User.objects.filter(reduce(operator.or_,conditions)):
                follow(user, u)

            return http.HttpResponseRedirect(urlresolvers.reverse('socialregistration_friends'))
    else:
        if profile.__class__.__name__ == 'FacebookProfile':
            upstream = request.facebook.graph.request(request.facebook.user['uid'])
            initial = {
                'first_name': upstream.get('first_name', ''),
                'last_name': upstream.get('last_name', ''),
                'email': upstream.get('email', ''),
                'avatar_url': 'http://graph.facebook.com/%s/picture' % request.facebook.user['uid'],
                'nick': '%s %s' % (upstream.get('first_name', ''), upstream.get('last_name', '')),
                'url': upstream.get('link', ''),
            }
            if 'location' in upstream:
                initial['location'] = upstream['location']['name']
            else:   
                initial['location'] = ''

        elif profile.__class__.__name__ == 'TwitterProfile':
            client = OAuthTwitter(
                request, settings.TWITTER_CONSUMER_KEY,
                settings.TWITTER_CONSUMER_SECRET_KEY,
                settings.TWITTER_REQUEST_TOKEN_URL,
            )
            upstream = client.get_user_info()
            initial = {
                'first_name': '',
                'last_name': upstream.get('name', ''),
                'location': upstream.get('location', ''),
                'email': '',
                'avatar_url': upstream['profile_image_url'],
                'url': 'http://twitter.com/%s' % upstream['screen_name'],
                'nick': upstream['screen_name'],
            }

        elif profile.__class__.__name__ == 'GfcProfile':
            container = gfc.my_opensocial_container(request)
            req = opensocial.FetchPersonRequest(profile.uid, ['@all'])
            upstream = container.send_request(req)
            initial = {
                'first_name': upstream.get('displayName', ''),
                'last_name': '',
                'location': '',
                'email': '',
                'avatar_url': upstream['thumbnailUrl'],
                'url': upstream['urls'][0]['value'],
                'nick': upstream['displayName'],
            }
        form = form_class(initial=initial)

    context['form'] = form
    context['step'] = 'userdata'

    context.update(extra_context or {})
    return shortcuts.render_to_response(template_name, context,
        context_instance=template.RequestContext(request))
Beispiel #16
0
def music_recommendation_add(request, form_class=RecommendationForm,
    template_name='music/recommendation_add.html', extra_context=None):

    if not request.user.is_authenticated():
        return http.HttpResponseForbidden('please authenticate')

    context = {
        'track_name': request.REQUEST.get('track_name', ''),
        'artist_name': request.REQUEST.get('artist_name', ''),
        'target_pk_list': request.REQUEST.get('target_pk_list', ''),
        'track': None,
        'friend_pk': request.REQUEST.get('user_pk', ''),
    }

    context['track'] = get_or_fake_track(context['track_name'], context['artist_name'])

    if request.method == 'POST' and context['track']:
        if request.GET.get('method', False) == 'facebook':
            request.facebook.graph.put_wall_post(request.POST.get('message').encode('utf-8'))
            msg = 'thanks for sharing <a href="%s">%s</a> on Facebook' % (
                context['track'].get_absolute_url(),
                unicode(context['track']),
            )
            return http.HttpResponse(msg, status=201)
        elif request.GET.get('method', False) == 'twitter':
            session_key = 'oauth_%s_access_token' % get_token_prefix(settings.TWITTER_REQUEST_TOKEN_URL)
            if session_key in request.session.keys():
                restore = request.session[session_key]
            else:
                restore = None

            for twitterprofile in request.user.twitterprofile_set.all():
                request.session[session_key] = {
                    'oauth_token_secret': twitterprofile.token_secret, 
                    'oauth_token': twitterprofile.access_token, 
                    'user_id': twitterprofile.user_id,
                    'screen_name': twitterprofile.nick,
                }
                client = OAuthTwitter(
                    request, settings.TWITTER_CONSUMER_KEY,
                    settings.TWITTER_CONSUMER_SECRET_KEY,
                    settings.TWITTER_REQUEST_TOKEN_URL,
                )
                client.query('http://api.twitter.com/1/statuses/update.json', 'POST', {'status': request.POST.get('message').encode('utf-8')})
            
            if restore:
                request.session[session_key] = restore
            else:
                del request.session[session_key]

            msg = 'thanks for sharing <a href="%s">%s</a> on Twitter' % (
                context['track'].get_absolute_url(),
                unicode(context['track']),
            )
            return http.HttpResponse(msg, status=201)
        else:
            form = form_class(request.POST, instance=Recommendation(source=request.user, track=context['track']))
            if form.is_valid():
                save_if_fake_track(context['track'])
                form.instance.track = context['track']
                recommendation = form.save()
                action.send(request.user, verb='recommends', action_object=recommendation)
                msg = 'thanks for recommending <a href="%s">%s</a> to <a href="%s">%s %s</a>' % (
                    recommendation.track.get_absolute_url(),
                    unicode(recommendation.track),
                    recommendation.target.playlistprofile.get_absolute_url(),
                    unicode(recommendation.target.first_name),
                    unicode(recommendation.target.last_name),
                )
                return http.HttpResponse(msg, status=201)
            else:
                print form.errors
    else:
        form = form_class()

    base = 'http://%s' % request.META.get('HTTP_HOST', 'http://playlistnow.fm')
    profiles = request.user.twitterprofile_set.all()
    if profiles:
        context['twitterprofile'] = profiles[0]
        context['twitterurl'] = shorten_url(base+context['track'].get_absolute_url())
    profiles = request.user.facebookprofile_set.all()
    if profiles:
        context['facebookprofile'] = profiles[0]
        context['facebookurl'] = base+context['track'].get_absolute_url()

    context.update(extra_context or {})
    return shortcuts.render_to_response(template_name, context,
        context_instance=template.RequestContext(request))
def twitter(request, account_inactive_template='socialregistration/account_inactive.html',
    extra_context=dict()):
    """
    Actually setup/login an account relating to a twitter user after the oauth
    process is finished successfully
    """

    client = OAuthTwitter(
        request, settings.TWITTER_CONSUMER_KEY,
        settings.TWITTER_CONSUMER_SECRET_KEY,
        settings.TWITTER_REQUEST_TOKEN_URL,
    )

    user_info = client.get_user_info()
    logger.debug("User info known about user from Twitter: %s" % user_info)

    try:
        oauth_token = request.session['oauth_api.twitter.com_access_token']['oauth_token']
    except KeyError:
        try:
            oauth_token = request.session['oauth_twitter.com_access_token']['oauth_token']
        except:
            oauth_token = ''
    try:
        oauth_token_secret = request.session['oauth_api.twitter.com_access_token']['oauth_token_secret']
    except KeyError:
        try:
            oauth_token_secret = request.session['oauth_twitter.com_access_token']['oauth_token_secret']
        except:
            oauth_token_secret = ''

    logger.debug("Received token: %s / Secret: %s" % (oauth_token, oauth_token_secret))

    if 'socialregistration_connect_object' in request.session and request.session['socialregistration_connect_object'] != None:
        logger.debug("Object to be connected to: %s" % request.session['socialregistration_connect_object'])
        # this exists so that social credentials can be attached to any arbitrary object using the same callbacks.
        # Under normal circumstances it will not be used. Put an object in request.session named 'socialregistration_connect_object' and it will be used instead.
        # After the connection is made it will redirect to request.session value 'socialregistration_connect_redirect' or settings.LOGIN_REDIRECT_URL or /
        try:
            # get the profile for this Twitter ID and type of connected object
            profile = TwitterProfile.objects.get(twitter_id=user_info['id'], content_type=ContentType.objects.get_for_model(request.session['socialregistration_connect_object'].__class__), object_id=request.session['socialregistration_connect_object'].pk)
            logger.debug("Found Twitter Profile for %s, Twitter User ID %s" % (request.session['socialregistration_connect_object'], user_info['id']))
        except TwitterProfile.DoesNotExist:
            TwitterProfile.objects.create(content_object=request.session['socialregistration_connect_object'], twitter_id=user_info['id'], \
                screenname=user_info['screen_name'], consumer_key=oauth_token, consumer_secret=oauth_token_secret)
            logger.debug("Created Twitter Profile for %s, Twitter User ID %s / screen name %s" % (request.session['socialregistration_connect_object'], user_info['id'], user_info['screen_name']))

        del request.session['socialregistration_connect_object']
    else:
        logger.debug("No connection object found, will use currently logged in user instead.")
        if request.user.is_authenticated():
            # Handling already logged in users connecting their accounts
            try:
                profile = TwitterProfile.objects.get(twitter_id=user_info['id'], content_type=ContentType.objects.get_for_model(User))
            except TwitterProfile.DoesNotExist:  # There can only be one profile!
                profile = TwitterProfile.objects.create(content_object=request.user, twitter_id=user_info['id'], screenname=user_info['screen_name'], consumer_key=oauth_token, consumer_secret=oauth_token_secret)

            logger.debug("Redirecting user to %s after matching up a Twitter Profile." % _get_next(request))
            return HttpResponseRedirect(_get_next(request))

        user = authenticate(twitter_id=user_info['id'])

        if user is None:
            request.session['socialregistration_profile'] = TwitterProfile(twitter_id=user_info['id'], screenname=user_info['screen_name'], consumer_key=oauth_token, consumer_secret=oauth_token_secret)
            request.session['socialregistration_user'] = User()
            request.session['next'] = _get_next(request)
            logger.info("No user found / authentication failed for Twitter ID %s, sending to %s to login, will send to %s after login." % (user_info['id'], reverse('socialregistration_setup'), request.session['next']))
            return HttpResponseRedirect(reverse('socialregistration_setup'))

        if not user.is_active:
            logger.info("The user logging in is marked inactive. Alerting them to this.")
            return render_to_response(
                account_inactive_template,
                extra_context,
                context_instance=RequestContext(request)
            )

        login(request, user)

    next_url = _get_next(request)  # IF the next url is coming from session, the method removes it and makes the next call default to the profile view. So the log reads right, but the user goes to the wrong place.
    logger.info("Falling back, redirecting user to %s" % next_url)
    return HttpResponseRedirect(next_url)