예제 #1
0
def user_reinvestment_reminder():
    """
    Mail worker

    Send email update to user that eligible for reinvestment.
    This should execute after month_allocation

    This how the script do:
    1. Read user profile with reinvest_pool >0 and subscribed_to_repayment_notifications = True
    2. For each user send updated email

    """
    SITE_URL = settings.SITE_URL
    project_reinvest_list_url = SITE_URL + reverse('reinvest_list')
    project_portfolio_url = SITE_URL + reverse('donor:dashboard')
    unsubscribe_update_url = SITE_URL + reverse('unsubscribe', kwargs={'action': 'confirmation'})
    for user in RevolvUserProfile.objects.filter(reinvest_pool__gt=0.0, subscribed_to_repayment_notifications=True):
        data = dict()
        data['amount'] = user.reinvest_pool
        data['portfolio_link'] = project_portfolio_url + utils.get_query_string(user.user)
        data['projects_url'] = project_reinvest_list_url + utils.get_query_string(user.user)
        data['unsubscribe_url'] = unsubscribe_update_url + utils.get_query_string(user.user)
        if user.user.first_name:
            data['first_name'] = user.user.first_name.title()
        else:
            data['first_name'] = 'RE-volv Supporter'

        send_revolv_email(
            'reinvestment_reminder',
            data, [user.user.email]
        )
예제 #2
0
def user_reinvestment_reminder():
    """
    Mail worker

    Send email update to user that eligible for reinvestment.
    This should execute after month_allocation

    This how the script do:
    1. Read user profile with reinvest_pool >0 and subscribed_to_updates = True
    2. For each user send updated email

    """
    SITE_URL = settings.SITE_URL
    project_reinvest_list_url = SITE_URL + reverse('reinvest_list')
    project_portfolio_url = SITE_URL + reverse('dashboard')
    unsubscribe_update_url = SITE_URL + reverse('unsubscribe', kwargs={'action': 'updates'})
    for user in RevolvUserProfile.objects.filter(reinvest_pool__gt=0.0, subscribed_to_updates=True):
        data = dict()
        amount=user.reinvest_pool
        if amount > 0.00:
            data['amount'] = amount
            data['portfolio_link'] = project_portfolio_url + utils.get_query_string(user.user)
            data['projects_url'] = project_reinvest_list_url + utils.get_query_string(user.user)
            data['unsubscribe_url'] = unsubscribe_update_url + utils.get_query_string(user.user)
            if user.user.first_name:
                data['first_name'] = user.user.first_name.title()
            else:
                data['first_name'] = 'RE-volv Supporter'
            send_revolv_email(
                'reinvestment_reminder',
                data, [user.user.email]
            )
예제 #3
0
 def handle(self, *args, **kwargs):
     if kwargs['username']:
         user = User.objects.get(username=kwargs['username'])
         print(get_query_string(user))
     else:
         for u in User.objects.all():
             print(u.username)
             print("http://0.0.0.0:8000" + get_query_string(u))
예제 #4
0
def send_login_email(user, request, *, welcome):
    assert user.email, f"User has no email: {user}"

    base = reverse('redirector', args=["login"], request=request)
    token = get_query_string(user)
    url = base + token

    message = EmailMessage(
        subject=None,
        from_email="Citizen Labs <*****@*****.**>",
        to=[user.email],
    )
    if welcome:
        message.template_id = 'voter-engagement-welcome'
    else:
        message.template_id = 'voter-engagement-login'
    message.merge_global_data = {
        'FIRST_NAME': user.first_name,
        'LAST_NAME': user.last_name,
        'LOGIN_URL': url,
        # TODO: Set site URL dynamically
        'SITE_URL': 'https://alpha-vote.citizenlabs.org/',
        # TODO: Implement unsubscribe functionality
        'UNSUBSCRIBE_URL': 'https://citizenlabs.org/contact/',
        'ABOUT_URL': 'https://citizenlabs.org/about/',
    }

    log.debug(f"Sending email: {prettify(message.__dict__)}")
    count = message.send(fail_silently=False)

    return count
예제 #5
0
def process_template(template_string, user):
    from .models import UserInCampaign
    from sesame import utils as sesame_utils

    template = string.Template(template_string)

    # Make variable substitutions
    text = template.substitute(
        addressment=user.userprofile.get_addressment(),
        last_name_vokativ=user.userprofile.get_last_name_vokativ(),
        name=user.userprofile.first_name,
        firstname=user.userprofile.first_name,
        surname=user.userprofile.last_name,
        street=user.userprofile.street,
        city=user.userprofile.city,
        zipcode=user.userprofile.zip_code,
        email=user.userprofile.email,
        telephone=user.userprofile.telephone,
        regular_amount=user.regular_amount,
        regular_frequency=_localize_enum(
            UserInCampaign.REGULAR_PAYMENT_FREQUENCIES, user.regular_frequency,
            user.userprofile.language),
        var_symbol=user.variable_symbol,
        last_payment_amount=user.last_payment and user.last_payment.amount
        or None,
        auth_token=sesame_utils.get_query_string(user.userprofile),
    )

    return gendrify_text(text, user.userprofile.sex)
