예제 #1
0
def donate(request):
    message = None
    if request.method == 'POST':
        donation_form = DonationForm(request.POST)
        stub_account = False

        if request.user.is_anonymous():
            # Either this is a new account, a stubbed one, or a user that's simply not logged into their account
            try:
                stub_account = User.objects.filter(profile__stub_account=True). \
                                            get(email__iexact=request.POST.get('email'))
            except User.DoesNotExist:
                pass

            if not stub_account:
                user_form = UserForm(request.POST)
                profile_form = ProfileForm(request.POST)
            else:
                # We use the stub account and anonymous users even are allowed to update it. This is OK, because we
                # don't care too much about the accuracy of this data. Later if/when this becomes a real account,
                # anonymous users won't be able to update this information -- that's what matters.
                user_form = UserForm(request.POST, instance=stub_account)
                profile_form = ProfileForm(request.POST,
                                           instance=stub_account.profile)
        else:
            user_form = UserForm(request.POST, instance=request.user)
            profile_form = ProfileForm(request.POST,
                                       instance=request.user.profile)

        if all([
                donation_form.is_valid(),
                user_form.is_valid(),
                profile_form.is_valid()
        ]):
            # Process the data in form.cleaned_data
            cd_donation_form = donation_form.cleaned_data
            cd_user_form = user_form.cleaned_data
            cd_profile_form = profile_form.cleaned_data
            stripe_token = request.POST.get('stripeToken')

            # Route the payment to a payment provider
            response = route_and_process_donation(cd_donation_form,
                                                  cd_profile_form,
                                                  cd_user_form, stripe_token)
            logger.info("Payment routed with response: %s" % response)

            if response['status'] == 0:
                d = donation_form.save(commit=False)
                d.status = response['status']
                d.payment_id = response['payment_id']
                d.transaction_id = response.get(
                    'transaction_id')  # Will onlyl work for Paypal.
                d.save()

                if request.user.is_anonymous() and not stub_account:
                    # Create a stub account with an unusable password
                    new_user = User.objects.create_user(
                        cd_user_form['email']
                        [:30],  # Username can only be 30 chars long
                        cd_user_form['email'],
                    )
                    new_user.first_name = cd_user_form['first_name']
                    new_user.last_name = cd_user_form['last_name']
                    new_user.save()
                    profile = UserProfile(
                        user=new_user,
                        stub_account=True,
                        address1=cd_profile_form['address1'],
                        address2=cd_profile_form.get('address2'),
                        city=cd_profile_form['city'],
                        state=cd_profile_form['state'],
                        zip_code=cd_profile_form['zip_code'],
                        wants_newsletter=cd_profile_form['wants_newsletter'])
                    profile.save()
                else:
                    # Logged in user or an existing stub account.
                    user = user_form.save()
                    profile = profile_form.save()

                # Associate the donation with the profile
                profile.donation.add(d)
                profile.save()
                return HttpResponseRedirect(response['redirect'])

            else:
                logger.critical(
                    "Got back status of %s when making initial request of API. Message was:\n%s"
                    % (response['status'], response['message']))
                message = response['message']
    else:
        try:
            donation_form = DonationForm(
                initial={'referrer': request.GET.get('referrer')})
            user_form = UserForm(
                initial={
                    'first_name': request.user.first_name,
                    'last_name': request.user.last_name,
                    'email': request.user.email,
                })
            up = request.user.profile
            profile_form = ProfileForm(
                initial={
                    'address1': up.address1,
                    'address2': up.address2,
                    'city': up.city,
                    'state': up.state,
                    'zip_code': up.zip_code,
                    'wants_newsletter': up.wants_newsletter
                })
        except AttributeError:
            # for anonymous users, who lack profile info
            user_form = UserForm()
            profile_form = ProfileForm()

    return render_to_response(
        'donate/donate.html', {
            'donation_form': donation_form,
            'user_form': user_form,
            'profile_form': profile_form,
            'private': False,
            'message': message,
            'stripe_public_key': settings.STRIPE_PUBLIC_KEY
        }, RequestContext(request))
