Esempio n. 1
0
def save_open_profile(user, open_profile, amqp_headers=None):
    from twitter.models import TwitterProfile
    from registration.utils import copy_avatar_from_url_to_profile, is_sso_email
    if not open_profile:
        return
    p_type = open_profile['profile_type']
    user_profile = user.get_profile()
    if p_type in settings.INSTALLED_APPS:
        if p_type == 'twitter':
            profile = user_profile.twitter_profile
            created = False
            if not profile:
                profile = TwitterProfile(user_profile=user_profile)
                created = True
            profile.created = created
            profile.screen_name = open_profile['screen_name']
            profile.appuser_id = unicode(open_profile['appuser_id'])
            profile.access_token = open_profile['access_token']
            profile.save(amqp_headers=amqp_headers)
            # If user doesn't have a first and last name, set them from the open_profile
            user_changed = False
            if not user.first_name:
                user.first_name = open_profile['first_name']
                user_changed = True
            if not user.last_name:
                user.last_name = open_profile['last_name']
                user_changed = True
            if user_changed:
                user.save()
            if not user_profile.avatar_medium and 'profile_image_url' in open_profile:
                # grab twitter profile image
                url = open_profile['profile_image_url']
                copy_avatar_from_url_to_profile(url, user_profile, commit=True)
            return profile
    return None
Esempio n. 2
0
    def save_profile_image(self, user_profile, commit=True):
        """Save avatar image if one was uploaded.

        If `commit` is True, save the profile instance.

        Return the given user_profile instance.

        """
        avatar_img = self.cleaned_data.get('image', None)
        img_updated = False
        if avatar_img:
            avatar_img_field = user_profile._meta.get_field('avatar_image')
            avatar_img_field.save_form_data(user_profile, avatar_img)
            img_updated = True
        elif self.open_profile and self.open_profile['profile_image_url']:
            # Download and use Twitter profile image
            url = self.open_profile.get('profile_image_url', None)
            copy_avatar_from_url_to_profile(url, user_profile, commit=commit)
            img_updated = True
        if commit:
            user_profile.save()
            if img_updated:
                try:
                    user_profile._create_resized_images(raw_field=None, save=commit)
                except:
                    # retry once
                    try:
                        user_profile._create_resized_images(raw_field=None, save=commit)
                    except Exception, e:
                        _log.warn("User id %s's profile image could not be resized. Removing image.", user_profile.user.username)
                        _log.exception(e)
                        user_profile.avatar_image = None
                        user_profile.avatar = None
                        user_profile.avatar_medium = None
                        super(UserProfile, user_profile).save()
Esempio n. 3
0
    def save_profile_image(self, user_profile, commit=True):
        """Save avatar image if one was uploaded.

        If `commit` is True, save the profile instance.

        Return the given user_profile instance.

        """
        avatar_img = self.cleaned_data.get('image', None)
        img_updated = False
        if avatar_img:
            avatar_img_field = user_profile._meta.get_field('avatar_image')
            avatar_img_field.save_form_data(user_profile, avatar_img)
            img_updated = True
        elif self.open_profile and self.open_profile['profile_image_url']:
            # Download and use Twitter profile image
            url = self.open_profile.get('profile_image_url', None)
            copy_avatar_from_url_to_profile(url, user_profile, commit=commit)
            img_updated = True
        if commit:
            user_profile.save()
            if img_updated:
                try:
                    user_profile._create_resized_images(raw_field=None,
                                                        save=commit)
                except:
                    # retry once
                    try:
                        user_profile._create_resized_images(raw_field=None,
                                                            save=commit)
                    except Exception, e:
                        _log.warn(
                            "User id %s's profile image could not be resized. Removing image.",
                            user_profile.user.username)
                        _log.exception(e)
                        user_profile.avatar_image = None
                        user_profile.avatar = None
                        user_profile.avatar_medium = None
                        super(UserProfile, user_profile).save()
Esempio n. 4
0
def save_open_profile(user, open_profile, amqp_headers=None):
    from twitter.models import TwitterProfile
    from registration.utils import copy_avatar_from_url_to_profile, is_sso_email

    if not open_profile:
        return
    p_type = open_profile["profile_type"]
    user_profile = user.get_profile()
    if p_type in settings.INSTALLED_APPS:
        if p_type == "twitter":
            profile = user_profile.twitter_profile
            created = False
            if not profile:
                profile = TwitterProfile(user_profile=user_profile)
                created = True
            profile.created = created
            profile.screen_name = open_profile["screen_name"]
            profile.appuser_id = unicode(open_profile["appuser_id"])
            profile.access_token = open_profile["access_token"]
            profile.save(amqp_headers=amqp_headers)
            # If user doesn't have a first and last name, set them from the open_profile
            user_changed = False
            if not user.first_name:
                user.first_name = open_profile["first_name"]
                user_changed = True
            if not user.last_name:
                user.last_name = open_profile["last_name"]
                user_changed = True
            if user_changed:
                user.save()
            if not user_profile.avatar_medium and "profile_image_url" in open_profile:
                # grab twitter profile image
                url = open_profile["profile_image_url"]
                copy_avatar_from_url_to_profile(url, user_profile, commit=True)
            return profile
    return None