예제 #6
0
파일: views.py 프로젝트: kwabena-aboah/adma
def login_now(request):
    # magic link login
    if request.method == "POST":
        try:
            email = request.POST.get('emailId')
            user = User.objects.get(email=email)
            login_token = utils.get_query_string(user)
            login_link = 'https://admagvgh.herokuapp.com/{}'.format(
                login_token)
            # login_link = '127.0.0.1:8000/{}'.format(login_token)

            html_message = """
    		<p>Hi there,</p>
    		<p>Here is your <a href="{}">magic link</a></p>
    		<p>Thanks,</p>
    		<p>AdMA Blog</p>
    		""".format(login_link)

            send_mail('AdMA Magic Link',
                      html_message,
                      '*****@*****.**', [email],
                      fail_silently=False,
                      html_message=html_message)
        except User.DoesNotExist:
            raise Http404("Requested user does not exist. Contact site admin.")
        message = "Please check your email for magic link."
        context = {'message': message}
        return render(request, 'accounts/login.html', context)
    return render(request, 'accounts/login.html')
예제 #7
0
    def form_valid(self, form):
        email = form.cleaned_data["email"]
        user, created = User.objects.get_or_create(email=email)
        login_token = utils.get_query_string(user)

        logo_url = "/static/images/logo-vertical.png"
        logo_src = "http://{}{}".format(self.request.get_host(), logo_url)
        login_link = "http://{}/{}".format(self.request.get_host(),
                                           login_token)

        html_message = render_to_string(
            "email/magiclink_login_message.html",
            {
                "login_link": login_link,
                "logo_src": logo_src
            },
        )

        send_mail(
            "Hospital Aid Login Link",
            html_message,
            "*****@*****.**",
            [email],
            fail_silently=False,
            html_message=html_message,
        )

        logger.info("Signup requested. Sent email.", email=email)
        return super().form_valid(form)
예제 #8
0
파일: api.py 프로젝트: daniilko0/ralph_cms
 def get(self, request, group):
     try:
         perm = Permission.objects.get(codename__contains=str(group))
     except Permission.DoesNotExist:
         return Response({
             "result": {
                 "code": 400,
                 "description": "[400] Permission doesn't exist",
             }
         })
     try:
         user = User.objects.get(user_permissions=perm, is_superuser=False)
     except User.DoesNotExist:
         return Response({
             "result": {
                 "code": 400,
                 "description": "[400] User doesn't exist",
             }
         })
     link_data = utils.get_query_string(user)
     return Response({
         "result": {
             "code": 200,
             "description": "[200] OK",
             "link": link_data
         }
     })
예제 #9
0
파일: test_views.py 프로젝트: auto-mat/klub
    def test_sign_petition_confirmation(self):
        """
        confirmation petition signature
        """
        user = mommy.make("aklub.UserProfile")
        mommy.make(
            "aklub.ProfileEmail",
            email=self.sign_petition["userprofile-email"],
            user=user,
            is_primary=True,
        )
        signature = mommy.make(
            "interactions.PetitionSignature",
            administrative_unit=self.unit,
            user=user,
            event=self.event,
        )

        address = reverse("sing-petition-confirm", kwargs={"campaign_slug": "klub"})
        url_hax = sesame_utils.get_query_string(user)
        address += url_hax

        response = self.client.get(address)
        self.assertEqual(response.status_code, 201)
        self.assertEqual(response.content.decode(), "Podpis potvrzen")

        signature.refresh_from_db()
        self.assertTrue(signature.email_confirmed)
예제 #10
0
파일: test_views.py 프로젝트: auto-mat/klub
    def test_send_mailing_list_subscribe(self):
        """
        subscribe back to mailing list in preference
        """
        self.term_cond.value = "user-mailing-subscribe"
        self.term_cond.save()

        user = mommy.make("aklub.UserProfile")
        mommy.make(
            "aklub.ProfileEmail", email="*****@*****.**", user=user, is_primary=True
        )
        preference = mommy.make(
            "aklub.Preference",
            user=user,
            administrative_unit=self.unit,
            send_mailing_lists=False,
        )

        address = reverse(
            "send-mailing-list",
            kwargs={"unit": self.unit.slug, "unsubscribe": "subscribe"},
        )
        url_hax = sesame_utils.get_query_string(user)
        address += url_hax

        response = self.client.get(address, follow=True)
        self.assertEqual(response.status_code, 201)

        preference.refresh_from_db()
        self.assertTrue(preference.send_mailing_lists)

        self.assertEqual(len(mail.outbox), 1)
예제 #11
0
def login_page(request):
    if request.method == "POST":
        email = request.POST.get("emailId")
        user = User.objects.get(email=email)
        login_token = utils.get_query_string(user)
        login_link = "http://127.0.0.1:8000/customers/{}".format(login_token)

        html_message = """
        <p>Hi there,</p>
        <p>Here is your <a href="{}">magic link</a> </p>
        <p>Thanks,</p>
        <p>Django Admin</p>
        """.format(login_link)

        send_mail('Django Magic Link',
                  html_message,
                  '*****@*****.**', [email],
                  fail_silently=False,
                  html_message=html_message)
        return render(
            request,
            "login.html",
            context={"message": "Please check your email for magic link."})

    return render(request, "login.html")
