Ejemplo n.º 1
0
def create_stub_account(user_data, profile_data):
    email = user_data['email']
    new_user = User.objects.create_user(
        # Username can only be 30 chars long. Use a hash of the
        # email address to reduce the odds of somebody
        # wanting to create an account that already exists.
        # We'll change this to good values later, when the stub
        # account is upgraded to a real account with a real
        # username.
        hashlib.md5(email).hexdigest()[:30],
        email,
    )
    new_user.first_name = user_data['first_name']
    new_user.last_name = user_data['last_name']

    # Associate a profile
    profile = UserProfile(user=new_user,
                          stub_account=True,
                          address1=profile_data['address1'],
                          address2=profile_data.get('address2'),
                          city=profile_data['city'],
                          state=profile_data['state'],
                          zip_code=profile_data['zip_code'],
                          wants_newsletter=profile_data['wants_newsletter'])
    return new_user, profile
Ejemplo n.º 2
0
    def migrate_users_profiles_alerts_favorites_and_donations(self):
        self.stdout.write("Migrating users, profiles, alerts, favorites, and "
                          "donations to the new database...")
        old_users = User.objects.using('old').all()
        num_users = old_users.count()

        progress = 0
        self._print_progress(progress, num_users)
        for old_user in old_users:
            old_profile = old_user.profile_legacy
            old_alerts = old_profile.alert.all()
            old_favorites = old_profile.favorite.all()
            old_donations = old_profile.donation.all()

            new_user = User(
                pk=old_user.pk,
                username=old_user.username,
                first_name=old_user.first_name,
                last_name=old_user.last_name,
                email=old_user.email,
                is_staff=old_user.is_staff,
                is_active=old_user.is_active,
                is_superuser=old_user.is_superuser,
                date_joined=old_user.date_joined,
                last_login=old_user.last_login,
                password=old_user.password,
            )
            new_user.save(using='default')

            new_profile = UserProfileNew(
                pk=old_profile.pk,
                user=new_user,
                stub_account=old_profile.stub_account,
                employer=old_profile.employer,
                address1=old_profile.address1,
                address2=old_profile.address2,
                city=old_profile.city,
                state=old_profile.state,
                zip_code=old_profile.zip_code,
                avatar=old_profile.avatar,
                wants_newsletter=old_profile.wants_newsletter,
                plaintext_preferred=old_profile.plaintext_preferred,
                activation_key=old_profile.activation_key,
                key_expires=old_profile.key_expires,
                email_confirmed=old_profile.email_confirmed,
            )
            new_profile.save(using='default')
            new_profile.barmembership.add(
                *[membership.pk for membership in
                  old_profile.barmembership.all()]
            )

            for old_alert in old_alerts:
                new_alert = AlertNew(
                    pk=old_alert.pk,
                    user=new_user,
                    date_created=self.the_beginning_of_time,
                    date_modified=self.the_beginning_of_time,
                    name=old_alert.name,
                    query=old_alert.query,
                    rate=old_alert.rate,
                    always_send_email=old_alert.always_send_email,
                    date_last_hit=old_alert.date_last_hit,
                )
                new_alert.save(using='default')

            for old_favorite in old_favorites:
                opinion_fave_pk = getattr(old_favorite.doc_id, 'pk', None)
                audio_fave_pk = getattr(old_favorite.audio_id, 'pk', None)
                if opinion_fave_pk is not None:
                    cluster = OpinionClusterNew.objects.get(
                        pk=opinion_fave_pk)
                    audio = None
                else:
                    cluster = None
                    audio = AudioNew.objects.get(pk=audio_fave_pk)
                new_favorite = FavoriteNew(
                    pk=old_favorite.pk,
                    user=new_user,
                    cluster_id=cluster,
                    audio_id=audio,
                    date_created=old_favorite.date_modified or now(),
                    date_modified=old_favorite.date_modified or now(),
                    name=old_favorite.name,
                    notes=old_favorite.notes,
                )
                new_favorite.save(using='default')

            for old_donation in old_donations:
                new_donation = DonationNew(
                    pk=old_donation.pk,
                    donor=new_user,
                    date_modified=old_donation.date_modified,
                    date_created=old_donation.date_created,
                    clearing_date=old_donation.clearing_date,
                    send_annual_reminder=old_donation.send_annual_reminder,
                    amount=old_donation.amount,
                    payment_provider=old_donation.payment_provider,
                    payment_id=old_donation.payment_id,
                    transaction_id=old_donation.transaction_id,
                    status=old_donation.status,
                    referrer=old_donation.referrer,
                )
                new_donation.save(using='default')

            progress += 1
            self._print_progress(progress, num_users)
        self.stdout.write(u'')  # Do a newline...