Esempio n. 5
0
def get_artist_user_profile(name):
    """Return existing artist profile or create a new one and return it"""
    if not name:
        return _ARTIST.user_profile
    name = name.strip()
    if not name:
        return _ARTIST.user_profile
    is_dirty = False
    try:
        user_profile = UserProfile.objects.get(full_artistname=name)
        _log.debug("Reusing existing artist profile")
    except UserProfile.DoesNotExist:
        # create user profile from last fm data
        n = name.split(' ')
        if len(n) == 2:
            first_name, last_name = n
        elif len(n) > 2:
            first_name = n[0]
            last_name = u' '.join(n[1:])
        else:
            first_name = n
            last_name = ''
        username = name_to_username(name)
        if not username:
            return _ARTIST.user_profile
        username = username.strip()
        if not is_username_available(username):
            username = username + "-"
        a, created = User.objects.get_or_create(
            username=username,
            defaults = dict(
                first_name=first_name[:30],
                last_name=last_name[:30],
                email='*****@*****.**' % username.lower(),
                is_staff=False,
                is_active=True,                
            )
        )
        user_profile = a.get_profile()
        if created:
            user_profile.send_reminders = False
            user_profile.send_favorites = False
            user_profile.is_verified = True
            user_profile.permission = 'everyone'
            is_dirty = True  
            _log.debug("Using newly created artist profile")
    if not user_profile.full_artistname:
        user_profile.full_artistname = name
        is_dirty = True
    if not user_profile.avatar:
        # download profile image from last.fm
        info = get_artist_info(name)
        if info:
            imagelist = info.get('artist', {}).get('image', [])
            if imagelist:
                url = get_image_url(imagelist)
                copy_avatar_from_url_to_profile(url, user_profile)
                is_dirty = False
    if is_dirty:
        user_profile.save()
    return user_profile 
Esempio n. 6
0
def sso_authorized(request):
    """Process Single Sign-On (SSO) authorization from Twitter.

    If authorized:
        If account doesn't already exist:
        - Create dummy user account with disabled password ()
        - Create user profile with sso (including avatar image)
        - Save Twitter profile
    - Initiate AMQP tasks for user
    - Log the user in
    - Redirect to saved HTTP_REFERER or ``next`` value from sso_initiate

    """
    from event.amqp.tasks import build_recommended_events
    next = request.session.get('SSO_NEXT', '/')
    if request.user.is_authenticated():
        return HttpResponseRedirect(next)
    if 'OPEN_PROFILE' not in request.session:
        _log.debug("Lost session data during SSO authorization. Retrying.")
        return sso_initiate(request)
    oprofile = request.session['OPEN_PROFILE']
    screen_name = oprofile['screen_name'].lower()
    new_signup = False
    try:
        # Use already created SSO account if one exists
        prof = UserProfile.objects.select_related('user').get(sso_username__iexact=screen_name)
        user = prof.user
    except UserProfile.DoesNotExist:
        try:
            # Use latest existing account if one linked to this twitter screen name exists
            prof = UserProfile.objects.select_related('user').filter(
                twitterprofile__screen_name__iexact=screen_name,
                twitterprofile__pk__isnull=False
            ).order_by("-pk")[:1].get()
            user = prof.user
        except UserProfile.DoesNotExist:
            # Create a new SSO account
            # If screenname is available, use it as username.
            # If not, suffix it with a number and use that.
            new_signup = True
            email = request.session.get("email", None)
            if not email:
                add_message(request, u"Create a new account below in two easy steps before signing in with Twitter.")
                return HttpResponseRedirect(reverse("signup") + "?next=" + next)
            screen_name = screen_name.strip()[:32]
            user = None
            if User.objects.filter(username=screen_name).count():
                screen_name = screen_name[:27] # make room for suffixed digits
                for x in range(2, 100):
                    uname = u"%s%s" % (screen_name, x)
                    if not User.objects.filter(username=uname).count():
                        user = User.objects.create(
                            username=uname,
                            first_name=oprofile['first_name'],
                            last_name=oprofile['last_name'],
                            email=email,
                        )
                        break
            else:
                user = User.objects.create(
                    username=screen_name,
                    first_name=oprofile['first_name'],
                    last_name=oprofile['last_name'],
                    email=email,
                )
            if not user:
                # use a randomly suffixed username
                user = User.objects.create(
                    username=u''.join([screen_name[:25], u'-', uuid4().hex[::6]]),
                    first_name=oprofile['first_name'],
                    last_name=oprofile['last_name'],
                    email=email,
                )
            prof = user.get_profile()
            prof.is_sso = True
            prof.sso_username = screen_name
            prof.send_reminders = False
            prof.send_favorites = False
            prof.save()
    # build AMQP headers so that recommended events are built right after 
    # this user's friendships have been computed
    amqp_headers = {
        'final_reply_to':'signal/signal.events.build_recommended_events',
        'user_profile_id':prof.pk
    }
    save_open_profile(user, oprofile, amqp_headers) # this will also initiate the friendship builder AMQP task
    if not prof.avatar_image:
        url = oprofile.get('profile_image_url', None)
        copy_avatar_from_url_to_profile(url, prof, commit=True)
    # annotate the user object with the path of the backend so that 
    # login() works without a password:
    backend = get_backends()[0] 
    user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
    login(request, user)
    if new_signup:
        user.message_set.create(message=_(u'Thank you for signing-up with Twitter!'))
    _log.debug("SSO user %s logged in" % prof.username)
    return HttpResponseRedirect(next)