예제 #12
0
def send_login_email(accounting_data):
    from sesame.utils import get_query_string

    User = get_user_model()
    Organization = swapper.load_model('openwisp_users', 'Organization')
    username = accounting_data.get('username', None)
    org_uuid = accounting_data.get('organization')
    try:
        user = User.objects.get(username=username)
        organization = Organization.objects.select_related('radius_settings').get(
            id=org_uuid
        )
    except ObjectDoesNotExist:
        logger.warning(f'user with {username} does not exists')
        return
    if not organization.is_member(user):
        logger.warning(f'{username} is not the member of {organization.name}')
        return

    org_radius_settings = organization.radius_settings
    login_url = org_radius_settings.login_url
    if not login_url:
        logger.error(f'login_url is not defined for {organization.name} organization')
        return
    with translation.override(user.language):
        one_time_login_url = login_url + get_query_string(user)
        subject = _('New WiFi session started')
        context = {
            'user': user,
            'subject': subject,
            'call_to_action_url': one_time_login_url,
            'call_to_action_text': _('Manage Session'),
        }
        body_html = loader.render_to_string('radius_accounting_start.html', context)
        send_email(subject, body_html, body_html, [user.email], context)
예제 #13
0
def register(request):
    try:
        if request.user.is_authenticated:
            auser = Admin.objects.get(user=request.user)
        else:
            auser = None
    except Admin.DoesNotExist:
        auser = None

    if auser != None:
        form = CreateUserForm()
        if request.method == 'POST':
            form = CreateUserForm(request.POST)
            if form.is_valid():
                theuser = form.save(commit=False)
                theuser.username = form.cleaned_data.get('email')
                password = User.objects.make_random_password()
                theuser.set_password(password)
                username = form.cleaned_data.get('email')
                
                home = 'http://127.0.0.1:8000/'
                theuser.save()
                user = User.objects.get(username=username)
                thecand = Candidate(user=user)
                thecand.save()
                
                uniquelink = get_query_string(user)
                link = home + uniquelink
                themessage = 'Dear ' + theuser.first_name + '\n' + 'An avaloq coding test account has been created for you with following credentials\n' + 'Username: '******'\nPassword: '******'\nUnique login link: ' + link + "\nUnique login link is valid for 2 weeks"
                send_mail(
                    'User account created for avaloq',
                    themessage,
                    '*****@*****.**',
                    [str(username)],
                    fail_silently=False,

                )

                message = "User account created for " + str(username)

                messages.add_message(request, messages.SUCCESS, message)
                
                return redirect('cs14:register')
            
            else:
                 messages.add_message(request, messages.ERROR, 'Account already generated for this email')

    else:
        return redirect('cs14:login')

        
    context = {'form': form}
    return render(request, 'cs14/register.html', context)
예제 #14
0
def send_invite(user):
    tmp = get_template("email_template.html")
    params = utils.get_query_string(user)
    content = tmp.render(dict(user=user, params=params))
    id = user.invitation_details
    id.invite_sent = timezone.now()
    id.save()
    send_mail(SUBJECT,
              "please come to our wedding",
              'Christina & Fred', [user.email],
              fail_silently=False,
              html_message=content)
예제 #15
0
def user_reinvestment_reminder():
    """
    Mail worker

    Send email update to user that eligible for reinvestment.
    This should execute after month_allocation

    This how the script do:
    1. Read user profile with reinvest_pool >0 and subscribed_to_updates = True
    2. For each user send updated email

    """
    SITE_URL = settings.SITE_URL
    project_reinvest_list_url = SITE_URL + reverse("project:reinvest_list")
    unsubscribe_update_url = SITE_URL + reverse("unsubscribe", kwargs={"action": "updates"})
    for user in RevolvUserProfile.objects.filter(reinvest_pool__gt=0.0, subscribed_to_updates=True):
        data = dict()
        data["amount"] = user.reinvest_pool
        data["projects_url"] = project_reinvest_list_url + utils.get_query_string(user.user)
        data["unsubscribe_url"] = unsubscribe_update_url + utils.get_query_string(user.user)
        data["first_name"] = user.user.first_name
        send_revolv_email("reinvestment_reminder", data, [user.user.email])
예제 #16
0
    def post(self, request, *args, **kwargs):
        email = request.POST.get('email')
        job_update_url = reverse('job_update')
        
        try:
            user = User.objects.get(username__iexact=email)
        except:
            # a User record is automatically created when
            # an OrganizationAdmin is added. If no User record
            # is found, the address shouldn't be logging in. 
            msg = 'Sorry, no admin account associated with this email address.'
            messages.error(request, msg)
            return redirect(job_update_url)        

        # use django-sesame to send magic login link
        site_url = '{}://{}'.format(request.scheme, get_current_site(request))
        login_token = sesame_utils.get_query_string(user)
        login_link = '{}{}{}'.format(site_url, job_update_url, login_token)
                
        msg = 'We just emailed you a login link! Please check your inbox.'
        
        email_context = {
            'site_url': site_url,
            'login_link': login_link,
        }
    
        text_content = render_to_string(
            'jobs/_v2/emails/jobs_admin_login.txt',
            email_context,
        )
        html_content = render_to_string(
            'jobs/_v2/emails/jobs_admin_login.html',
            email_context
        )

        send_multipart_email(
            subject = 'Source Jobs: Log in to your account',
            from_email = settings.DEFAULT_FROM_EMAIL,
            to = email,
            text_content = text_content,
            html_content = html_content
        )

        if request.is_ajax():
            result = {'message': msg}
            return render_json_to_response(result)

        messages.success(request, msg)
        return redirect(job_update_url)
