def edit_media(request):
    recipient = request.user.get_profile().recipient
    substate_menu_items = _organizer_submenu(request, "media", recipient)
    submenu_id = "organizer_submenu"
    
    FormKlass = get_form(Recipient, EDIT_TYPE, includes=('logo',
                                                         'promotional_video',
                                                         'pd_experience_video'))

    if request.POST:
        form = FormKlass(request.POST, request.FILES, instance=recipient)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message='Changes saved')
            arrow_direction = request.POST.get("arrow_direction", None)
            if arrow_direction and arrow_direction == "prev":
                return HttpResponseRedirect(reverse('edit_private_information'))
            elif arrow_direction and arrow_direction == "next":
                return HttpResponseRedirect(reverse('edit_promo_cards'))
            else:
                return HttpResponseRedirect(reverse('edit_media'))
    else:
        form = FormKlass(instance=recipient)

    return render_response(request, 'procrasdonate/recipient_organizer_pages/edit_media.html', locals())
Exemple #2
0
def adword_email_form(request, page, group):
    if request.POST:
        email = request.POST.get('email', None)

        if email:
            email = email.strip()
            visitor = Visitor.add(group, page, email)

            try:
                # send email for recipient user to reset password
                txt = render_string(
                    request, 'adwords/email.txt', {
                        'email': email,
                        'settings': settings,
                        'visitor': visitor,
                        'group': group,
                        'page': page
                    })
                visitor.send_email("Welcome to ProcrasDonate",
                                   txt,
                                   from_email=settings.EMAIL)
                return HttpResponseRedirect(
                    reverse('adword_done', args=(page, group)))
            except:
                Log.Error(
                    "Adword visitor::Problem sending thank you email to %s for %s \
                    (maybe email address does not exist?)" % (email, visitor),
                    "adword")
                return HttpResponseRedirect(
                    reverse('adword_done', args=(page, group)))
Exemple #3
0
def confirm_reset_password(request, username, confirmation_code):
    logout(request)
    tagging = RecipientUserTagging.get_or_none(user__username=username)
    error = None
    if not tagging:
        error = "Unknown username"
    #elif tagging.is_confirmed:
    #    error = "Registration is already complete."
    elif not tagging.confirm(confirmation_code):
        error = "Error confirming confirmation_code %s" % confirmation_code
    else:
        if request.POST:
            form = SetPasswordForm(tagging.user, request.POST)
            if form.is_valid():
                form.save()
                
                success = tagging.confirm(confirmation_code)
                if not success:
                    return render_response(request, 'procrasdonate/recipient_organizer_pages/account/confirmation_error.html', locals())

                user = authenticate(username=username, password=form.cleaned_data['new_password1'])
                if user.is_active:
                    login(request, user)
                    user.message_set.create(message='Password reset complete!')
                    return HttpResponseRedirect(reverse('recipient_organizer_dashboard'))                
                else:
                    return HttpResponseRedirect(reverse('login'))
        
    form = SetPasswordForm(tagging.user)
    instructions = """Enter a new password. It can be whatever you want, but it will
    be more secure if you use numbers and uppercase letters in addition to lowercase letters."""
    return render_response(request, 'procrasdonate/recipient_organizer_pages/account/confirm.html', locals())
def edit_public_information(request):
    recipient = request.user.get_profile().recipient
    substate_menu_items = _organizer_submenu(request, "public", recipient)
    submenu_id = "organizer_submenu"
        
    FormKlass = get_form(Recipient, EDIT_TYPE, includes=('name',
                                                         'category',
                                                         'mission',
                                                         'description',
                                                         'url'))

    if request.POST:
        form = FormKlass(request.POST, instance=recipient)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message='Changes saved')
            arrow_direction = request.POST.get("arrow_direction", None)
            if arrow_direction and arrow_direction == "prev":
                return HttpResponseRedirect(reverse('payment_registration'))
            elif arrow_direction and arrow_direction == "next":
                return HttpResponseRedirect(reverse('edit_private_information'))
            else:
                return HttpResponseRedirect(reverse('edit_public_information'))
    else:
        form = FormKlass(instance=recipient)

    return render_response(request, 'procrasdonate/recipient_organizer_pages/edit_public_information.html', locals())
Exemple #5
0
def remove_from_waitlist(request, remove_key):
    w = WaitList.get_or_none(remove_key=remove_key)
    if w:
        Log.Log("Remove from waitlist: %s" % w, "waitlist_remove")
        w.delete()
        return HttpResponseRedirect("%s?email=%s&is_removed=True" %
                                    (reverse('waitlist'), w.email.email))
    return HttpResponseRedirect(
        "%s?email=%s" % (reverse('waitlist'), w and w.email.email or ''))
