예제 #1
0
def view_settings(request):
    old_email = request.user.email  # this line has to be at the top to work.
    old_wants_newsletter = request.user.profile.wants_newsletter
    user = request.user
    up = user.profile
    user_form = UserForm(request.POST or None, instance=user)
    profile_form = ProfileForm(request.POST or None, instance=up)
    if profile_form.is_valid() and user_form.is_valid():
        user_cd = user_form.cleaned_data
        profile_cd = profile_form.cleaned_data
        new_email = user_cd['email']
        changed_email = old_email != new_email
        if changed_email:
            # Email was changed.
            up.activation_key = sha1_activation_key(user.username)
            up.key_expires = now() + timedelta(5)
            up.email_confirmed = False

            # Unsubscribe the old address in mailchimp (we'll
            # resubscribe it when they confirm it later).
            update_mailchimp.delay(old_email, 'unsubscribed')

            # Send the email.
            email = emails['email_changed_successfully']
            send_mail(
                email['subject'],
                email['body'] % (user.username, up.activation_key),
                email['from'],
                [new_email],
            )

            msg = message_dict['email_changed_successfully']
            messages.add_message(request, msg['level'], msg['message'])
            logout(request)
        else:
            # if the email wasn't changed, simply inform of success.
            msg = message_dict['settings_changed_successfully']
            messages.add_message(request, msg['level'], msg['message'])

        new_wants_newsletter = profile_cd['wants_newsletter']
        if old_wants_newsletter != new_wants_newsletter:
            if new_wants_newsletter is True and not changed_email:
                # They just subscribed. If they didn't *also* update their
                # email address, subscribe them.
                subscribe_to_mailchimp.delay(new_email)
            elif new_wants_newsletter is False:
                # They just unsubscribed
                update_mailchimp.delay(new_email, 'unsubscribed')

        # New email address and changes above are saved here.
        profile_form.save()
        user_form.save()

        return HttpResponseRedirect(reverse('view_settings'))
    return render(request, 'profile/settings.html', {
        'profile_form': profile_form,
        'user_form': user_form,
        'private': True
    })
예제 #2
0
def request_email_confirmation(request: HttpRequest) -> HttpResponse:
    """Send an email confirmation email"""
    if request.method == "POST":
        form = EmailConfirmationForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            users = User.objects.filter(email__iexact=cd["email"])
            if not len(users):
                # Normally, we'd throw an error here, but instead we pretend it
                # was a success. Meanwhile, we send an email saying that a
                # request was made, but we don't have an account with that
                # email address.
                email: EmailType = emails["no_account_found"]
                message = email["body"] % (
                    "email confirmation",
                    reverse("register"),
                )
                send_mail(
                    email["subject"],
                    message,
                    email["from_email"],
                    [cd["email"]],
                )
                return HttpResponseRedirect(reverse("email_confirm_success"))

            activation_key = sha1_activation_key(cd["email"])
            key_expires = now() + timedelta(days=5)

            for user in users:
                # associate it with the user's accounts.
                up = user.profile
                up.activation_key = activation_key
                up.key_expires = key_expires
                up.save()

            email: EmailType = emails["confirm_existing_account"]
            send_mail(
                email["subject"],
                email["body"] % activation_key,
                email["from_email"],
                [user.email],
            )
            return HttpResponseRedirect(reverse("email_confirm_success"))
    else:
        form = EmailConfirmationForm()
    return render(
        request,
        "register/request_email_confirmation.html",
        {
            "private": True,
            "form": form
        },
    )
예제 #3
0
    def notify_unconfirmed_accounts(self):
        """This function will notify people who have not confirmed their
        accounts that they must do so for fear of deletion.

        This function should be run once a week, or so.

        Because it updates the expiration date of the user's key, and also uses
        that field to determine if the user should be notified in the first
        place, the first week, a user will have an old enough key, and will be
        notified, but the next week their key will have a very recent
        expiration date (because it was just updated the prior week). This
        means that they won't be selected the next week, but the one after,
        their key will be old again, and they will be selected. It's not ideal,
        but it's OK.
        """

        # if your account is more than a week old, and you have not confirmed
        # it, we will send you a notification, requesting that you confirm it.
        a_week_ago = now() - datetime.timedelta(7)
        unconfirmed_ups = UserProfile.objects.filter(
            email_confirmed=False,
            key_expires__lte=a_week_ago,
            stub_account=False,
        )

        for up in unconfirmed_ups:
            if self.options["verbose"]:
                print "User %s will be notified" % up.user

            if not self.options["simulate"]:
                # Build and save a new activation key for the account.
                activation_key = sha1_activation_key(up.user.username)
                key_expires = now() + datetime.timedelta(5)
                up.activation_key = activation_key
                up.key_expires = key_expires
                up.save()

                # Send the email.
                current_site = Site.objects.get_current()
                email = emails["email_not_confirmed"]
                send_mail(
                    email["subject"] % current_site.name,
                    email["body"] % (up.user.username, up.activation_key),
                    email["from"],
                    [up.user.email],
                )