예제 #17
0
def user_reinvestment_reminder():
    """
    Mail worker

    Send email update to user that eligible for reinvestment.
    This should execute after month_allocation

    This how the script do:
    1. Read user profile with reinvest_pool >0 and subscribed_to_updates = True
    2. For each user send updated email

    """
    project_reinvest_list_url = SITE_URL + reverse('project:reinvest_list')
    unsubscribe_update_url = SITE_URL + reverse('unsubscribe', kwargs={'action': 'updates'})
    for user in RevolvUserProfile.objects.filter(reinvest_pool__gt=0.0, subscribed_to_updates=True):
        data = dict()
        data['amount'] = user.reinvest_pool
        data['projects_url'] = project_reinvest_list_url + utils.get_query_string(user.user)
        data['unsubscribe_url'] = unsubscribe_update_url + utils.get_query_string(user.user)
        data['first_name'] = user.user.first_name
        send_revolv_email(
            'reinvestment_reminder',
            data, [user.user.email]
        )
예제 #18
0
파일: autocom.py 프로젝트: auto-mat/klub
def process_template(template_string, user, payment_channel):
    from aklub.models import DonorPaymentChannel
    from sesame import utils as sesame_utils

    template = string.Template(template_string)
    if payment_channel:

        payment_substitutes = {
            "regular_amount":
            payment_channel.regular_amount,
            "regular_frequency":
            _localize_enum(
                DonorPaymentChannel.REGULAR_PAYMENT_FREQUENCIES,
                payment_channel.regular_frequency,
                user.language,
            ),
            "var_symbol":
            payment_channel.VS,
            "last_payment_amount":
            payment_channel.last_payment.amount
            if payment_channel.last_payment else None,
        }

    else:
        payment_substitutes = {}

    # Make variable substitutions
    text = template.substitute(
        addressment=user.get_addressment(),
        last_name_vokativ=user.get_last_name_vokativ(),
        name=user.first_name if hasattr(user, "first_name") else user.name,
        firstname=user.first_name
        if hasattr(user, "first_name") else user.name,
        surname=user.last_name if hasattr(user, "first_name") else user.name,
        street=user.street,
        city=user.city,
        zipcode=user.zip_code,
        email=user.email,
        telephone=user.get_telephone(),
        auth_token=sesame_utils.get_query_string(user),
        **payment_substitutes,
    )
    return gendrify_text(text, user.sex if hasattr(user, "sex") else "")
예제 #19
0
def signup_magiclink(request):
    if request.method == "POST":
        email = request.POST.get("email")
        user, created = User.objects.get_or_create(email=email)
        login_token = utils.get_query_string(user)
        login_link = "http://{}/{}".format(request.get_host(), login_token)

        html_message = """
        <p>Hi there,</p>
        <p>Here is your <a href="{}">login link</a> </p>
        <p>Thanks,</p>
        <p>HospitalAid Admin</p>
        """.format(login_link)

        send_mail('Hospital Aid Login Link',
                  html_message,
                  '*****@*****.**', [email],
                  fail_silently=False,
                  html_message=html_message)
        return render(request, "magiclink_sent.html", context={"email": email})

    return HttpResponseBadRequest()
예제 #20
0
def get_login_url(request, user):
    base = reverse('redirector', args=["login"], request=request)
    token = get_query_string(user)
    return base + token