Ejemplo n.º 3
0
def register(request):
    """allow only an anonymous user to register"""
    redirect_to = sanitize_redirection(request)
    if request.user.is_anonymous:
        if request.method == 'POST':
            try:
                stub_account = User.objects.filter(
                    profile__stub_account=True,
                ).get(
                    email__iexact=request.POST.get('email'),
                )
            except User.DoesNotExist:
                stub_account = False

            if stub_account:
                form = UserCreationFormExtended(
                    request.POST,
                    instance=stub_account
                )
            else:
                form = UserCreationFormExtended(request.POST)

            consent_form = OptInConsentForm(request.POST)
            if form.is_valid() and consent_form.is_valid():
                cd = form.cleaned_data
                if not stub_account:
                    # make a new user that is active, but has not confirmed
                    # their email address
                    user = User.objects.create_user(
                        cd['username'],
                        cd['email'],
                        cd['password1']
                    )
                    up = UserProfile(user=user)
                else:
                    # Upgrade the stub account to make it a regular account.
                    user = stub_account
                    user.set_password(cd['password1'])
                    user.username = cd['username']
                    up = stub_account.profile
                    up.stub_account = False

                if cd['first_name']:
                    user.first_name = cd['first_name']
                if cd['last_name']:
                    user.last_name = cd['last_name']
                user.save()

                # Build and assign the activation key
                up.activation_key = sha1_activation_key(user.username)
                up.key_expires = now() + timedelta(days=5)
                up.save()

                email = emails['confirm_your_new_account']
                send_mail(
                    email['subject'],
                    email['body'] % (user.username, up.activation_key),
                    email['from'],
                    [user.email]
                )
                email = emails['new_account_created']
                send_mail(
                    email['subject'] % up.user.username,
                    email['body'] % (
                        up.user.get_full_name() or "Not provided",
                        up.user.email
                    ),
                    email['from'],
                    email['to'],
                )
                tally_stat('user.created')
                get_str = '?next=%s&email=%s' % (urlencode(redirect_to),
                                                 urlencode(user.email))
                return HttpResponseRedirect(reverse('register_success') +
                                            get_str)
        else:
            form = UserCreationFormExtended()
            consent_form = OptInConsentForm()
        return render(request, "register/register.html", {
            'form': form,
            'consent_form': consent_form,
            'private': False
        })
    else:
        # The user is already logged in. Direct them to their settings page as
        # a logical fallback
        return HttpResponseRedirect(reverse('view_settings'))