예제 #2
0
def register(request):
    """allow only an anonymous user to register"""
    redirect_to = request.REQUEST.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 not stub_account:
                form = UserCreationFormExtended(request.POST)
            else:
                form = UserCreationFormExtended(request.POST,
                                                instance=stub_account)

            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:
                    user = stub_account
                    user.set_password(cd['password1'])
                    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()

                # Send an email with the confirmation link to the new user
                email_subject = 'Confirm your account on CourtListener.com'
                email_body = (
                    "Hello, %s, and thanks for signing up for an account!\n\n"
                    "To send you emails, we need you to activate your account with CourtListener. To "
                    "activate your account, click this link within five days:\n\n"
                    "https://www.courtlistener.com/email/confirm/%s\n\n"
                    "Thanks for using our site,\n\n"
                    "The CourtListener Team\n\n"
                    "-------------------\n"
                    "For questions or comments, please see our contact page, "
                    "https://www.courtlistener.com/contact/." %
                    (user.username, up.activation_key))
                send_mail(email_subject, email_body,
                          'CourtListener <*****@*****.**>',
                          [user.email])

                # Send an email letting the admins know there's somebody to say hi to
                email_subject = 'New user confirmed on CourtListener: %s' % up.user.username
                email_body = (
                    "A new user has signed up on CourtListener and they'll be automatically welcomed soon!\n\n"
                    "  Their name is: %s\n"
                    "  Their email address is: %s\n\n"
                    "Sincerely,\n\n"
                    "The CourtListener Bots" %
                    (up.user.get_full_name() or "Not provided", up.user.email))
                send_mail(email_subject, email_body,
                          'CourtListener <*****@*****.**>',
                          [a[1] for a in settings.ADMINS])
                tally_stat('user.created')
                return HttpResponseRedirect('/register/success/?next=%s' %
                                            redirect_to)
        else:
            form = UserCreationFormExtended()
        return render_to_response("profile/register.html", {
            'form': form,
            'private': False
        }, RequestContext(request))
    else:
        # The user is already logged in. Direct them to their settings page as
        # a logical fallback
        return HttpResponseRedirect('/profile/settings/')
예제 #3
0
def register(request):
    """allow only an anonymous user to register"""
    redirect_to = request.REQUEST.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 not stub_account:
                form = UserCreationFormExtended(request.POST)
            else:
                form = UserCreationFormExtended(request.POST, instance=stub_account)

            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:
                    user = stub_account
                    user.set_password(cd['password1'])
                    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()

                # Send an email with the confirmation link to the new user
                email_subject = 'Confirm your account on CourtListener.com'
                email_body = ("Hello, %s, and thanks for signing up for an account!\n\n"
                              "To send you emails, we need you to activate your account with CourtListener. To "
                              "activate your account, click this link within five days:\n\n"
                              "https://www.courtlistener.com/email/confirm/%s\n\n"
                              "Thanks for using our site,\n\n"
                              "The CourtListener Team\n\n"
                              "-------------------\n"
                              "For questions or comments, please see our contact page, "
                              "https://www.courtlistener.com/contact/." % (user.username, up.activation_key))
                send_mail(
                    email_subject,
                    email_body, 'CourtListener <*****@*****.**>',
                    [user.email]
                )

                # Send an email letting the admins know there's somebody to say hi to
                email_subject = 'New user confirmed on CourtListener: %s' % up.user.username
                email_body = ("A new user has signed up on CourtListener and they'll be automatically welcomed soon!\n\n"
                              "  Their name is: %s\n"
                              "  Their email address is: %s\n\n"
                              "Sincerely,\n\n"
                              "The CourtListener Bots" % (up.user.get_full_name() or "Not provided",
                                                          up.user.email))
                send_mail(email_subject,
                          email_body,
                          'CourtListener <*****@*****.**>',
                          [a[1] for a in settings.ADMINS])
                tally_stat('user.created')
                return HttpResponseRedirect('/register/success/?next=%s' % redirect_to)
        else:
            form = UserCreationFormExtended()
        return render_to_response("profile/register.html",
                                  {'form': form, 'private': False},
                                  RequestContext(request))
    else:
        # The user is already logged in. Direct them to their settings page as
        # a logical fallback
        return HttpResponseRedirect('/profile/settings/')