예제 #21
0
파일: views.py 프로젝트: RE-volv/revolv
def stripe_payment(request, pk):
    try:
        token = request.POST['stripeToken']
        tip_cents = request.POST['metadata']
        amount_cents = request.POST['amount_cents']
        email = request.POST['stripeEmail']
    except KeyError:
        logger.exception('stripe_payment called without required POST data')
        return HttpResponseBadRequest('bad POST data')

    try:
        tip_cents = int(tip_cents)
        amount_cents = int(amount_cents)
        if not (0 < amount_cents < MAX_PAYMENT_CENTS):
            raise ValueError('amount_cents cannot be negative')
        if not (0 <= tip_cents <= amount_cents):
            raise ValueError('tip_cents cannot be negative or more than project contribution')
    except ValueError:
        logger.exception('stripe_payment called with improper POST data')
        return HttpResponseBadRequest('bad POST data')

    project = get_object_or_404(Project, pk=pk)

    project_matching_donors = ProjectMatchingDonors.objects.filter(project=project, amount__gt=0)

    donation_cents = amount_cents - tip_cents

    error_msg = None
    try:
        stripe.Charge.create(source=token, description="Donation for " + project.title, currency="usd",
                             amount=amount_cents)
    except stripe.error.CardError as e:
        body = e.json_body
        error_msg = body['error']['message']
    except stripe.error.APIConnectionError as e:
        body = e.json_body
        error_msg = body['error']['message']
    except Exception:
        error_msg = "Payment error. Re-volv has been notified."
        logger.exception(error_msg)
    if error_msg:
        return render(request, "project/project_donate_error.html", {
            "msg": error_msg, "project": project
        })

    if project_matching_donors:
        for donor in project_matching_donors:
            if donor.amount > donation_cents / 100:
                matching_donation = donation_cents / 100
                donor.amount = donor.amount - donation_cents / 100
                donor.save()
            else:
                matching_donation = donor.amount
                donor.amount = 0
                donor.save()

            tip = None

            Payment.objects.create(
                user=donor.matching_donor,
                entrant=donor.matching_donor,
                amount=matching_donation,
                project=project,
                tip=tip,
                payment_type=PaymentType.objects.get_stripe(),
            )
            send_donation_info(donor.matching_donor.get_full_name(), matching_donation, donor.matching_donor.user.email,
                               project.title, address='')

    if request.user.is_authenticated():
        user = request.user.revolvuserprofile
    else:
        user_id = User.objects.get(username='******').pk
        user = RevolvUserProfile.objects.get(user_id=user_id)

    tip = None
    if tip_cents > 0:
        tip = Tip.objects.create(
            amount=tip_cents / 100.0,
            user=user,
        )

    payment = Payment.objects.create(
        user=user,
        entrant=user,
        amount=donation_cents / 100.0,
        project=project,
        tip=tip,
        payment_type=PaymentType.objects.get_stripe(),
    )
    if request.session.has_key("utm_params"):
        utm_params = request.session.get("utm_params")
        utm_source = utm_params.get("utm_source")
        utm_medium = utm_params.get("utm_medium")
        utm_campaign = utm_params.get("utm_campaign")
        utm_content = utm_params.get("utm_content")
        referral_source_track = ReferralSourceTrack.objects.create(
            source=utm_source,
            medium=utm_medium,
            campaign=utm_campaign,
            content=utm_content,
            payment=payment
        )

    if not request.user.is_authenticated():
        my_ip = load(urlopen('http://jsonip.com'))['ip']

        url = 'http://api.ipstack.com/' + my_ip + '?access_key=' + settings.IP_STACK_ACCESS_KEY

        url_timezone = 'http://ip-api.com/json/' + my_ip

        response = load(urlopen(url))
        response_timezone = load(urlopen(url_timezone))

        try:
            AnonymousUserDonation.objects.create(
                payment=payment,
                email=email,
                ip_address=my_ip,
                city=response['city'],
                region_code=response['region_code'],
                region_name=response['region_name'],
                time_zone=response_timezone['timezone'],
                country_name=response['country_name'],
                zip_code=response['zip']
            )
        except:
            AnonymousUserDonation.objects.create(email=email, payment=payment)
        request.session['payment'] = payment.id
        SITE_URL = settings.SITE_URL
        portfolio_link = SITE_URL + reverse('dashboard')
        context = {}
        context['project'] = project
        context['amount'] = donation_cents / 100.0
        if tip_cents != 0:
            context['tip_cents'] = tip_cents / 100.0
        else:
            context['tip_cents'] = False
        context['amount_cents'] = amount_cents / 100.0
        context['portfolio_link'] = portfolio_link
        request.session['project'] = project.title
        previous_url = request.META.get('HTTP_REFERER')
        request.session['url'] = previous_url
        context['first_name'] = "RE-volv"
        context['last_name'] = "supporter"
        send_donation_info(email, donation_cents / 100.0, email, project.title, address='')
        send_revolv_email(
            'post_donation',
            context, [email]
        )
        response = redirect('/signin/#signup')
        response.set_cookie('last_project', payment.project.title)
        return response
    else:
        SITE_URL = settings.SITE_URL
        portfolio_link = SITE_URL + reverse('dashboard')
        user = RevolvUserProfile.objects.get(user=request.user)
        context = {}
        context['project'] = project
        context['amount'] = donation_cents / 100.0
        if tip_cents != 0:
            context['tip_cents'] = tip_cents / 100.0
        else:
            context['tip_cents'] = False
        context['amount_cents'] = amount_cents / 100.0
        context['portfolio_link'] = portfolio_link + utils.get_query_string(request.user)
        context['first_name'] = request.user.first_name.title
        context['last_name'] = request.user.last_name.title

        amount = donation_cents / 100.0
        cover_photo = Project.objects.values_list('cover_photo', flat=True).filter(pk=pk)
        cover_photo = list(cover_photo)
        request.session['amount'] = str(amount)
        request.session['project'] = project.title
        previous_url = request.META.get('HTTP_REFERER')
        request.session['url'] = previous_url
        request.session['cover_photo'] = (SITE_URL + '/media/') + ''.join(cover_photo)
        request.session['social'] = "donation"
        send_donation_info(user.get_full_name(), donation_cents / 100.0, user.user.email, project.title, address='')
        send_revolv_email(
            'post_donation',
            context, [request.user.email]
        )
        return redirect('dashboard')