예제 #4
0
def request_email_confirmation(request):
    """Send an email confirmation email"""
    if request.method == 'POST':
        form = EmailConfirmationForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            users = User.objects.filter(email__iexact=cd['email'])
            if not len(users):
                # Normally, we'd throw an error here, but instead we pretend it
                # was a success. Meanwhile, we send an email saying that a
                # request was made, but we don't have an account with that
                # email address.
                email = emails['no_account_found']
                message = email['body'] % ('email confirmation',
                                           reverse('register'))
                send_mail(email['subject'], message,
                          email['from'], [cd['email']])
                return HttpResponseRedirect(reverse('email_confirm_success'))

            activation_key = sha1_activation_key(cd['email'])
            key_expires = now() + timedelta(days=5)

            for user in users:
                # associate it with the user's accounts.
                up = user.profile
                up.activation_key = activation_key
                up.key_expires = key_expires
                up.save()

            email = emails['confirm_existing_account']
            send_mail(
                email['subject'],
                email['body'] % activation_key,
                email['from'],
                [user.email],
            )
            return HttpResponseRedirect(reverse('email_confirm_success'))
    else:
        form = EmailConfirmationForm()
    return render(request, 'register/request_email_confirmation.html', {
        'private': True,
        'form': form
    })
예제 #5
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'))
예제 #6
0
def view_settings(request):
    old_email = request.user.email  # this line has to be at the top to work.
    old_wants_newsletter = request.user.profile.wants_newsletter
    user = request.user
    up = user.profile
    user_form = UserForm(request.POST or None, instance=user)
    profile_form = ProfileForm(request.POST or None, instance=up)
    if profile_form.is_valid() and user_form.is_valid():
        user_cd = user_form.cleaned_data
        profile_cd = profile_form.cleaned_data
        new_email = user_cd["email"]
        changed_email = old_email != new_email
        if changed_email:
            # Email was changed.
            up.activation_key = sha1_activation_key(user.username)
            up.key_expires = now() + timedelta(5)
            up.email_confirmed = False

            # Unsubscribe the old address in mailchimp (we'll
            # resubscribe it when they confirm it later).
            update_mailchimp.delay(old_email, "unsubscribed")

            # Send an email to the new and old addresses. New for verification;
            # old for notification of the change.
            email = emails["email_changed_successfully"]
            send_mail(
                email["subject"],
                email["body"] % (user.username, up.activation_key),
                email["from"],
                [new_email],
            )
            email = emails["notify_old_address"]
            send_mail(
                email["subject"],
                email["body"] % (user.username, old_email, new_email),
                email["from"],
                [old_email],
            )
            msg = message_dict["email_changed_successfully"]
            messages.add_message(request, msg["level"], msg["message"])
            logout(request)
        else:
            # if the email wasn't changed, simply inform of success.
            msg = message_dict["settings_changed_successfully"]
            messages.add_message(request, msg["level"], msg["message"])

        new_wants_newsletter = profile_cd["wants_newsletter"]
        if old_wants_newsletter != new_wants_newsletter:
            if new_wants_newsletter is True and not changed_email:
                # They just subscribed. If they didn't *also* update their
                # email address, subscribe them.
                subscribe_to_mailchimp.delay(new_email)
            elif new_wants_newsletter is False:
                # They just unsubscribed
                update_mailchimp.delay(new_email, "unsubscribed")

        # New email address and changes above are saved here.
        profile_form.save()
        user_form.save()

        return HttpResponseRedirect(reverse("view_settings"))
    return render(
        request,
        "profile/settings.html",
        {
            "profile_form": profile_form,
            "user_form": user_form,
            "private": True,
        },
    )
예제 #7
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"))