예제 #4
0
def donate(request):
    message = None
    if request.method == 'POST':
        donation_form = DonationForm(request.POST)
        stub_account = False

        if request.user.is_anonymous():
            # Either this is a new account, a stubbed one, or a user that's simply not logged into their account
            try:
                stub_account = User.objects.filter(profile__stub_account=True). \
                                            get(email__iexact=request.POST.get('email'))
            except User.DoesNotExist:
                pass

            if not stub_account:
                user_form = UserForm(request.POST)
                profile_form = ProfileForm(request.POST)
            else:
                # We use the stub account and anonymous users even are allowed to update it. This is OK, because we
                # don't care too much about the accuracy of this data. Later if/when this becomes a real account,
                # anonymous users won't be able to update this information -- that's what matters.
                user_form = UserForm(request.POST, instance=stub_account)
                profile_form = ProfileForm(request.POST, instance=stub_account.profile)
        else:
            user_form = UserForm(request.POST, instance=request.user)
            profile_form = ProfileForm(request.POST, instance=request.user.profile)

        if all([donation_form.is_valid(), user_form.is_valid(), profile_form.is_valid()]):
            # Process the data in form.cleaned_data
            cd_donation_form = donation_form.cleaned_data
            cd_user_form = user_form.cleaned_data
            cd_profile_form = profile_form.cleaned_data
            stripe_token = request.POST.get('stripeToken')

            # Route the payment to a payment provider
            response = route_and_process_donation(cd_donation_form, cd_profile_form, cd_user_form, stripe_token)
            logger.info("Payment routed with response: %s" % response)

            if response['status'] == 0:
                d = donation_form.save(commit=False)
                d.status = response['status']
                d.payment_id = response['payment_id']
                d.transaction_id = response.get('transaction_id')  # Will onlyl work for Paypal.
                d.save()

                if request.user.is_anonymous() and not stub_account:
                    # Create a stub account with an unusable password
                    new_user = User.objects.create_user(
                        cd_user_form['email'][:30],  # Username can only be 30 chars long
                        cd_user_form['email'],
                    )
                    new_user.first_name = cd_user_form['first_name']
                    new_user.last_name = cd_user_form['last_name']
                    new_user.save()
                    profile = UserProfile(
                        user=new_user,
                        stub_account=True,
                        address1=cd_profile_form['address1'],
                        address2=cd_profile_form.get('address2'),
                        city=cd_profile_form['city'],
                        state=cd_profile_form['state'],
                        zip_code=cd_profile_form['zip_code'],
                        wants_newsletter=cd_profile_form['wants_newsletter']
                    )
                    profile.save()
                else:
                    # Logged in user or an existing stub account.
                    user = user_form.save()
                    profile = profile_form.save()

                # Associate the donation with the profile
                profile.donation.add(d)
                profile.save()
                return HttpResponseRedirect(response['redirect'])

            else:
                logger.critical("Got back status of %s when making initial request of API. Message was:\n%s" %
                                (response['status'], response['message']))
                message = response['message']
    else:
        try:
            donation_form = DonationForm(
                initial={
                    'referrer': request.GET.get('referrer')
                }
            )
            user_form = UserForm(
                initial={
                    'first_name': request.user.first_name,
                    'last_name': request.user.last_name,
                    'email': request.user.email,
                }
            )
            up = request.user.profile
            profile_form = ProfileForm(
                initial={
                    'address1': up.address1,
                    'address2': up.address2,
                    'city': up.city,
                    'state': up.state,
                    'zip_code': up.zip_code,
                    'wants_newsletter': up.wants_newsletter
                }
            )
        except AttributeError:
            # for anonymous users, who lack profile info
            user_form = UserForm()
            profile_form = ProfileForm()

    return render_to_response(
        'donate/donate.html',
        {
            'donation_form': donation_form,
            'user_form': user_form,
            'profile_form': profile_form,
            'private': False,
            'message': message,
            'stripe_public_key': settings.STRIPE_PUBLIC_KEY
        },
        RequestContext(request)
    )