Ejemplo n.º 4
0
def register(request):
    """allow only an anonymous user to register"""
    redirect_to = request.GET.get('next', '')
    if 'sign-in' in redirect_to:
        # thus, we don't redirect people back to the sign-in form
        redirect_to = ''

    # security checks:
    # Light security check -- make sure redirect_to isn't garbage.
    if not redirect_to or ' ' in redirect_to:
        redirect_to = settings.LOGIN_REDIRECT_URL

    # Heavier security check -- redirects to http://example.com should
    # not be allowed, but things like /view/?param=http://example.com
    # should be allowed. This regex checks if there is a '//' *before* a
    # question mark.
    elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
        redirect_to = settings.LOGIN_REDIRECT_URL

    if request.user.is_anonymous():
        if request.method == 'POST':
            try:
                stub_account = User.objects.filter(
                    profile__stub_account=True, ).get(
                        email__iexact=request.POST.get('email'), )
            except User.DoesNotExist:
                stub_account = False

            if stub_account:
                form = UserCreationFormExtended(request.POST,
                                                instance=stub_account)
            else:
                form = UserCreationFormExtended(request.POST)

            if form.is_valid():
                cd = form.cleaned_data
                if not stub_account:
                    # make a new user that is active, but has not confirmed
                    # their email address
                    user = User.objects.create_user(cd['username'],
                                                    cd['email'],
                                                    cd['password1'])
                    up = UserProfile(user=user)
                else:
                    # Upgrade the stub account to make it a regular account.
                    user = stub_account
                    user.set_password(cd['password1'])
                    user.username = cd['username']
                    up = stub_account.profile
                    up.stub_account = False

                if cd['first_name']:
                    user.first_name = cd['first_name']
                if cd['last_name']:
                    user.last_name = cd['last_name']
                user.save()

                # Build and assign the activation key
                salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
                up.activation_key = hashlib.sha1(salt +
                                                 user.username).hexdigest()
                up.key_expires = now() + timedelta(days=5)
                up.save()

                email = emails['confirm_your_new_account']
                send_mail(email['subject'],
                          email['body'] % (user.username, up.activation_key),
                          email['from'], [user.email])
                email = emails['new_account_created']
                send_mail(
                    email['subject'] % up.user.username,
                    email['body'] %
                    (up.user.get_full_name() or "Not provided", up.user.email),
                    email['from'],
                    email['to'],
                )
                tally_stat('user.created')
                return HttpResponseRedirect(
                    reverse('register_success') + '?next=%s' % redirect_to)
        else:
            form = UserCreationFormExtended()
        return render(request, "register/register.html", {
            'form': form,
            'private': False
        })
    else:
        # The user is already logged in. Direct them to their settings page as
        # a logical fallback
        return HttpResponseRedirect(reverse('view_settings'))
Ejemplo n.º 5
0
def register(request: HttpRequest) -> HttpResponse:
    """allow only an anonymous user to register"""
    redirect_to = get_redirect_or_login_url(request, "next")
    if request.user.is_anonymous:
        if request.method == "POST":
            try:
                stub_account = User.objects.filter(
                    profile__stub_account=True, ).get(
                        email__iexact=request.POST.get("email"))
            except User.DoesNotExist:
                stub_account = False

            if stub_account:
                form = UserCreationFormExtended(request.POST,
                                                instance=stub_account)
            else:
                form = UserCreationFormExtended(request.POST)

            consent_form = OptInConsentForm(request.POST)
            if form.is_valid() and consent_form.is_valid():
                cd = form.cleaned_data
                if not stub_account:
                    # make a new user that is active, but has not confirmed
                    # their email address
                    user = User.objects.create_user(cd["username"],
                                                    cd["email"],
                                                    cd["password1"])
                    up = UserProfile(user=user)
                else:
                    # Upgrade the stub account to make it a regular account.
                    user = stub_account
                    user.set_password(cd["password1"])
                    user.username = cd["username"]
                    up = stub_account.profile
                    up.stub_account = False

                if cd["first_name"]:
                    user.first_name = cd["first_name"]
                if cd["last_name"]:
                    user.last_name = cd["last_name"]
                user.save()

                # Build and assign the activation key
                up.activation_key = sha1_activation_key(user.username)
                up.key_expires = now() + timedelta(days=5)
                up.save()

                email: EmailType = emails["confirm_your_new_account"]
                send_mail(
                    email["subject"],
                    email["body"] % (user.username, up.activation_key),
                    email["from_email"],
                    [user.email],
                )
                email: EmailType = emails["new_account_created"]
                send_mail(
                    email["subject"] % up.user.username,
                    email["body"] % (
                        up.user.get_full_name() or "Not provided",
                        up.user.email,
                    ),
                    email["from_email"],
                    email["to"],
                )
                tally_stat("user.created")
                get_str = "?next=%s&email=%s" % (
                    urlencode(redirect_to),
                    urlencode(user.email),
                )
                return HttpResponseRedirect(
                    reverse("register_success") + get_str)
        else:
            form = UserCreationFormExtended()
            consent_form = OptInConsentForm()
        return render(
            request,
            "register/register.html",
            {
                "form": form,
                "consent_form": consent_form,
                "private": False
            },
        )
    else:
        # The user is already logged in. Direct them to their settings page as
        # a logical fallback
        return HttpResponseRedirect(reverse("view_settings"))