Exemple #6
0
def remove_from_waitlist_form(request):
    email = request.POST and request.POST.get('remove_email', '') or ''
    w = WaitList.get_or_none(email__email=email)
    if w:
        Log.Log("Remove from waitlist: %s" % w, "waitlist_remove")
        w.delete()
        return HttpResponseRedirect("%s?email=%s&is_removed=True" %
                                    (reverse('waitlist'), w.email.email))
    return HttpResponseRedirect("%s?email=%s" % (reverse('waitlist'), email))
Exemple #7
0
def choose_recipient(request, rescuetime_key, recipient_slug):
    rt = RescueTimeUser.get_or_none(rescuetime_key=rescuetime_key)
    if not rt:
        return HttpResponseRedirect(reverse('rt_signup'))

    recipient = Recipient.get_or_none(slug=recipient_slug)
    if not recipient:
        return HttpResponseRedirect(
            reverse('rt_dashboard', args=(rescuetime_key, )))

    rt.recipient = recipient
    rt.save()
    return HttpResponseRedirect(
        reverse('rt_dashboard', args=(rescuetime_key, )))
Exemple #8
0
def dashboard(request, rescuetime_key):
    rt = RescueTimeUser.get_or_none(rescuetime_key=rescuetime_key)
    if not rt:
        return HttpResponseRedirect(reverse('rt_signup'))

    data = rt.data({
        'rs': 'day',  # 1 day of reports
        'pv': 'rank',  # perspective (rank, interval, member)
        'restrict_begin': '2010-02-11',
        'restrict_end': '2010-02-12'
    })
    if 'error' in data:
        error = "We received an invalid RescueTime API key. Is it deactivated? <a href='%s'>Please try again</a>" % reverse(
            'rt_signup')
        return render_response(request, 'rescuetime_interface/dashboard.html',
                               locals())

    pledges = []
    for row in rt.procrastination_data()['rows']:
        if rt.row_amt(row) > 0.01:
            pledges.append({
                'amt': rt.row_amt(row),
                'hrs': rt.row_hrs(row),
                'name': rt.row_name(row),
                'productivity': rt.row_productivity(row)
            })

    recipients = Recipient.objects.filter(
        fpsrecipient__status=FPSRecipient.STATUSES['SUCCESS']).exclude(
            slug="PD")
    return render_response(request, 'rescuetime_interface/dashboard.html',
                           locals())
Exemple #9
0
def signup(request):
    errors = []
    if request.POST:
        rescuetime_key = request.POST.get("rescuetime_key", "")
        #recipient_slug = request.POST.get("recipient_slug", "")
        #dollars_per_hr = request.POST.get("dollars_per_hr", "")
        if not rescuetime_key:
            errors.append("Please enter a RescueTime key")
            return render_response(request, 'rescuetime_interface/signup.html',
                                   locals())
        #if not recipient_slug:
        #    errors.append("Please select a charity to donate to")
        #    return render_response(request, 'rescuetime_interface/signup.html', locals())
        #if not dollars_per_hr:
        #    errors.append("Please enter how many dollars you will donate for every hour procrastinated")
        #    return render_response(request, 'rescuetime_interface/signup.html', locals())

        rt = RescueTimeUser.get_or_none(rescuetime_key=rescuetime_key)
        if not rt:
            rt = RescueTimeUser.add(rescuetime_key)

        return HttpResponseRedirect(
            reverse('rt_dashboard', args=(rt.rescuetime_key, )))

    return render_response(request, 'rescuetime_interface/signup.html',
                           locals())
    """        
def edit_thank_yous(request):
    recipient = request.user.get_profile().recipient
    
    substate_menu_items = _organizer_submenu(request, "thank_yous", recipient)
    submenu_id = "organizer_submenu"
    
    thank_yous = recipient.thank_yous()
    if thank_yous.count() < 3:
        for threshhold in [10, 100, 500]:
            MetaReport.add(recipient,
                           "Thanks for donating more than $%s to %s" % (threshhold, recipient.name),
                           """Thanks for donating more than $%s to %s