예제 #5
0
def donate(request):
    """Load the donate page or process a submitted donation.

    This page has several branches. The logic is as follows:
        if GET:
            --> Load the page
        elif POST:
            if user is anonymous:
                if email address on record as a stub account:
                    --> Use it.
                elif new email address or a non-stub account:
                    --> We cannot allow anonymous people to update real
                        accounts, or this is a new email address, so create a
                        new stub account.
            elif user is logged in:
                --> associate with account.

            We now have an account. Process the payment and associate it.
    """

    message = None
    if request.method == 'POST':
        donation_form = DonationForm(request.POST)

        if request.user.is_anonymous():
            # Either this is a new account, a stubbed one, or a user that's
            # simply not logged into their account
            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:
                # We use the stub account and anonymous users even are allowed
                # to update it. This is OK, because we don't care too much
                # about the accuracy of this data. Later if/when this becomes
                # a real account, anonymous users won't be able to update this
                # information -- that's what matters.
                user_form = UserForm(
                    request.POST,
                    instance=stub_account
                )
                profile_form = ProfileForm(
                    request.POST,
                    instance=stub_account.profile
                )
            else:
                # Either a regular account or an email address we've never
                # seen before. Create a new user from the POST data.
                user_form = UserForm(request.POST)
                profile_form = ProfileForm(request.POST)
        else:
            user_form = UserForm(
                request.POST,
                instance=request.user
            )
            profile_form = ProfileForm(
                request.POST,
                instance=request.user.profile
            )

        if all([donation_form.is_valid(),
                user_form.is_valid(),
                profile_form.is_valid()]):
            # Process the data in form.cleaned_data
            cd_donation_form = donation_form.cleaned_data
            cd_user_form = user_form.cleaned_data
            cd_profile_form = profile_form.cleaned_data
            stripe_token = request.POST.get('stripeToken')

            # Route the payment to a payment provider
            response = route_and_process_donation(
                cd_donation_form,
                cd_profile_form,
                cd_user_form,
                stripe_token
            )
            logger.info("Payment routed with response: %s" % response)

            if response['status'] == 0:
                d = donation_form.save(commit=False)
                d.status = response['status']
                d.payment_id = response['payment_id']
                d.transaction_id = response.get('transaction_id')  # Will only work for Paypal.
                d.save()

                if request.user.is_anonymous() and not stub_account:
                    # Create a stub account with an unusable password
                    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(request.POST.get('email')).hexdigest()[:30],
                        cd_user_form['email'],
                    )
                    new_user.first_name = cd_user_form['first_name']
                    new_user.last_name = cd_user_form['last_name']
                    new_user.save()
                    profile = UserProfile(
                        user=new_user,
                        stub_account=True,
                        address1=cd_profile_form['address1'],
                        address2=cd_profile_form.get('address2'),
                        city=cd_profile_form['city'],
                        state=cd_profile_form['state'],
                        zip_code=cd_profile_form['zip_code'],
                        wants_newsletter=cd_profile_form['wants_newsletter']
                    )
                    profile.save()
                else:
                    # Logged in user or an existing stub account.
                    user = user_form.save()
                    profile = profile_form.save()

                # Associate the donation with the profile
                profile.donation.add(d)
                profile.save()
                return HttpResponseRedirect(response['redirect'])

            else:
                logger.critical("Got back status of %s when making initial "
                                "request of API. Message was:\n%s" %
                                (response['status'], response['message']))
                message = response['message']
    else:
        try:
            donation_form = DonationForm(
                initial={
                    'referrer': request.GET.get('referrer')
                }
            )
            user_form = UserForm(
                initial={
                    'first_name': request.user.first_name,
                    'last_name': request.user.last_name,
                    'email': request.user.email,
                }
            )
            up = request.user.profile
            profile_form = ProfileForm(
                initial={
                    'address1': up.address1,
                    'address2': up.address2,
                    'city': up.city,
                    'state': up.state,
                    'zip_code': up.zip_code,
                    'wants_newsletter': up.wants_newsletter
                }
            )
        except AttributeError:
            # for anonymous users, who lack profile info
            user_form = UserForm()
            profile_form = ProfileForm()

    return render_to_response(
        'donate/donate.html',
        {
            'donation_form': donation_form,
            'user_form': user_form,
            'profile_form': profile_form,
            'private': False,
            'message': message,
            'stripe_public_key': settings.STRIPE_PUBLIC_KEY
        },
        RequestContext(request)
    )