예제 #22
0
def stripe_payment(request, pk):
    try:
        token = request.POST['stripeToken']
        tip_cents = request.POST['metadata']
        amount_cents = request.POST['amount_cents']
        email = request.POST['stripeEmail']
    except KeyError:
        logger.exception('stripe_payment called without required POST data')
        return HttpResponseBadRequest('bad POST data')

    try:
        tip_cents = int(tip_cents)
        amount_cents = int(amount_cents)
        if not (0 < amount_cents < MAX_PAYMENT_CENTS):
            raise ValueError('amount_cents cannot be negative')
        if not (0 <= tip_cents < amount_cents):
            raise ValueError('tip_cents cannot be negative or more than project contribution')
    except ValueError:
        logger.exception('stripe_payment called with improper POST data')
        return HttpResponseBadRequest('bad POST data')

    project = get_object_or_404(Project, pk=pk)

    project_matching_donors = ProjectMatchingDonors.objects.filter(project=project, amount__gt=0)

    donation_cents = amount_cents - tip_cents

    error_msg = None
    try:
        stripe.Charge.create(source=token, description="Donation for "+project.title, currency="usd", amount=amount_cents)
    except stripe.error.CardError as e:
        body = e.json_body
        error_msg = body['error']['message']
    except stripe.error.APIConnectionError as e:
        body = e.json_body
        error_msg = body['error']['message']
    except Exception:
        error_msg = "Payment error. Re-volv has been notified."
        logger.exception(error_msg)
    if error_msg:
        return render(request, "project/project_donate_error.html", {
            "msg": error_msg, "project": project
        })

    if project_matching_donors:
        for donor in project_matching_donors:
            if donor.amount > donation_cents / 100:
                matching_donation = donation_cents / 100
                donor.amount = donor.amount - donation_cents / 100
                donor.save()
            else:
                matching_donation = donor.amount
                donor.amount = 0
                donor.save()

            tip = None

            Payment.objects.create(
                user=donor.matching_donor,
                entrant=donor.matching_donor,
                amount=matching_donation,
                project=project,
                tip=tip,
                payment_type=PaymentType.objects.get_stripe(),
            )
            send_donation_info(donor.matching_donor.get_full_name(), matching_donation, donor.matching_donor.user.email, project.title, address='')

    if request.user.is_authenticated():
        user = request.user.revolvuserprofile
    else:
        user_id = User.objects.get(username='******').pk
        user = RevolvUserProfile.objects.get(user_id=user_id)

    tip = None
    if tip_cents > 0:
        tip=Tip.objects.create(
            amount=tip_cents / 100.0,
            user=user,
        )

    payment=Payment.objects.create(
        user=user,
        entrant=user,
        amount=donation_cents/100.0,
        project=project,
        tip=tip,
        payment_type=PaymentType.objects.get_stripe(),
    )

    if not request.user.is_authenticated():
        request.session['payment'] = payment.id
        SITE_URL = settings.SITE_URL
        portfolio_link = SITE_URL + reverse('dashboard')
        context = {}
        context['project'] = project
        context['amount'] = donation_cents / 100.0
        context['tip_cents'] = tip_cents / 100.0
        context['amount_cents'] = amount_cents / 100.0
        context['portfolio_link'] = portfolio_link
        context['first_name'] = "RE-volv"
        context['last_name'] = "Supporter"
        send_donation_info(user.get_full_name(), donation_cents / 100.0, user.user.email, project.title, address='')
        send_revolv_email(
            'post_donation',
            context, [email]
        )
        return redirect('signin')
    else:
        SITE_URL = settings.SITE_URL
        portfolio_link = SITE_URL + reverse('dashboard')
        user=RevolvUserProfile.objects.get(user=request.user)
        context = {}
        context['project'] = project
        context['amount'] = donation_cents/100.0
        context['tip_cents'] = tip_cents / 100.0
        context['amount_cents'] = amount_cents/100.0
        context['portfolio_link'] = portfolio_link + utils.get_query_string(request.user)
        context['first_name'] = request.user.first_name
        context['last_name'] = request.user.last_name

        amount = donation_cents / 100.0
        cover_photo = Project.objects.values_list('cover_photo', flat=True).filter(pk=pk)
        cover_photo = list(cover_photo)
        request.session['amount'] = str(amount)
        request.session['project'] = project.title
        previous_url = request.META.get('HTTP_REFERER')
        request.session['url'] = previous_url
        request.session['cover_photo'] = (SITE_URL + '/media/') + ''.join(cover_photo)
        request.session['social'] = "donation"
        send_donation_info(user.get_full_name(), donation_cents/100.0, user.user.email, project.title, address='')
        send_revolv_email(
            'post_donation',
            context, [request.user.email]
        )
        return redirect('dashboard')