""" % (threshhold, recipient.name),
                           MetaReport.TYPES['THANKYOU'],
                           False,
                           datetime.datetime.now(),
                           threshhold)
            
    
    ThankYouFormSet = modelformset_factory(MetaReport, extra=(3-thank_yous.count()),
                                           max_num=3,
                                           fields=('threshhold', 'subject', 'message'))
    if request.method == 'POST':
        formset = ThankYouFormSet(request.POST, queryset=thank_yous)
        if formset.is_valid():
            formset.save()
            request.user.message_set.create(message='Changes saved')
            return HttpResponseRedirect(reverse('recipient_organizer_dashboard'))
        else:
            error = "Please correct the errors below"
    else:
        formset = ThankYouFormSet(queryset=thank_yous)
    return render_response(request, 'procrasdonate/recipient_organizer_pages/edit_thank_yous.html', locals())
def recipient_organizer_dashboard(request):
    recipient_user_tagging = request.user.get_profile()
    recipient = recipient_user_tagging.recipient
    
    checkbox_fields = []
    for field in RecipientUserTagging.CHECKBOX_FIELDS:
        f = getattr(recipient_user_tagging, field)
        if f != RecipientUserTagging.TASK_STATES["INVISIBLE"]:
            if request.POST:
                checked = request.POST.get(field)
            else:
                checked = f == RecipientUserTagging.TASK_STATES["DONE"]
            checkbox_fields.append({'name'   : field,
                                    'checked': checked,
                                    'label'  : field,
                                    'help'   : '',
                                    'error'  : ''})

    if request.POST:
        for field in checkbox_fields:
            if field['checked']:
                setattr(recipient_user_tagging, field['name'], RecipientUserTagging.TASK_STATES["DONE"])
            else:
                setattr(recipient_user_tagging, field['name'], RecipientUserTagging.TASK_STATES["TODO"])
        recipient_user_tagging.save()
        request.user.message_set.create(message='changes saved')
        return HttpResponseRedirect(reverse('recipient_organizer_dashboard'))
    
    return render_response(request, 'procrasdonate/recipient_organizer_pages/dashboard.html', locals())
Exemple #12
0
def edit_dollars_per_hr(request, rescuetime_key):
    rt = RescueTimeUser.get_or_none(rescuetime_key=rescuetime_key)
    if not rt:
        return HttpResponseRedirect(reverse('rt_signup'))

    if request.POST:
        dollars_per_hr = request.POST.get("dollars_per_hr", "").strip()
        try:
            dollars_per_hr = float(dollars_per_hr)
            rt.dollars_per_hr = dollars_per_hr
            rt.save()
        except:
            Log.Error("Problem saving dollars_per_hr: %s" % request,
                      "rescuetime_interface")

    return HttpResponseRedirect(
        reverse('rt_dashboard', args=(rescuetime_key, )))
Exemple #13
0
def login_view(request):
    next = request.GET.get('next', None)
    # Light security check -- make sure redirect_to isn't garbage.                                                                                                                
    if not next or '//' in next or ' ' in next:
        next = reverse('weddings_settings')

    username = request.POST.get('username', None)
    password = request.POST.get('password', None)
    user = authenticate(username=username, password=password)
    error = None
    if user is not None:
        if user.is_active:
            login(request, user)
            if not user.get_profile():
                Log.Error("dynamic_webpages.login_view: django user (RecipientUser) has no get_profile (RecipientUserTagging): %s" % user)
                return HttpResponseRedirect(reverse('home'))
            return HttpResponseRedirect(next)
        else:
            error = "Your account has been disabled"
    else:
        error = "Invalid username or password."
    return render_response(request, 'procrasdonate/recipient_organizer_pages/account/login.html', locals())
Exemple #14
0
def confirm(request, username, confirmation_code):
    logout(request)
    tagging = RecipientUserTagging.get_or_none(confirmation_code=confirmation_code)
    error = None
    if not tagging:
        error = "Unknown confirmation code"
        Log.Log(error)
    elif tagging.user.username != username:
        error = "Something unexpected happened while confirming your registration as an organizer for %s. Please send us an email with this message" % tagging.recipient.name
        Log.Error(error)
    elif tagging.is_confirmed:
        error = "Registration is already complete."
        Log.Log(error)
    elif not tagging.confirmable(confirmation_code):
        error = "Error confirming confirmation code %s" % confirmation_code
        Log.Log(error)
    else:
        if request.POST:
            form = SetPasswordForm(tagging.user, request.POST)
            if form.is_valid():
                form.save()
                
                success = tagging.confirm(confirmation_code)
                if not success:
                    return render_response(request, 'procrasdonate/recipient_organizer_pages/account/confirmation_error.html', locals())

                user = authenticate(username=username, password=form.cleaned_data['new_password1'])
                if user.is_active:
                    login(request, user)
                    user.message_set.create(message='Registration complete!')
                    return HttpResponseRedirect(reverse('recipient_organizer_dashboard'))                
                else:
                    return HttpResponseRedirect(reverse('login'))
        
    form = tagging and SetPasswordForm(tagging.user) or None
    instructions = """<p>Welcome, %s.</p><p>Please enter a password. You can enter whatever 
    you want; for security, consider using at least 8 characters and mixing numbers with 
    lower and uppercase letters.</p>""" % username
    return render_response(request, 'procrasdonate/recipient_organizer_pages/account/confirm.html', locals())
def edit_private_information(request):
    recipient = request.user.get_profile().recipient
    substate_menu_items = _organizer_submenu(request, "private", recipient)
    submenu_id = "organizer_submenu"
    
    FormKlass = get_form(Recipient, EDIT_TYPE, includes=('employers_identification_number',
                                                         'tax_exempt_status',
                                                         'sponsoring_organization',
                                                         'office_phone',
                                                         'mailing_address',
                                                         'city',
                                                         'state',
                                                         'country'))
    
    RU_FormKlass = get_form(RecipientUser, EDIT_TYPE, includes=('first_name', 'last_name', 'email'))

    if request.POST:
        form = FormKlass(request.POST, instance=recipient)
        ru_form = RU_FormKlass(request.POST, instance=request.user)
        
        if form.is_valid() and ru_form.is_valid():
            form.save()
            ru_form.save()
            request.user.message_set.create(message='Changes saved')
            arrow_direction = request.POST.get("arrow_direction", None)
            if arrow_direction and arrow_direction == "prev":
                return HttpResponseRedirect(reverse('edit_public_information'))
            elif arrow_direction and arrow_direction == "next":
                return HttpResponseRedirect(reverse('edit_media'))
            else:
                return HttpResponseRedirect(reverse('edit_private_information'))
    else:
        form = FormKlass(instance=recipient)
        ru_form = RU_FormKlass(instance=request.user)

    return render_response(request, 'procrasdonate/recipient_organizer_pages/edit_private_information.html', locals())
def link_vote(request, vote_id, recipient_slug):
    rvote = RecipientVote.get_or_none(id=vote_id)
    if rvote:
        if recipient_slug == "None":
            recipient = None
            message = "Successfully unlinked vote %s" % rvote.name
        else:
            recipient = Recipient.get_or_none(slug=recipient_slug)
            message = "Successfully linked vote %s to recipient %s" % (
                rvote.name, recipient.name)
        rvote.recipient = recipient
        rvote.save()
        request.user.message_set.create(message=message)
    else:
        request.user.message_set.create(
            message='Error: could not find recipient vote %s' % vote_id)
    return HttpResponseRedirect(reverse('recipient_votes'))
def _edit_recipient_something(request, includes, template):
    """
    could use this but.... edit_foo's are likely to become more complicated with amazon auth and video stuff....
    """
    recipient = request.user.get_profile().recipient
        
    FormKlass = get_form(Recipient, EDIT_TYPE, includes=includes)

    if request.POST:
        form = FormKlass(request.POST, instance=recipient)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message='Changes saved')
            return HttpResponseRedirect(reverse('recipient', args=(recipient.slug,)))
    else:
        form = FormKlass(instance=recipient)

    return render_response(request, template, locals())
Exemple #18
0
def debug(request, rescuetime_key):
    rt = RescueTimeUser.get_or_none(rescuetime_key=rescuetime_key)
    if not rt:
        return HttpResponseRedirect(reverse('rt_signup'))

    a = AnalyticApiKey(rt.rescuetime_key, "ProcrasDonate")
    s = Service()

    data = s.fetch_data(
        a,
        {
            'rs': 'day',  # 1 day of reports
            'pv': 'rank',  # perspective (rank, interval, member)
            'restrict_begin': '2010-02-11',
            'restrict_end': '2010-02-12'
        })

    dollars_per_hr = rt.dollars_per_hr
    recipient = rt.recipient

    websites = []
    for row in data['rows']:
        if domain_re.search(row[3]):
            secs = row[1]
            amt = secs / 3600.0 * dollars_per_hr
            websites.append({
                'amt': amt,
                'hrs': secs / 3600.0,
                'domain': row[3]
            })

    payments = []
    for row in data['rows']:
        if row[5] < 0:
            secs = row[1]
            amt = int(secs) / 3600.0 * dollars_per_hr
            payments.append({
                'amt': amt,
                'hrs': int(secs) / 3600.0,
                'domain': row[3]
            })

    return render_response(request, 'rescuetime_interface/dashboard.html',
                           locals())
Exemple #19
0
def authorize(request, rescuetime_key):
    #if not settings.DJANGO_SERVER and not request.is_secure():
    #    message = "must secure data via HTTPS: request=%s" % request
    #    Log.Error(message, "request_error")
    #    return HttpResponseRedirect(reverse('rt_dashboard', args=(rescuetime_key, )))

    rt = RescueTimeUser.get_or_none(rescuetime_key=rescuetime_key)
    if not rt:
        return HttpResponseRedirect(reverse('rt_signup'))

    lower_parameters = {
        "caller_reference": create_id(12),
        "payment_reason": "ProcrasDonating for a good cause",
        "payment_method": "ABT,ACH,CC",
        "global_amount_limit": "100",
        "recipient_slug_list": "all",
        "version": settings.FPS['version']
    }
    #"timestamp",

    # params for FPS REST request
    camel_parameters = _switch_cases(lower_parameters, to_lower=False)

    recipients = []
    if camel_parameters['recipient_slug_list'] == "all":
        allr = Recipient.objects.filter(
            fpsrecipient__status=FPSRecipient.STATUSES['SUCCESS'])
        print "ALLR", allr
        allr = allr.exclude(slug="PD")
        print "ALLR2", allr
    else:
        allr = Recipient.objects.filter(
            fpsrecipient__status=FPSRecipient.STATUSES['SUCCESS'])
        allr = allr.filter(
            slug__in=camel_parameters['recipient_slug_list'].split(','))

    print
    for recipient in allr:
        print "RECIPIENT", recipient
        recipients.append(recipient)

    recipient_token_list = ",".join(
        [recipient.fps_data.token_id for recipient in recipients])
    if not recipient_token_list:
        Log.error("Empty recipient token list! %s" % request,
                  "empty_recipient_token_list")
    del camel_parameters['recipient_slug_list']
    camel_parameters['recipientTokenList'] = recipient_token_list

    camel_parameters.update({#'RecipientCobranding': "true",
                           #'paymentMethod': 'CC,ACH,ABT',
                           # common CBUI parameters
                           'cobrandingUrl': settings.FPS['cobrandingUrl'],
                           'websiteDescription': settings.FPS['websiteDescription'],
                           'pipelineName': "MultiUse",
                           'returnURL': "%s%s" % (settings.DOMAIN,
                                                  reverse('rt_authorize_callback',
                                                          args=(rescuetime_key, camel_parameters['callerReference']))),
                                                          #kwargs={'caller_reference': parameters['callerReference']})),
                           'callerKey': settings.FPS['callerKey'],
                           })

    # add timestampe and signature
    finalize_parameters(camel_parameters, type=CBUI_TYPE)
    print "POST FINALIZE"
    for x in camel_parameters:
        print x, "=", camel_parameters[x]

    full_url = "%s?%s" % (AMAZON_CBUI_URL, urllib.urlencode(camel_parameters))
    print
    print "FULL_URL", full_url
    print

    multiuse = FPSMultiuseAuth.get_or_none(
        caller_reference=lower_parameters['caller_reference'])
    if not multiuse:
        multiuse = FPSMultiuseAuth.add(rt.user, lower_parameters)

    return HttpResponseRedirect(full_url)
Exemple #20
0
def payment_registration_callback(request):
    """
    inserts callback response parameters into HTML for procrasdonate extension to handle
    
    GET parameters:
    signature: DrYecY%2B1zu3pQlCfRJMeBBuilH8%3D
    refundTokenID: 26TKG9N9N13K6CPD4SAP57BQ8ZXFUFULH8INJMJS42T9R1BPVD7Z7Q6N9XYKYHRU
    tokenID      : 25TKV9S9NP3C6CKDLSA257BQIZNFUDUHH8JN3MJU4FT961GPVB727QQNXXYJYVR6
    status: SR
    callerReference: 
    
    
    signature=HC6EetKji26dd8qpBTtSTQVeEPs%3D
    refundTokenID=R7VX84PBU5N341F2VVP92NVLCTICNLH1BPRB2GKVZN84FH3FR6JP6C1JEEU7E1WS
    tokenID=R4VXE4LBUTNL41U2PVPA21VLXT7CN3HMBP3BSGKDZH845H1FR1JR6CQJSEULE6WU
    status=SR
    callerReference=h2Yij4nUqPzL
    """
    if not settings.DJANGO_SERVER and not request.is_secure():
        message = "must secure data via HTTPS: request=%s" % request
        Log.Error(message, "request_error")
        return json_failure(message)

    recipient = request.user.get_profile().recipient
    errors = []

    fpsr = recipient.fps_data

    print "RECIP CALLBACK GET: ", request.GET
    expected_parameters = ["signature", "status"]
    optional_parameters = [
        "refundTokenID", "tokenID", "callerReference", "errormessage"
    ]

    response = extract_parameters(request, "GET", expected_parameters,
                                  optional_parameters)
    if not response['success']:
        Log.Error(
            "payment_registration_callback::Something went wrong extracting parameters from Amazon's request: %s for %s. Full request: %s"
            % (response['reason'], recipient.slug, request.GET))
        return HttpResponseRedirect(reverse('payment_registration'))

    parameters = response['parameters']

    corrupted = is_corrupted(parameters, CBUI_CALLBACK_TYPE)
    if corrupted:
        Log.Error(
            "payment_registration_callback::Signature did not check out from Amazon's request: %s. Full request: %s"
            % (recipient.slug, request.GET))
        #return HttpResponseRedirect(reverse('payment_registration'))

    fpsr.refund_token_id = parameters['refundTokenID']
    fpsr.token_id = parameters['tokenID']
    fpsr.status = parameters['status']
    fpsr.save()

    if fpsr.status != FPSRecipient.STATUSES['SUCCESS']:
        Log.Error(
            "payment_registration_callback::Payment registration failed: %s for %s. Full request: %s"
            % (recipient.slug, request.GET))
    return HttpResponseRedirect(reverse('payment_registration'))
Exemple #21
0
def authorize_multiuse_callback(request, caller_reference):
    """
        user already authorized token:
            MTGcPUGRNCpQ
            signature=LVCSaC%2F6Yehs42YULIUE9af91OA%3D
            errorMessage=NP
            status=NP
        
        user aborted:
            MTGcPUGRNCpQ
            signature=uZK3bFyJKccNrClZCqY3FNfc72Y%3D
            status=A
        
        success:
            AUKJCQ7MdteM
            signature=S8BaFR36BYvtHk54v9cD3x7wfXI%3D
            expiry=03%2F2015
            tokenID=5495IQGR5ASC3RLHX6JCEDXVJMZJDVJAENVH46VIJJGEIIT891CTNAJEBHY4A2Y5
            status=SC
            callerReference=AUKJCQ7MdteM
            
            http://localhost:8000/fps/user/multiuse/authorize_callback/AmOYgYlAUMd6/
            signature=KO8sd2aac6YAT6Omctb19vq5MZo%3D
            errorMessage=The+following+input(s)+are+not+well+formed%3A+[callerReference]
            status=CE
            callerReference=AmOYgYlAUMd6
    """
    if not settings.DJANGO_SERVER and not request.is_secure():
        message = "must secure data via HTTPS: request=%s" % request
        Log.Error(message, "request_error")
        return json_failure(message)

    print request
    print "PAYMENT AUTH CALLBACK GET: ", caller_reference, json.dumps(
        request.GET, indent=2)
    multi_auth = FPSMultiuseAuth.get_or_none(caller_reference=caller_reference)

    expected_parameters = ["signature", "status"]
    optional_parameters = [
        "expiry",
        "tokenID",
        "callerReference",
        "errorMessage",
    ]

    response = extract_parameters(request, "GET", expected_parameters,
                                  optional_parameters)
    if not response['success']:
        multi_auth.status = FPSMultiuseAuth.STATUSES['RESPONSE_ERROR']
        multi_auth.save()
        return HttpResponseRedirect(reverse('register'))

    parameters = response['parameters']
    print "PARAMS FROM EXTRACTOR", json.dumps(parameters, indent=2)
    """
    TODO
    corrupted = is_corrupted(parameters, CBUI_CALLBACK_TYPE)
    if corrupted:
        multi_auth.status = FPSMultiuseAuth.STATUS['RESPONSE_ERROR']
        multi_auth.save()
        return HttpResponseRedirect(reverse('register'))
    """

    if FPSMultiuseAuth.success(parameters['status']):
        multi_auth.token_id = parameters['tokenID']
        multi_auth.expiry = parameters['expiry']
        if parameters['callerReference'] != caller_reference:
            Log.Error(
                "fps.authorize_multiuse_callback returned non-matching caller reference %s v %s. %s"
                %
                (parameters['callerReference'], caller_reference, request.GET))
    elif parameters['status'] == FPSMultiuseAuth.STATUSES[
            'PAYMENT_ERROR']:  # NP
        # payment error. eg user doesn't have a payment method
        # or user already has an authorized token
        if 'errorMessage' in parameters:
            multi_auth.error_message = parameters['errorMessage']
    elif parameters['status'] == FPSMultiuseAuth.STATUSES['ABORTED']:  # A
        # user aborted pipeilne
        if 'errorMessage' in parameters:
            multi_auth.error_message = parameters['errorMessage']

    multi_auth.status = parameters['status']
    multi_auth.save()

    return HttpResponseRedirect(reverse('register'))
Exemple #22
0
def authorize_multiuse(request):
    """
    expect parameters
        timestamp
        callerReference - use this so can resubmit pay requests, etc.
        globalAmountLimit - total $$ ever that can flow across token during token's lifetime
        paymentMethod - "ABT,ACH,CC"
        paymentReason - html
        recipient_slug_list - 'sluga,slugb,slugc' or 'all'
        version - one of ["2009-01-09"]
    
    returns
        parameters
        
    """
    #f = open('/var/sites/ProcrasDonate/auth.log', 'w')
    #import time
    #f.write("\n\n %s AUTHORIZE MULTIUSE WEASELS: " % (time.time(), request))
    #f.close()
    if not settings.DJANGO_SERVER and not request.is_secure():
        message = "must secure data via HTTPS: request=%s" % request
        Log.Error(message, "request_error")
        return json_failure(message)

    errors = []
    expected_parameters = [
        "caller_reference",
        "payment_reason",
        "payment_method",
        "global_amount_limit",
        "recipient_slug_list",
        "version",
        #"timestamp",
        "private_key"
    ]

    response = extract_parameters(request, "POST", expected_parameters)
    if not response['success']:
        return json_failure("Something went wrong extracting parameters: %s" %
                            response['reason'])

    # params to send back to client and use locally (database worthy)
    lower_parameters = response['parameters']
    private_key = lower_parameters['private_key']
    del lower_parameters['private_key']

    # params for FPS REST request
    camel_parameters = _switch_cases(response['parameters'], to_lower=False)

    recipients = []
    if camel_parameters['recipient_slug_list'] == "all":
        allr = Recipient.objects.filter(
            fpsrecipient__status=FPSRecipient.STATUSES['SUCCESS'])
    else:
        allr = Recipient.objects.filter(
            fpsrecipient__status=FPSRecipient.STATUSES['SUCCESS'])
        allr = allr.filter(
            slug__in=camel_parameters['recipient_slug_list'].split(','))

    for recipient in allr:
        recipients.append(recipient)

    recipient_token_list = ",".join(
        [recipient.fps_data.token_id for recipient in recipients])
    del camel_parameters['recipient_slug_list']
    camel_parameters['recipientTokenList'] = recipient_token_list

    camel_parameters.update({#'RecipientCobranding': "true",
                           #'paymentMethod': 'CC,ACH,ABT',
                           # common CBUI parameters
                           'cobrandingUrl': settings.FPS['cobrandingUrl'],
                           'websiteDescription': settings.FPS['websiteDescription'],
                           'pipelineName': "MultiUse",
                           'returnURL': "%s%s" % (settings.DOMAIN,
                                                  reverse('multiuse_authorize_callback',
                                                          args=(camel_parameters['callerReference'],))),
                                                          #kwargs={'caller_reference': parameters['callerReference']})),
                           'callerKey': settings.FPS['callerKey'],
                           })

    # add timestampe and signature
    print "PRE FINALIZE"
    for x in camel_parameters:
        print x, "=", camel_parameters[x]
    finalize_parameters(camel_parameters, type=CBUI_TYPE)
    print "POST FINALIZE"
    for x in camel_parameters:
        print x, "=", camel_parameters[x]

    full_url = "%s?%s" % (AMAZON_CBUI_URL, urllib.urlencode(camel_parameters))
    print
    print "FULL_URL", full_url
    print

    user = User.get_or_none(private_key=private_key)
    if not user:
        message = "unknown user: %s, request=%s" % (private_key, request)
        Log.Error(message, "unknown_user")
        return json_failure(message)

    multiuse = FPSMultiuseAuth.get_or_none(
        caller_reference=lower_parameters['caller_reference'])
    if not multiuse:
        multiuse = FPSMultiuseAuth.add(user, lower_parameters)

    return HttpResponseRedirect(full_url)
Exemple #23
0
def add_to_waitlist(request, group):
    if request.POST:
        expected_parameters = ["email"]
        optional_parameters = ["note"]

        response = extract_parameters(request, "POST", expected_parameters,
                                      optional_parameters)
        if not response['success']:
            Log.Error(
                "add_to_waitlist::Something went wrong extracting parameters (no email?): %s for %s"
                % (response['reason'], request.GET), "waitlist")
            return HttpResponseRedirect(reverse('waitlist'))
            #return json_failure("oops")

        parameters = response['parameters']
        note = 'note' in parameters and parameters['note'] or None

        w = WaitList.get_or_none(email__email=parameters['email'])
        if not w:
            w = WaitList.add(parameters['email'], group, note)
        else:
            Log.Log(
                "Same email address added to waitlist. Note and group NOT updated from waitlist, %s. New note: %s, new group: %s"
                % (w, note, group), "waitlist_duplicate")

        # send email for recipient user to reset password
        c = Context({
            'waiter':
            w,
            'remove_link':
            reverse('remove_from_waitlist', args=(w.remove_key, )),
            'settings':
            settings
        })
        txt_email = loader.get_template(
            'procrasdonate/wait_list/added_to_waitlist_email.txt')
        html_email = loader.get_template(
            'procrasdonate/wait_list/added_to_waitlist_email.html')
        """
        html_emailer.send_email(sender=settings.EMAIL,
                                    recipient=w.email.email,
                                    subject="Welcome ProcrasDonate Beta Tester",
                                    text=txt_email.render(c),
                                    html=html_email.render(c))
        """
        try:
            html_emailer.send_email(
                sender=settings.EMAIL,
                recipient=w.email.email,
                subject="Welcome ProcrasDonate Beta Tester",
                text=txt_email.render(c),
                html=html_email.render(c))
            return HttpResponseRedirect("%s?email=%s&is_added=True" %
                                        (reverse('waitlist'), w.email.email))
            #return json_success()
        except:
            Log.Error(
                "add_to_waitlist::Problem sending added-to-waitlist email to %s (does email address exist?)"
                % w, "waitlist")
            #return HttpResponseRedirect(reverse('waitlist'))
            return HttpResponseRedirect("%s?email=%s&is_added=True" %
                                        (reverse('waitlist'), w.email.email))
Exemple #24
0
def logout_view(request):
    logout(request)
    return HttpResponseRedirect(reverse('home'))
def register_organizer(request):
    RecipientUserTaggingForm = get_form(RecipientUserTagging,
                                        EDIT_TYPE,
                                        excludes=('user', 'is_confirmed',
                                                  'confirmation_code'))
    RecipientUserForm = get_form(RecipientUser,
                                 EDIT_TYPE,
                                 includes=('username', 'first_name',
                                           'last_name', 'email'))
    recipients = Recipient.objects.all()

    if request.POST:
        recipient_user_tagging_form = RecipientUserTaggingForm(request.POST)
        recipient_user_form = RecipientUserForm(request.POST)

        if recipient_user_tagging_form.is_valid(
        ) and recipient_user_form.is_valid():
            user = recipient_user_form.save()
            user.set_unusable_password()
            user.is_active = False
            user.save()

            fake_tagging = recipient_user_tagging_form.save(commit=False)
            tagging = RecipientUserTagging.add(user,
                                               fake_tagging.recipient,
                                               require_confirmation=True)
            del fake_tagging

            # send email for recipient user to login
            c = Context({
                'user':
                user,
                'recipient':
                tagging.recipient,
                'site_url':
                "http://ProcrasDonate.com",
                'confirmation_link':
                "%s" %
                (reverse('confirm',
                         args=(user.username, tagging.confirmation_code))),
                'confirmation_code':
                tagging.confirmation_code,
                'expiration_days':
                14
            })
            t = loader.get_template(
                'procrasdonate/recipient_organizer_pages/account/confirmation_email.txt'
            )
            tagging.send_email(
                "Welcome to ProcrasDonate! Please complete registration for %s"
                % tagging.recipient.name,
                t.render(c),
                from_email=settings.EMAIL)

            request.user.message_set.create(
                message='RecipientUser successfully registered')
            return HttpResponseRedirect(reverse('home'))
    else:
        recipient_user_tagging_form = RecipientUserTaggingForm()
        recipient_user_form = RecipientUserForm()

    return render_response(
        request,
        'procrasdonate/recipient_organizer_pages/account/register.html',
        locals())
def recipient(request, slug):
    recipient = get_object_or_404(Recipient, slug__iexact=slug)
    if recipient and recipient.slug != slug:
        return HttpResponseRedirect(reverse('recipient', args=(recipient.slug, )))
    return render_response(request, 'procrasdonate/public_recipient_pages/recipient.html', locals())