예제 #6
0
def donate(request):
    """Load the donate page or process a submitted donation.

    This page has several branches. The logic is as follows:
        if GET:
            --> Load the page
        elif POST:
            if user is anonymous:
                if email address on record as a stub account:
                    --> Use it.
                elif new email address or a non-stub account:
                    --> We cannot allow anonymous people to update real
                        accounts, or this is a new email address, so create a
                        new stub account.
            elif user is logged in:
                --> associate with account.

            We now have an account. Process the payment and associate it.
    """

    message = None
    if request.method == 'POST':
        donation_form = DonationForm(request.POST)

        if request.user.is_anonymous():
            # Either this is a new account, a stubbed one, or a user that's
            # simply not logged into their account
            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:
                # We use the stub account and anonymous users even are allowed
                # to update it. This is OK, because we don't care too much
                # about the accuracy of this data. Later if/when this becomes
                # a real account, anonymous users won't be able to update this
                # information -- that's what matters.
                user_form = UserForm(request.POST, instance=stub_account)
                profile_form = ProfileForm(request.POST,
                                           instance=stub_account.profile)
            else:
                # Either a regular account or an email address we've never
                # seen before. Create a new user from the POST data.
                user_form = UserForm(request.POST)
                profile_form = ProfileForm(request.POST)
        else:
            user_form = UserForm(request.POST, instance=request.user)
            profile_form = ProfileForm(request.POST,
                                       instance=request.user.profile)

        if all([
                donation_form.is_valid(),
                user_form.is_valid(),
                profile_form.is_valid()
        ]):
            # Process the data in form.cleaned_data
            cd_donation_form = donation_form.cleaned_data
            cd_user_form = user_form.cleaned_data
            cd_profile_form = profile_form.cleaned_data
            stripe_token = request.POST.get('stripeToken')

            # Route the payment to a payment provider
            response = route_and_process_donation(cd_donation_form,
                                                  cd_profile_form,
                                                  cd_user_form, stripe_token)
            logger.info("Payment routed with response: %s" % response)

            if response['status'] == 0:
                d = donation_form.save(commit=False)
                d.status = response['status']
                d.payment_id = response['payment_id']
                d.transaction_id = response.get(
                    'transaction_id')  # Will only work for Paypal.
                d.save()

                if request.user.is_anonymous() and not stub_account:
                    # Create a stub account with an unusable password
                    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(request.POST.get('email')).hexdigest()
                        [:30],
                        cd_user_form['email'],
                    )
                    new_user.first_name = cd_user_form['first_name']
                    new_user.last_name = cd_user_form['last_name']
                    new_user.save()
                    profile = UserProfile(
                        user=new_user,
                        stub_account=True,
                        address1=cd_profile_form['address1'],
                        address2=cd_profile_form.get('address2'),
                        city=cd_profile_form['city'],
                        state=cd_profile_form['state'],
                        zip_code=cd_profile_form['zip_code'],
                        wants_newsletter=cd_profile_form['wants_newsletter'])
                    profile.save()
                else:
                    # Logged in user or an existing stub account.
                    user = user_form.save()
                    profile = profile_form.save()

                # Associate the donation with the profile
                profile.donation.add(d)
                profile.save()
                return HttpResponseRedirect(response['redirect'])

            else:
                logger.critical("Got back status of %s when making initial "
                                "request of API. Message was:\n%s" %
                                (response['status'], response['message']))
                message = response['message']
    else:
        try:
            donation_form = DonationForm(
                initial={'referrer': request.GET.get('referrer')})
            user_form = UserForm(
                initial={
                    'first_name': request.user.first_name,
                    'last_name': request.user.last_name,
                    'email': request.user.email,
                })
            up = request.user.profile
            profile_form = ProfileForm(
                initial={
                    'address1': up.address1,
                    'address2': up.address2,
                    'city': up.city,
                    'state': up.state,
                    'zip_code': up.zip_code,
                    'wants_newsletter': up.wants_newsletter
                })
        except AttributeError:
            # for anonymous users, who lack profile info
            user_form = UserForm()
            profile_form = ProfileForm()

    return render_to_response(
        'donate/donate.html', {
            'donation_form': donation_form,
            'user_form': user_form,
            'profile_form': profile_form,
            'private': False,
            'message': message,
            'stripe_public_key': settings.STRIPE_PUBLIC_KEY
        }, RequestContext(request))