예제 #23
0
파일: views.py 프로젝트: saurabh1e/revolv
def stripe_payment(request, pk):
    try:
        token = request.POST['stripeToken']
        tip_cents = request.POST['metadata']
        amount_cents = request.POST['amount_cents']
        email = request.POST['stripeEmail']
    except KeyError:
        logger.exception('stripe_payment called without required POST data')
        return HttpResponseBadRequest('bad POST data')

    try:
        tip_cents = int(tip_cents)
        amount_cents = int(amount_cents)
        if not (0 < amount_cents < MAX_PAYMENT_CENTS):
            raise ValueError('amount_cents cannot be negative')
        if not (0 <= tip_cents <= amount_cents):
            raise ValueError(
                'tip_cents cannot be negative or more than project contribution'
            )
    except ValueError:
        logger.exception('stripe_payment called with improper POST data')
        return HttpResponseBadRequest('bad POST data')

    project = get_object_or_404(Project, pk=pk)

    project_matching_donors = ProjectMatchingDonors.objects.filter(
        project=project, amount__gt=0)

    donation_cents = amount_cents - tip_cents

    error_msg = None
    try:
        stripe.Charge.create(source=token,
                             description="Donation for " + project.title,
                             currency="usd",
                             amount=amount_cents)
    except stripe.error.CardError as e:
        body = e.json_body
        error_msg = body['error']['message']
    except stripe.error.APIConnectionError as e:
        body = e.json_body
        error_msg = body['error']['message']
    except Exception:
        error_msg = "Payment error. Re-volv has been notified."
        logger.exception(error_msg)
    if error_msg:
        return render(request, "project/project_donate_error.html", {
            "msg": error_msg,
            "project": project
        })

    if project_matching_donors:
        for donor in project_matching_donors:
            if donor.amount > donation_cents / 100:
                matching_donation = donation_cents / 100
                donor.amount = donor.amount - donation_cents / 100
                donor.save()
            else:
                matching_donation = donor.amount
                donor.amount = 0
                donor.save()

            tip = None

            Payment.objects.create(
                user=donor.matching_donor,
                entrant=donor.matching_donor,
                amount=matching_donation,
                project=project,
                tip=tip,
                payment_type=PaymentType.objects.get_stripe(),
            )
            send_donation_info(donor.matching_donor.get_full_name(),
                               matching_donation,
                               donor.matching_donor.user.email,
                               project.title,
                               address='')

    if request.user.is_authenticated():
        user = request.user.revolvuserprofile
    else:
        user_id = User.objects.get(username='******').pk
        user = RevolvUserProfile.objects.get(user_id=user_id)

    tip = None
    if tip_cents > 0:
        tip = Tip.objects.create(
            amount=tip_cents / 100.0,
            user=user,
        )

    payment = Payment.objects.create(
        user=user,
        entrant=user,
        amount=donation_cents / 100.0,
        project=project,
        tip=tip,
        payment_type=PaymentType.objects.get_stripe(),
    )
    if request.session.has_key("utm_params"):
        utm_params = request.session.get("utm_params")
        utm_source = utm_params.get("utm_source")
        utm_medium = utm_params.get("utm_medium")
        utm_campaign = utm_params.get("utm_campaign")
        utm_content = utm_params.get("utm_content")
        referral_source_track = ReferralSourceTrack.objects.create(
            source=utm_source,
            medium=utm_medium,
            campaign=utm_campaign,
            content=utm_content,
            payment=payment)

    if not request.user.is_authenticated():
        my_ip = load(urlopen('http://jsonip.com'))['ip']

        url = 'http://api.ipstack.com/' + my_ip + '?access_key=' + settings.IP_STACK_ACCESS_KEY

        url_timezone = 'http://ip-api.com/json/' + my_ip

        response = load(urlopen(url))
        response_timezone = load(urlopen(url_timezone))

        try:
            AnonymousUserDonation.objects.create(
                payment=payment,
                email=email,
                ip_address=my_ip,
                city=response['city'],
                region_code=response['region_code'],
                region_name=response['region_name'],
                time_zone=response_timezone['timezone'],
                country_name=response['country_name'],
                zip_code=response['zip'])
        except:
            AnonymousUserDonation.objects.create(email=email, payment=payment)
        request.session['payment'] = payment.id
        SITE_URL = settings.SITE_URL
        portfolio_link = SITE_URL + reverse('dashboard')
        context = {}
        context['project'] = project
        context['amount'] = donation_cents / 100.0
        if tip_cents != 0:
            context['tip_cents'] = tip_cents / 100.0
        else:
            context['tip_cents'] = False
        context['amount_cents'] = amount_cents / 100.0
        context['portfolio_link'] = portfolio_link
        request.session['project'] = project.title
        previous_url = request.META.get('HTTP_REFERER')
        request.session['url'] = previous_url
        context['first_name'] = "RE-volv"
        context['last_name'] = "supporter"
        send_donation_info(email,
                           donation_cents / 100.0,
                           email,
                           project.title,
                           address='')
        send_revolv_email('post_donation', context, [email])
        response = redirect('/signin/#signup')
        response.set_cookie('last_project', payment.project.title)
        return response
    else:
        SITE_URL = settings.SITE_URL
        portfolio_link = SITE_URL + reverse('dashboard')
        user = RevolvUserProfile.objects.get(user=request.user)
        context = {}
        context['project'] = project
        context['amount'] = donation_cents / 100.0
        if tip_cents != 0:
            context['tip_cents'] = tip_cents / 100.0
        else:
            context['tip_cents'] = False
        context['amount_cents'] = amount_cents / 100.0
        context['portfolio_link'] = portfolio_link + utils.get_query_string(
            request.user)
        context['first_name'] = request.user.first_name.title
        context['last_name'] = request.user.last_name.title

        amount = donation_cents / 100.0
        cover_photo = Project.objects.values_list('cover_photo',
                                                  flat=True).filter(pk=pk)
        cover_photo = list(cover_photo)
        request.session['amount'] = str(amount)
        request.session['project'] = project.title
        previous_url = request.META.get('HTTP_REFERER')
        request.session['url'] = previous_url
        request.session['cover_photo'] = (SITE_URL +
                                          '/media/') + ''.join(cover_photo)
        request.session['social'] = "donation"
        send_donation_info(user.get_full_name(),
                           donation_cents / 100.0,
                           user.user.email,
                           project.title,
                           address='')
        send_revolv_email('post_donation', context, [request.user.email])
        return redirect('dashboard')