Ejemplo n.º 6
0
def register(request):
    """allow only an anonymous user to register"""
    redirect_to = request.GET.get('next', '')
    if 'sign-in' in redirect_to:
        # thus, we don't redirect people back to the sign-in form
        redirect_to = ''

    # security checks:
    # Light security check -- make sure redirect_to isn't garbage.
    if not redirect_to or ' ' in redirect_to:
        redirect_to = settings.LOGIN_REDIRECT_URL

    # Heavier security check -- redirects to http://example.com should
    # not be allowed, but things like /view/?param=http://example.com
    # should be allowed. This regex checks if there is a '//' *before* a
    # question mark.
    elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
        redirect_to = settings.LOGIN_REDIRECT_URL

    if request.user.is_anonymous:
        if request.method == 'POST':
            try:
                stub_account = User.objects.filter(
                    profile__stub_account=True,
                ).get(
                    email__iexact=request.POST.get('email'),
                )
            except User.DoesNotExist:
                stub_account = False

            if stub_account:
                form = UserCreationFormExtended(
                    request.POST,
                    instance=stub_account
                )
            else:
                form = UserCreationFormExtended(request.POST)

            consent_form = OptInConsentForm(request.POST)
            if form.is_valid() and consent_form.is_valid():
                cd = form.cleaned_data
                if not stub_account:
                    # make a new user that is active, but has not confirmed
                    # their email address
                    user = User.objects.create_user(
                        cd['username'],
                        cd['email'],
                        cd['password1']
                    )
                    up = UserProfile(user=user)
                else:
                    # Upgrade the stub account to make it a regular account.
                    user = stub_account
                    user.set_password(cd['password1'])
                    user.username = cd['username']
                    up = stub_account.profile
                    up.stub_account = False

                if cd['first_name']:
                    user.first_name = cd['first_name']
                if cd['last_name']:
                    user.last_name = cd['last_name']
                user.save()

                # Build and assign the activation key
                salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
                up.activation_key = hashlib.sha1(
                    salt + user.username).hexdigest()
                up.key_expires = now() + timedelta(days=5)
                up.save()

                email = emails['confirm_your_new_account']
                send_mail(
                    email['subject'],
                    email['body'] % (user.username, up.activation_key),
                    email['from'],
                    [user.email]
                )
                email = emails['new_account_created']
                send_mail(
                    email['subject'] % up.user.username,
                    email['body'] % (
                        up.user.get_full_name() or "Not provided",
                        up.user.email
                    ),
                    email['from'],
                    email['to'],
                )
                tally_stat('user.created')
                get_str = '?next=%s&email=%s' % (urlencode(redirect_to),
                                                 urlencode(user.email))
                return HttpResponseRedirect(reverse('register_success') +
                                            get_str)
        else:
            form = UserCreationFormExtended()
            consent_form = OptInConsentForm()
        return render(request, "register/register.html", {
            'form': form,
            'consent_form': consent_form,
            'private': False
        })
    else:
        # The user is already logged in. Direct them to their settings page as
        # a logical fallback
        return HttpResponseRedirect(reverse('view_settings'))