예제 #24
0
 def test_get_query_string(self):
     self.assertIn("?url_auth_token=", get_query_string(self.user))
예제 #25
0
 def test_get_query_string(self):
     self.assertIn('?url_auth_token=', get_query_string(self.user))
예제 #26
0
def get_unsubscribe_url(request, user):
    base = reverse('redirector', args=["unsubscribed"], request=request)
    token = get_query_string(user)
    return base + token + "&unsubscribe=true"
예제 #27
0
def stripe_payment(request, pk):
    try:
        token = request.POST['stripeToken']
        tip_cents = request.POST['metadata']
        amount_cents = request.POST['amount_cents']
    except KeyError:
        logger.exception('stripe_payment called without required POST data')
        return HttpResponseBadRequest('bad POST data')

    try:
        tip_cents = int(tip_cents)
        amount_cents = int(amount_cents)
        if not (0 < amount_cents < MAX_PAYMENT_CENTS):
            raise ValueError('amount_cents cannot be negative')
        if not (0 <= tip_cents < amount_cents):
            raise ValueError(
                'tip_cents cannot be negative or more than project contribution'
            )
    except ValueError:
        logger.exception('stripe_payment called with improper POST data')
        return HttpResponseBadRequest('bad POST data')

    project = get_object_or_404(Project, pk=pk)

    project_matching_donors = ProjectMatchingDonors.objects.filter(
        project=project, amount__gt=0)

    donation_cents = amount_cents - tip_cents

    error_msg = None
    try:
        stripe.Charge.create(source=token,
                             description="Donation for " + project.title,
                             currency="usd",
                             amount=amount_cents)
    except stripe.error.CardError as e:
        body = e.json_body
        error_msg = body['error']['message']
    except stripe.error.APIConnectionError as e:
        body = e.json_body
        error_msg = body['error']['message']
    except Exception:
        error_msg = "Payment error. Re-volv has been notified."
        logger.exception(error_msg)
    if error_msg:
        return render(request, "project/project_donate_error.html", {
            "msg": error_msg,
            "project": project
        })

    if project_matching_donors:
        for donor in project_matching_donors:
            if donor.amount > donation_cents / 100:
                matching_donation = donation_cents / 100
                donor.amount = donor.amount - donation_cents / 100
                donor.save()
            else:
                matching_donation = donor.amount
                donor.amount = 0
                donor.save()

            tip = None

            Payment.objects.create(
                user=donor.matching_donor,
                entrant=donor.matching_donor,
                amount=matching_donation,
                project=project,
                tip=tip,
                payment_type=PaymentType.objects.get_stripe(),
            )

    tip = None
    if tip_cents > 0:
        tip = Tip.objects.create(
            amount=tip_cents / 100.0,
            user=request.user.revolvuserprofile,
        )

    Payment.objects.create(
        user=request.user.revolvuserprofile,
        entrant=request.user.revolvuserprofile,
        amount=donation_cents / 100.0,
        project=project,
        tip=tip,
        payment_type=PaymentType.objects.get_stripe(),
    )

    SITE_URL = settings.SITE_URL
    portfolio_link = SITE_URL + reverse('dashboard')
    context = {}
    context['user'] = request.user
    context['project'] = project
    context['amount'] = donation_cents / 100.0
    context['tip_cents'] = tip_cents / 100.0
    context['amount_cents'] = amount_cents / 100.0
    context['portfolio_link'] = portfolio_link + utils.get_query_string(
        request.user)
    send_revolv_email('post_donation', context, [request.user.email])
    return redirect('dashboard')
예제 #28
0
 def test_token_in_POST_request(self):
     response = self.client.post("/" + get_query_string(self.user))
     self.assertUserLoggedIn(response, redirect_url=None)
예제 #29
0
 def test_get_query_string_with_scope(self):
     # Tokens v2 only contain URL-safe characters. There's no escaping.
     self.assertEqual(
         get_query_string(self.user, scope="test"),
         "?sesame=" + get_token(self.user, scope="test"),
     )
예제 #30
0
파일: views.py 프로젝트: ShivamBh/risk_pr
def tokenurl(request):
    user = request.user
    token = utils.get_query_string(user)
    return HttpResponse(token)