Compare commits

..

1 commit

Author SHA1 Message Date
PCoder
32615e30ac Update Chanelog for 2.12.1 2020-07-21 23:07:25 +05:30
35 changed files with 761 additions and 2021 deletions

View file

@ -1 +0,0 @@
.git

View file

@ -1,16 +1,3 @@
3.2: 2021-02-07
* 8816: Update order confirmation text to better prepared for payment dispute
* supportticket#22990: Fix: can't add a deleted card
3.1: 2021-01-11
* 8781: Fix error is setting a default card (MR!746)
3.0: 2021-01-07
* 8393: Implement SCA for stripe payments (MR!745)
* 8691: Implment check_vm_templates management command (MR!744)
2.14: 2020-12-07
* 8692: Create a script that fixes django db for the order after celery error (MR!743)
2.13: 2020-12-02
* 8654: Fix 500 error on invoices list for the user contact+devuanhosting.com@virus.media (MR!742)
* 8593: Escape user's ssh key in xml-rpc call to create VM (MR!741)
2.12.1: 2020-07-21
* 8307: Introduce "Exclude vat calculations" for Generic Products (MR!740)
* Change DE VAT rate to 16% from 19% (MR!739)

View file

@ -1,18 +0,0 @@
FROM python:3.10.0-alpine3.15
WORKDIR /usr/src/app
RUN apk add --update --no-cache \
git \
build-base \
openldap-dev \
python3-dev \
libpq-dev \
&& rm -rf /var/cache/apk/*
# FIX https://github.com/python-ldap/python-ldap/issues/432
RUN echo 'INPUT ( libldap.so )' > /usr/lib/libldap_r.so
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY ./ .

View file

@ -14,12 +14,6 @@ help:
@echo ' make rsync_upload '
@echo ' make install_debian_packages '
buildimage:
docker build -t dynamicweb:$$(git describe) .
releaseimage: buildimage
./release.sh
collectstatic:
$(PY?) $(BASEDIR)/manage.py collectstatic

View file

@ -8,7 +8,7 @@ msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2021-02-07 11:10+0000\n"
"POT-Creation-Date: 2020-03-24 07:02+0000\n"
"PO-Revision-Date: 2018-03-30 23:22+0000\n"
"Last-Translator: b'Anonymous User <coder.purple+25@gmail.com>'\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
@ -451,43 +451,38 @@ msgstr "Dein Gesamtpreis"
#, python-format
msgid ""
" By clicking \"Place order\" you agree to our <a href=\"https://"
"datacenterlight.ch/en-us/cms/terms-of-service/\">Terms of Service</a> and "
"this plan will charge your credit card account with %(total_price)s CHF/year"
"By clicking \"Place order\" this plan will charge your credit card account "
"with %(total_price)s CHF/year"
msgstr ""
"Indem Du auf \"Bestellung aufgeben\" klickst, erklärst Du dich mit unseren <a href=\"https://"
"datacenterlight.ch/en-us/cms/terms-of-service/\">Nutzungsbedingungen</a> einverstanden und Dein Kreditkartenkonto wird mit %(total_price)s CHF/Jahr belastet."
"Wenn Du \"bestellen\" auswählst, wird Deine Kreditkarte mit %(total_price)s "
"CHF pro Jahr belastet"
#, python-format
msgid ""
"\n"
" By clicking \"Place order\" you agree to "
"our <a href=\"https://datacenterlight.ch/en-us/cms/terms-of-service/\">Terms "
"of Service</a> and this plan will charge your credit card account with "
"%(total_price)s CHF/month"
"By clicking \"Place order\" this plan will charge your credit card account "
"with %(total_price)s CHF/month"
msgstr ""
"\n"
"Indem Du auf \"Bestellung aufgeben\" klickst, erklärst Du dich mit unseren <a href=\"https://"
"datacenterlight.ch/en-us/cms/terms-of-service/\">Nutzungsbedingungen</a> einverstanden und Dein Kreditkartenkonto wird mit %(total_price)s CHF/Monat belastet."
"Wenn Du \"bestellen\" auswählst, wird Deine Kreditkarte mit %(total_price)s "
"CHF pro Monat belastet"
#, fuzzy, python-format
#| msgid ""
#| "By clicking \"Place order\" this payment will charge your credit card "
#| "account with a one time amount of %(total_price)s CHF"
msgid ""
"By clicking \"Place order\" this payment will charge your credit card "
"account with a one time amount of %(total_price)s CHF"
msgstr ""
"Wenn Du \"bestellen\" auswählst, wird Deine Kreditkarte mit "
"%(vm_total_price)s CHF pro Monat belastet"
#, python-format
msgid ""
"By clicking \"Place order\" you agree to our <a href=\"https://"
"datacenterlight.ch/en-us/cms/terms-of-service/\">Terms of Service</a> and "
"this plan will charge your credit card account with %(total_price)s CHF"
"By clicking \"Place order\" this plan will charge your credit card account "
"with %(vm_total_price)s CHF/month"
msgstr ""
"Indem Du auf \"Bestellung aufgeben\" klickst, erklärst Du dich mit unseren <a href=\"https://"
"datacenterlight.ch/de/cms/terms-of-service/\">Nutzungsbedingungen</a> einverstanden und Dein Kreditkartenkonto wird mit %(total_price)s CHF belastet."
#, python-format
msgid ""
"By clicking \"Place order\" you agree to our <a href=\"https://"
"datacenterlight.ch/en-us/cms/terms-of-service/\">Terms of Service</a> and "
"this plan will charge your credit card account with %(vm_total_price)s CHF/"
"month"
msgstr ""
"Indem Du auf \"Bestellung aufgeben\" klickst, erklärst Du dich mit unseren <a href=\"https://"
"datacenterlight.ch/de/cms/terms-of-service/\">Nutzungsbedingungen</a> einverstanden und Dein Kreditkartenkonto wird mit %(vm_total_price)s CHF/Monat belastet"
"Wenn Du \"bestellen\" auswählst, wird Deine Kreditkarte mit "
"%(vm_total_price)s CHF pro Monat belastet"
msgid "Place order"
msgstr "Bestellen"
@ -606,22 +601,16 @@ msgid "Incorrect pricing name. Please contact support{support_email}"
msgstr ""
"Ungültige Preisbezeichnung. Bitte kontaktiere den Support{support_email}"
#, python-brace-format
msgid "{user} does not have permission to access the card"
msgstr "{user} hat keine Erlaubnis auf diese Karte zuzugreifen"
msgid "An error occurred. Details: {}"
msgstr "Ein Fehler ist aufgetreten. Details: {}"
msgid "Confirm Order"
msgstr "Bestellung Bestätigen"
#, fuzzy
#| msgid "Thank you!"
msgid "Thank you !"
msgstr "Vielen Dank!"
msgid "Your product will be provisioned as soon as we receive the payment."
msgstr ""
#, python-brace-format
msgid "An error occurred while associating the card. Details: {details}"
msgstr ""
"Beim Verbinden der Karte ist ein Fehler aufgetreten. Details: {details}"
msgid "Error."
msgstr ""
@ -632,21 +621,10 @@ msgstr ""
"Es ist ein Fehler bei der Zahlung betreten. Du wirst nach dem Schliessen vom "
"Popup zur Bezahlseite weitergeleitet."
msgid "Thank you for the order."
msgstr "Danke für Deine Bestellung."
msgid ""
"Your product will be provisioned as soon as we receive a payment "
"confirmation from Stripe. We will send you a confirmation email. You can "
"always contact us at support@datacenterlight.ch"
#, python-brace-format
msgid "An error occurred while associating the card. Details: {details}"
msgstr ""
msgid ""
"Your VM will be up and running in a few moments. We will send you a "
"confirmation email as soon as it is ready."
msgstr ""
"Deine VM ist gleich bereit. Wir senden Dir eine Bestätigungsemail, sobald Du "
"auf sie zugreifen kannst."
"Beim Verbinden der Karte ist ein Fehler aufgetreten. Details: {details}"
msgid " This is a monthly recurring plan."
msgstr "Dies ist ein monatlich wiederkehrender Plan."
@ -686,31 +664,15 @@ msgstr ""
"Du wirst bald eine Bestätigungs-E-Mail über die Zahlung erhalten. Du kannst "
"jederzeit unter info@ungleich.ch kontaktieren."
#, python-format
#~ msgid ""
#~ "By clicking \"Place order\" this plan will charge your credit card "
#~ "account with %(total_price)s CHF/month"
#~ msgstr ""
#~ "Wenn Du \"bestellen\" auswählst, wird Deine Kreditkarte mit "
#~ "%(total_price)s CHF pro Monat belastet"
msgid "Thank you for the order."
msgstr "Danke für Deine Bestellung."
#, fuzzy, python-format
#~| msgid ""
#~| "By clicking \"Place order\" this payment will charge your credit card "
#~| "account with a one time amount of %(total_price)s CHF"
#~ msgid ""
#~ "By clicking \"Place order\" this payment will charge your credit card "
#~ "account with a one time amount of %(total_price)s CHF"
#~ msgstr ""
#~ "Wenn Du \"bestellen\" auswählst, wird Deine Kreditkarte mit "
#~ "%(vm_total_price)s CHF pro Monat belastet"
#, python-brace-format
#~ msgid "{user} does not have permission to access the card"
#~ msgstr "{user} hat keine Erlaubnis auf diese Karte zuzugreifen"
#~ msgid "An error occurred. Details: {}"
#~ msgstr "Ein Fehler ist aufgetreten. Details: {}"
msgid ""
"Your VM will be up and running in a few moments. We will send you a "
"confirmation email as soon as it is ready."
msgstr ""
"Deine VM ist gleich bereit. Wir senden Dir eine Bestätigungsemail, sobald Du "
"auf sie zugreifen kannst."
#~ msgid "Price"
#~ msgstr "Preise"
@ -786,6 +748,9 @@ msgstr ""
#~ "Wir werden dann sobald als möglich Ihren Beta-Zugang erstellen und Sie "
#~ "daraufhin kontaktieren.Bis dahin bitten wir Sie um etwas Geduld."
#~ msgid "Thank you!"
#~ msgstr "Vielen Dank!"
#~ msgid "Thank you for order! Our team will contact you via email"
#~ msgstr ""
#~ "Vielen Dank für die Bestellung. Unser Team setzt sich sobald wie möglich "

View file

@ -1,65 +0,0 @@
from django.core.management.base import BaseCommand
from opennebula_api.models import OpenNebulaManager
from datacenterlight.models import VMTemplate
from membership.models import CustomUser
from django.conf import settings
from time import sleep
import datetime
import json
import logging
import os
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = '''Checks all VM templates to find if they can be instantiated'''
def add_arguments(self, parser):
parser.add_argument('user_email', type=str)
def handle(self, *args, **options):
result_dict = {}
user_email = options['user_email'] if 'user_email' in options else ""
if user_email:
cu = CustomUser.objects.get(email=user_email)
specs = {'cpu': 1, 'memory': 1, 'disk_size': 10}
manager = OpenNebulaManager(email=user_email, password=cu.password)
pub_keys = [settings.TEST_MANAGE_SSH_KEY_PUBKEY]
PROJECT_PATH = os.path.abspath(os.path.dirname(__name__))
if not os.path.exists("%s/outputs" % PROJECT_PATH):
os.mkdir("%s/outputs" % PROJECT_PATH)
for vm_template in VMTemplate.objects.all():
vm_name = 'test-%s' % vm_template.name
vm_id = manager.create_vm(
template_id=vm_template.opennebula_vm_template_id,
specs=specs,
ssh_key='\n'.join(pub_keys),
vm_name=vm_name
)
if vm_id and vm_id > 0:
result_dict[vm_name] = "%s OK, created VM %s" % (
'%s %s %s' % (vm_template.opennebula_vm_template_id,
vm_template.name, vm_template.vm_type),
vm_id
)
self.stdout.write(self.style.SUCCESS(result_dict[vm_name]))
manager.delete_vm(vm_id)
else:
result_dict[vm_name] = '''Error creating VM %s, template_id
%s %s''' % (vm_name,
vm_template.opennebula_vm_template_id,
vm_template.vm_type)
self.stdout.write(self.style.ERROR(result_dict[vm_name]))
sleep(1)
date_str = datetime.datetime.strftime(
datetime.datetime.now(), '%Y%m%d%H%M%S'
)
with open("%s/outputs/check_vm_templates_%s.txt" %
(PROJECT_PATH, date_str),
'w',
encoding='utf-8') as f:
f.write(json.dumps(result_dict))
self.stdout.write(self.style.SUCCESS("Done"))

View file

@ -1,76 +0,0 @@
from django.core.management.base import BaseCommand
from datacenterlight.tasks import handle_metadata_and_emails
from opennebula_api.models import OpenNebulaManager
from membership.models import CustomUser
import logging
import json
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = '''Updates the DB after manual creation of VM'''
def add_arguments(self, parser):
parser.add_argument('vm_id', type=int)
parser.add_argument('order_id', type=int)
parser.add_argument('user', type=str)
parser.add_argument('specs', type=str)
parser.add_argument('template', type=str)
def handle(self, *args, **options):
vm_id = options['vm_id']
order_id = options['order_id']
user_str = options['user']
specs_str = options['specs']
template_str = options['template']
json_acceptable_string = user_str.replace("'", "\"")
user_dict = json.loads(json_acceptable_string)
json_acceptable_string = specs_str.replace("'", "\"")
specs = json.loads(json_acceptable_string)
json_acceptable_string = template_str.replace("'", "\"")
template = json.loads(json_acceptable_string)
if vm_id <= 0:
self.stdout.write(self.style.ERROR(
'vm_id can\'t be less than or 0. Given: %s' % vm_id))
return
if vm_id <= 0:
self.stdout.write(self.style.ERROR(
'order_id can\'t be less than or 0. Given: %s' % vm_id))
return
if specs_str is None or specs_str == "":
self.stdout.write(
self.style.ERROR('specs can\'t be empty or None'))
return
user = {
'name': user_dict['name'],
'email': user_dict['email'],
'username': user_dict['username'],
'pass': user_dict['pass'],
'request_scheme': user_dict['request_scheme'],
'request_host': user_dict['request_host'],
'language': user_dict['language'],
}
cu = CustomUser.objects.get(username=user.get('username'))
# Create OpenNebulaManager
self.stdout.write(
self.style.SUCCESS(
'Connecting using %s' % (cu.username)
)
)
manager = OpenNebulaManager(email=cu.username, password=cu.password)
handle_metadata_and_emails(order_id, vm_id, manager, user, specs,
template)
self.stdout.write(
self.style.SUCCESS(
'Done handling metadata and emails for %s %s %s' % (
order_id,
vm_id,
str(user)
)
)
)

View file

@ -56,6 +56,11 @@ def create_vm_task(self, vm_template_id, user, specs, template, order_id):
"Running create_vm_task on {}".format(current_task.request.hostname))
vm_id = None
try:
final_price = (
specs.get('total_price') if 'total_price' in specs
else specs.get('price')
)
if 'pass' in user:
on_user = user.get('username')
on_pass = user.get('pass')
@ -87,52 +92,6 @@ def create_vm_task(self, vm_template_id, user, specs, template, order_id):
if vm_id is None:
raise Exception("Could not create VM")
handle_metadata_and_emails(order_id, vm_id, manager, user, specs,
template)
except Exception as e:
logger.error(str(e))
try:
retry_task(self)
except MaxRetriesExceededError:
msg_text = 'Finished {} retries for create_vm_task'.format(
self.request.retries)
logger.error(msg_text)
# Try sending email and stop
email_data = {
'subject': '{} CELERY TASK ERROR: {}'.format(settings.DCL_TEXT,
msg_text),
'from_email': current_task.request.hostname,
'to': settings.DCL_ERROR_EMAILS_TO_LIST,
'body': ',\n'.join(str(i) for i in self.request.args)
}
email = EmailMessage(**email_data)
email.send()
return
return vm_id
def handle_metadata_and_emails(order_id, vm_id, manager, user, specs,
template):
"""
Handle's setting up of the metadata in Stripe and database and sending of
emails to the user after VM creation
:param order_id: the hosting order id
:param vm_id: the id of the vm created
:param manager: the OpenNebula Manager instance
:param user: the user's dict passed to the celery task
:param specs: the specification's dict passed to the celery task
:param template: the template dict passed to the celery task
:return:
"""
custom_user = CustomUser.objects.get(email=user.get('email'))
final_price = (
specs.get('total_price') if 'total_price' in specs
else specs.get('price')
)
# Update HostingOrder with the created vm_id
hosting_order = HostingOrder.objects.filter(id=order_id).first()
error_msg = None
@ -195,7 +154,7 @@ def handle_metadata_and_emails(order_id, vm_id, manager, user, specs,
email_data = {
'subject': settings.DCL_TEXT + " Order from %s" % context['email'],
'from_email': settings.DCL_SUPPORT_FROM_ADDRESS,
'to': ['dcl-orders@ungleich.ch'],
'to': ['info@ungleich.ch'],
'body': "\n".join(
["%s=%s" % (k, v) for (k, v) in context.items()]),
'reply_to': [context['email']],
@ -234,3 +193,24 @@ def handle_metadata_and_emails(order_id, vm_id, manager, user, specs,
logger.debug("New VM ID is {vm_id}".format(vm_id=vm_id))
if vm_id > 0:
get_or_create_vm_detail(custom_user, manager, vm_id)
except Exception as e:
logger.error(str(e))
try:
retry_task(self)
except MaxRetriesExceededError:
msg_text = 'Finished {} retries for create_vm_task'.format(
self.request.retries)
logger.error(msg_text)
# Try sending email and stop
email_data = {
'subject': '{} CELERY TASK ERROR: {}'.format(settings.DCL_TEXT,
msg_text),
'from_email': current_task.request.hostname,
'to': settings.DCL_ERROR_EMAILS_TO_LIST,
'body': ',\n'.join(str(i) for i in self.request.args)
}
email = EmailMessage(**email_data)
email.send()
return
return vm_id

View file

@ -2,14 +2,6 @@
{% load staticfiles bootstrap3 i18n custom_tags humanize %}
{% block content %}
<script>
{% if payment_intent_secret %}
console.log("payment_intent_secret");
window.paymentIntentSecret = "{{payment_intent_secret}}";
{% else %}
console.log("No payment_intent_secret");
{% endif %}
</script>
<div id="order-detail{{order.pk}}" class="order-detail-container">
{% if messages %}
<div class="alert alert-warning">
@ -278,16 +270,15 @@
{% if generic_payment_details %}
{% if generic_payment_details.recurring %}
{% if generic_payment_details.recurring_interval == 'year' %}
<div class="dcl-place-order-text">{% blocktrans with total_price=generic_payment_details.amount|floatformat:2|intcomma %} By clicking "Place order" you agree to our <a href="https://datacenterlight.ch/en-us/cms/terms-of-service/">Terms of Service</a> and this plan will charge your credit card account with {{ total_price }} CHF/year{% endblocktrans %}.</div>
<div class="dcl-place-order-text">{% blocktrans with total_price=generic_payment_details.amount|floatformat:2|intcomma %}By clicking "Place order" this plan will charge your credit card account with {{total_price}} CHF/year{% endblocktrans %}.</div>
{% else %}
<div class="dcl-place-order-text">{% blocktrans with total_price=generic_payment_details.amount|floatformat:2|intcomma %}
By clicking "Place order" you agree to our <a href="https://datacenterlight.ch/en-us/cms/terms-of-service/">Terms of Service</a> and this plan will charge your credit card account with {{ total_price }} CHF/month{% endblocktrans %}.</div>
<div class="dcl-place-order-text">{% blocktrans with total_price=generic_payment_details.amount|floatformat:2|intcomma %}By clicking "Place order" this plan will charge your credit card account with {{total_price}} CHF/month{% endblocktrans %}.</div>
{% endif %}
{% else %}
<div class="dcl-place-order-text">{% blocktrans with total_price=generic_payment_details.amount|floatformat:2|intcomma %}By clicking "Place order" you agree to our <a href="https://datacenterlight.ch/en-us/cms/terms-of-service/">Terms of Service</a> and this plan will charge your credit card account with {{ total_price }} CHF{% endblocktrans %}.</div>
<div class="dcl-place-order-text">{% blocktrans with total_price=generic_payment_details.amount|floatformat:2|intcomma %}By clicking "Place order" this payment will charge your credit card account with a one time amount of {{total_price}} CHF{% endblocktrans %}.</div>
{% endif %}
{% else %}
<div class="dcl-place-order-text">{% blocktrans with vm_total_price=vm.total_price|floatformat:2|intcomma %}By clicking "Place order" you agree to our <a href="https://datacenterlight.ch/en-us/cms/terms-of-service/">Terms of Service</a> and this plan will charge your credit card account with {{ vm_total_price }} CHF/month{% endblocktrans %}.</div>
<div class="dcl-place-order-text">{% blocktrans with vm_total_price=vm.total_price|floatformat:2|intcomma %}By clicking "Place order" this plan will charge your credit card account with {{vm_total_price}} CHF/month{% endblocktrans %}.</div>
{% endif %}
</div>
<div class="col-sm-4 order-confirm-btn text-right">
@ -330,14 +321,5 @@
<script type="text/javascript">
{% trans "Some problem encountered. Please try again later." as err_msg %}
var create_vm_error_message = '{{err_msg|safe}}';
var pm_id = '{{id_payment_method}}';
var error_url = '{{ error_msg.redirect }}';
var error_msg = '{{ error_msg.msg_body }}';
var error_title = '{{ error_msg.msg_title }}';
var success_msg = '{{ success_msg.msg_body }}';
var success_title = '{{ success_msg.msg_title }}';
var success_url = '{{ success_msg.redirect }}';
window.stripeKey = "{{stripe_key}}";
window.isSubscription = ("{{is_subscription}}" === 'true');
</script>
{%endblock%}

View file

@ -72,7 +72,6 @@ def get_line_item_from_hosting_order_charge(hosting_order_id):
:param hosting_order_id: the HostingOrder id
:return:
"""
try:
hosting_order = HostingOrder.objects.get(id = hosting_order_id)
if hosting_order.stripe_charge_id:
return mark_safe("""
@ -93,9 +92,6 @@ def get_line_item_from_hosting_order_charge(hosting_order_id):
))
else:
return ""
except Exception as ex:
logger.error("Error %s" % str(ex))
return ""
@register.filter('get_line_item_from_stripe_invoice')
@ -114,7 +110,7 @@ def get_line_item_from_stripe_invoice(invoice):
plan_name = ""
for line_data in invoice["lines"]["data"]:
if is_first:
plan_name = line_data.plan.name if line_data.plan is not None else ""
plan_name = line_data.plan.name
start_date = line_data.period.start
end_date = line_data.period.end
is_first = False

View file

@ -20,7 +20,7 @@ logger = logging.getLogger(__name__)
eu_countries = ['at', 'be', 'bg', 'ch', 'cy', 'cz', 'hr', 'dk',
'ee', 'fi', 'fr', 'mc', 'de', 'gr', 'hu', 'ie', 'it',
'lv', 'lu', 'mt', 'nl', 'pl', 'pt', 'ro','sk', 'si', 'es',
'lv', 'lu', 'mt', 'nl', 'po', 'pt', 'ro','sk', 'si', 'es',
'se', 'gb']
@ -38,7 +38,6 @@ def get_cms_integration(name):
def create_vm(billing_address_data, stripe_customer_id, specs,
stripe_subscription_obj, card_details_dict, request,
vm_template_id, template, user):
logger.debug("In create_vm")
billing_address = BillingAddress(
cardholder_name=billing_address_data['cardholder_name'],
street_address=billing_address_data['street_address'],
@ -103,6 +102,8 @@ def create_vm(billing_address_data, stripe_customer_id, specs,
create_vm_task.delay(vm_template_id, user, specs, template, order.id)
clear_all_session_vars(request)
def clear_all_session_vars(request):
if request.session is not None:
@ -111,8 +112,7 @@ def clear_all_session_vars(request):
'token', 'customer', 'generic_payment_type',
'generic_payment_details', 'product_id',
'order_confirm_url', 'new_user_hosting_key_id',
'vat_validation_status', 'billing_address_id',
'id_payment_method']:
'vat_validation_status', 'billing_address_id']:
if session_var in request.session:
del request.session[session_var]

File diff suppressed because it is too large Load diff

View file

@ -376,6 +376,8 @@ msgid ""
" digitalglarus.ch<br/>\n"
" hack4lgarus.ch<br/>\n"
" ipv6onlyhosting.com<br/>\n"
" ipv6onlyhosting.ch<br/>\n"
" ipv6onlyhosting.net<br/>\n"
" django-hosting.ch<br/>\n"
" rails-hosting.ch<br/>\n"
" node-hosting.ch<br/>\n"
@ -634,8 +636,8 @@ msgstr ""
"Internetangebot der ungleich glarus ag, welches unter den nachfolgenden "
"Domains erreichbar ist:<br/><br/>ungleich.ch<br/>datacenterlight.ch<br/"
">devuanhosting.com<br/>devuanhosting.ch<br/>digitalglarus.ch<br/>hack4lgarus."
"ch<br/>ipv6onlyhosting.com<br/>django-hosting.ch<br/>rails-hosting.ch"
"<br/>node-hosting.ch<br/>blog."
"ch<br/>ipv6onlyhosting.com<br/>ipv6onlyhosting.ch<br/>ipv6onlyhosting.net<br/"
">django-hosting.ch<br/>rails-hosting.ch<br/>node-hosting.ch<br/>blog."
"ungleich.ch<br/><br/>Der Datenschutzbeauftragte des Verantwortlichen ist:<br/"
"><br/>Sanghee Kim<br/>ungleich glarus ag<br/>Bahnhofstrasse 1<br/>8783 "
"Linthal (CH)<br/>E-Mail: <a href=\"mailto:sanghee.kim@ungleich.ch\">sanghee."
@ -836,4 +838,3 @@ msgstr ""
#~ msgid "index/?$"
#~ msgstr "index/?$"

View file

@ -631,6 +631,8 @@ GOOGLE_ANALYTICS_PROPERTY_IDS = {
'datacenterlight.ch': 'UA-62285904-8',
'devuanhosting.ch': 'UA-62285904-9',
'devuanhosting.com': 'UA-62285904-9',
'ipv6onlyhosting.ch': 'UA-62285904-10',
'ipv6onlyhosting.net': 'UA-62285904-10',
'ipv6onlyhosting.com': 'UA-62285904-10',
'comic.ungleich.ch': 'UA-62285904-13',
'127.0.0.1:8000': 'localhost',

View file

@ -28,7 +28,9 @@ ALLOWED_HOSTS = [
".devuanhosting.ch",
".devuanhosting.com",
".digitalezukunft.ch",
".ipv6onlyhosting.ch",
".ipv6onlyhosting.com",
".ipv6onlyhosting.net",
".digitalglarus.ch",
".hack4glarus.ch",
".xn--nglarus-n2a.ch"

View file

@ -2,7 +2,6 @@ import datetime
import logging
import subprocess
import tempfile
import xml
from django import forms
from django.conf import settings
@ -208,7 +207,7 @@ class UserHostingKeyForm(forms.ModelForm):
logger.debug(
"Not a correct ssh format {error}".format(error=str(cpe)))
raise forms.ValidationError(KEY_ERROR_MESSAGE)
return xml.sax.saxutils.escape(openssh_pubkey_str)
return openssh_pubkey_str
def clean_name(self):
INVALID_NAME_MESSAGE = _("Comma not accepted in the name of the key")

View file

@ -8,7 +8,7 @@ msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2021-02-07 10:19+0000\n"
"POT-Creation-Date: 2019-11-15 16:40+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
@ -211,9 +211,6 @@ msgstr "Bezahlbares VM Hosting in der Schweiz"
msgid "My Dashboard"
msgstr "Mein Dashboard"
msgid "Welcome"
msgstr ""
msgid "My VMs"
msgstr "Meine VMs"
@ -367,11 +364,6 @@ msgstr "Abgelehnt"
msgid "Billed to"
msgstr "Rechnungsadresse"
#, fuzzy
#| msgid "Card Number"
msgid "VAT Number"
msgstr "Kreditkartennummer"
msgid "Payment method"
msgstr "Bezahlmethode"
@ -399,9 +391,6 @@ msgstr "Festplattenkapazität"
msgid "Subtotal"
msgstr "Zwischensumme"
msgid "VAT for"
msgstr ""
msgid "VAT"
msgstr "Mehrwertsteuer"
@ -435,22 +424,18 @@ msgstr "ZURÜCK ZUR LISTE"
msgid "Some problem encountered. Please try again later."
msgstr "Ein Problem ist aufgetreten. Bitte versuche es später noch einmal."
#, fuzzy
#| msgid "Description"
msgid "Subscriptions"
msgstr "Beschreibung"
#, fuzzy
#| msgid "One time payment"
msgid "One-time payments"
msgstr "Einmalzahlung"
msgid "VM ID"
msgstr ""
msgid "IP Address"
msgstr "IP-Adresse"
msgid "See Invoice"
msgstr "Siehe Rechnung"
msgid "Page"
msgstr "Seite"
msgid "Log in"
msgstr "Anmelden"
@ -495,13 +480,11 @@ msgstr "Bestellungsübersicht"
#, python-format
msgid ""
"By clicking \"Place order\" you agree to our <a href=\"https://"
"datacenterlight.ch/en-us/cms/terms-of-service/\">Terms of Service</a> and "
"this plan will charge your credit card account with %(vm_price)s CHF/month."
"By clicking \"Place order\" this plan will charge your credit card account "
"with %(vm_price)s CHF/month"
msgstr ""
"Indem Du auf \"Bestellung aufgeben\" klickst, erklärst Du dich mit unseren"
" <a href=\"https://"
"datacenterlight.ch/de/cms/terms-of-service/\">Nutzungsbedingungen</a> einverstanden und Dein Kreditkartenkonto wird mit %(vm_price)s CHF/Monat belastet."
"Wenn Du \"bestellen\" auswählst, wird Deine Kreditkarte mit %(vm_price)s CHF "
"pro Monat belastet"
msgid "Place order"
msgstr "Bestellen"
@ -521,12 +504,6 @@ msgstr "Schliessen"
msgid "Order Nr."
msgstr "Bestellung Nr."
msgid "See Invoice"
msgstr "Siehe Rechnung"
msgid "Page"
msgstr "Seite"
msgid "Your Order"
msgstr "Deine Bestellung"
@ -595,19 +572,6 @@ msgstr "Absenden"
msgid "Password reset"
msgstr "Passwort zurücksetzen"
#, fuzzy
#| msgid "Key name"
msgid "My Username"
msgstr "Key-Name"
msgid "Your VAT number has been verified"
msgstr ""
msgid ""
"Your VAT number is under validation. VAT will be adjusted, once the "
"validation is complete."
msgstr ""
msgid "UPDATE"
msgstr "AKTUALISIEREN"
@ -809,15 +773,21 @@ msgstr "Dein Passwort konnte nicht zurückgesetzt werden."
msgid "The reset password link is no longer valid."
msgstr "Der Link zum Zurücksetzen Deines Passwortes ist nicht mehr gültig."
msgid "Could not set a default card."
msgstr ""
msgid "Card deassociation successful"
msgstr "Die Verbindung mit der Karte wurde erfolgreich aufgehoben"
msgid "You are not permitted to do this operation"
msgstr "Du hast keine Erlaubnis um diese Operation durchzuführen"
msgid "The selected card does not exist"
msgstr "Die ausgewählte Karte existiert nicht"
msgid "Billing address updated successfully"
msgstr "Die Rechnungsadresse wurde erfolgreich aktualisiert"
msgid "You seem to have already added this card"
msgstr "Es scheint, als hättest du diese Karte bereits hinzugefügt"
#, python-brace-format
msgid "An error occurred while associating the card. Details: {details}"
msgstr ""
@ -882,8 +852,7 @@ msgstr "Ungültige Speicher-Grösse"
#, python-brace-format
msgid "Incorrect pricing name. Please contact support{support_email}"
msgstr ""
"Ungültige Preisbezeichnung. Bitte kontaktiere den Support{support_email}"
msgstr "Ungültige Preisbezeichnung. Bitte kontaktiere den Support{support_email}"
msgid ""
"We could not find the requested VM. Please "
@ -902,9 +871,7 @@ msgstr "Fehler beenden VM"
msgid ""
"VM terminate action timed out. Please contact support@datacenterlight.ch for "
"further information."
msgstr ""
"VM beendet wegen Zeitüberschreitung. Bitte kontaktiere "
"support@datacenterlight.ch für weitere Informationen."
msgstr "VM beendet wegen Zeitüberschreitung. Bitte kontaktiere support@datacenterlight.ch für weitere Informationen."
#, python-format
msgid "Virtual Machine %(vm_name)s Cancelled"
@ -915,15 +882,6 @@ msgstr ""
"Es gab einen Fehler bei der Bearbeitung Deine Anfrage. Bitte versuche es "
"noch einmal."
#~ msgid "You are not permitted to do this operation"
#~ msgstr "Du hast keine Erlaubnis um diese Operation durchzuführen"
#~ msgid "The selected card does not exist"
#~ msgstr "Die ausgewählte Karte existiert nicht"
#~ msgid "You seem to have already added this card"
#~ msgstr "Es scheint, als hättest du diese Karte bereits hinzugefügt"
#, python-format
#~ msgid "This key exists already with the name \"%(name)s\""
#~ msgstr "Der SSH-Key mit dem Name \"%(name)s\" existiert bereits"

View file

@ -1,39 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2020-12-23 05:36
from __future__ import unicode_literals
from django.db import migrations, models
import utils.mixins
class Migration(migrations.Migration):
dependencies = [
('hosting', '0061_genericproduct_exclude_vat_calculations'),
]
operations = [
migrations.CreateModel(
name='IncompleteSubscriptions',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('completed_at', models.DateTimeField()),
('subscription_id', models.CharField(max_length=100)),
('subscription_status', models.CharField(max_length=30)),
('name', models.CharField(max_length=50)),
('email', models.EmailField(max_length=254)),
('request', models.TextField()),
('stripe_api_cus_id', models.CharField(max_length=30)),
('card_details_response', models.TextField()),
('stripe_subscription_obj', models.TextField()),
('stripe_onetime_charge', models.TextField()),
('gp_details', models.TextField()),
('specs', models.TextField()),
('vm_template_id', models.PositiveIntegerField(default=0)),
('template', models.TextField()),
('billing_address_data', models.TextField()),
],
bases=(utils.mixins.AssignPermissionsMixin, models.Model),
),
]

View file

@ -1,20 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2020-12-23 06:12
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hosting', '0062_incompletesubscriptions'),
]
operations = [
migrations.AlterField(
model_name='incompletesubscriptions',
name='completed_at',
field=models.DateTimeField(null=True),
),
]

View file

@ -1,33 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2020-12-31 10:13
from __future__ import unicode_literals
from django.db import migrations, models
import utils.mixins
class Migration(migrations.Migration):
dependencies = [
('hosting', '0063_auto_20201223_0612'),
]
operations = [
migrations.CreateModel(
name='IncompletePaymentIntents',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('completed_at', models.DateTimeField(null=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('payment_intent_id', models.CharField(max_length=100)),
('request', models.TextField()),
('stripe_api_cus_id', models.CharField(max_length=30)),
('card_details_response', models.TextField()),
('stripe_subscription_id', models.TextField()),
('stripe_charge_id', models.TextField()),
('gp_details', models.TextField()),
('billing_address_data', models.TextField()),
],
bases=(utils.mixins.AssignPermissionsMixin, models.Model),
),
]

View file

@ -1,25 +0,0 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2020-12-31 10:41
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hosting', '0064_incompletepaymentintents'),
]
operations = [
migrations.AlterField(
model_name='incompletepaymentintents',
name='stripe_charge_id',
field=models.CharField(max_length=100, null=True),
),
migrations.AlterField(
model_name='incompletepaymentintents',
name='stripe_subscription_id',
field=models.CharField(max_length=100, null=True),
),
]

View file

@ -1,3 +1,4 @@
import decimal
import json
import logging
import os
@ -169,10 +170,6 @@ class HostingOrder(AssignPermissionsMixin, models.Model):
def set_stripe_charge(self, stripe_charge):
self.stripe_charge_id = stripe_charge.id
if stripe_charge.source is None:
self.last4 = stripe_charge.payment_method_details.card.last4
self.cc_brand = stripe_charge.payment_method_details.card.brand
else:
self.last4 = stripe_charge.source.last4
self.cc_brand = stripe_charge.source.brand
self.save()
@ -676,10 +673,6 @@ class UserCardDetail(AssignPermissionsMixin, models.Model):
stripe_utils = StripeUtils()
cus_response = stripe_utils.get_customer(stripe_api_cus_id)
cu = cus_response['response_object']
if stripe_source_id.startswith("pm"):
# card is a payment method
cu.invoice_settings.default_payment_method = stripe_source_id
else:
cu.default_source = stripe_source_id
cu.save()
UserCardDetail.save_default_card_local(
@ -748,35 +741,3 @@ class StripeTaxRate(AssignPermissionsMixin, models.Model):
display_name = models.CharField(max_length=100)
percentage = models.FloatField(default=0)
description = models.CharField(max_length=100)
class IncompletePaymentIntents(AssignPermissionsMixin, models.Model):
completed_at = models.DateTimeField(null=True)
created_at = models.DateTimeField(auto_now_add=True)
payment_intent_id = models.CharField(max_length=100)
request = models.TextField()
stripe_api_cus_id = models.CharField(max_length=30)
card_details_response = models.TextField()
stripe_subscription_id = models.CharField(max_length=100, null=True)
stripe_charge_id = models.CharField(max_length=100, null=True)
gp_details = models.TextField()
billing_address_data = models.TextField()
class IncompleteSubscriptions(AssignPermissionsMixin, models.Model):
created_at = models.DateTimeField(auto_now_add=True)
completed_at = models.DateTimeField(null=True)
subscription_id = models.CharField(max_length=100)
subscription_status = models.CharField(max_length=30)
name = models.CharField(max_length=50)
email = models.EmailField()
request = models.TextField()
stripe_api_cus_id = models.CharField(max_length=30)
card_details_response = models.TextField()
stripe_subscription_obj = models.TextField()
stripe_onetime_charge = models.TextField()
gp_details = models.TextField()
specs = models.TextField()
vm_template_id = models.PositiveIntegerField(default=0)
template = models.TextField()
billing_address_data = models.TextField()

View file

@ -84,9 +84,6 @@ $(document).ready(function () {
var hasCreditcard = window.hasCreditcard || false;
if (!hasCreditcard && window.stripeKey) {
var stripe = Stripe(window.stripeKey);
if (window.pm_id) {
} else {
var element_style = {
fonts: [{
family: 'lato-light',
@ -150,7 +147,6 @@ $(document).ready(function () {
}
});
}
}
var submit_form_btn = $('#payment_button_with_creditcard');
submit_form_btn.on('click', submit_payment);
@ -167,7 +163,7 @@ $(document).ready(function () {
if (parts.length === 2) return parts.pop().split(";").shift();
}
function submitBillingForm(pmId) {
function submitBillingForm() {
var billing_form = $('#billing-form');
var recurring_input = $('#id_generic_payment_form-recurring');
billing_form.append('<input type="hidden" name="generic_payment_form-product_name" value="' + $('#id_generic_payment_form-product_name').val() + '" />');
@ -178,40 +174,11 @@ $(document).ready(function () {
billing_form.append('<input type="hidden" name="generic_payment_form-recurring" value="' + (recurring_input.prop('checked') ? 'on' : '') + '" />');
}
billing_form.append('<input type="hidden" name="generic_payment_form-description" value="' + $('#id_generic_payment_form-description').val() + '" />');
billing_form.append('<input type="hidden" name="id_payment_method" value="' + pmId + '" />');
billing_form.submit();
}
var $form_new = $('#payment-form-new');
$form_new.submit(payWithPaymentIntent);
window.result = "";
window.card = "";
function payWithPaymentIntent(e) {
e.preventDefault();
function stripePMHandler(paymentMethod) {
// Insert the token ID into the form so it gets submitted to the server
console.log(paymentMethod);
$('#id_payment_method').val(paymentMethod.id);
submitBillingForm(paymentMethod.id);
}
stripe.createPaymentMethod({
type: 'card',
card: cardNumberElement,
})
.then(function(result) {
// Handle result.error or result.paymentMethod
window.result = result;
if(result.error) {
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
console.log("created paymentMethod " + result.paymentMethod.id);
stripePMHandler(result.paymentMethod);
}
});
window.card = cardNumberElement;
}
$form_new.submit(payWithStripe_new);
function payWithStripe_new(e) {
e.preventDefault();
@ -230,7 +197,7 @@ $(document).ready(function () {
} else {
var process_text = "Processing";
if (typeof window.processing_text !== 'undefined') {
process_text = window.processing_text;
process_text = window.processing_text
}
$form_new.find('[type=submit]').html(process_text + ' <i class="fa fa-spinner fa-pulse"></i>');

View file

@ -92,14 +92,13 @@ $(document).ready(function() {
});
var create_vm_form = $('#virtual_machine_create_form');
if (window.isSubscription) {
create_vm_form.submit(function () {
$('#btn-create-vm').prop('disabled', true);
$.ajax({
url: create_vm_form.attr('action'),
type: 'POST',
data: create_vm_form.serialize(),
init: function () {
init: function(){
ok_btn = $('#createvm-modal-done-btn');
close_btn = $('#createvm-modal-close-btn');
ok_btn.addClass('btn btn-success btn-ok btn-wide hide');
@ -108,27 +107,6 @@ $(document).ready(function() {
success: function (data) {
fa_icon = $('.modal-icon > .fa');
modal_btn = $('#createvm-modal-done-btn');
if (data.showSCA) {
console.log("Show SCA");
var stripe = Stripe(data.STRIPE_PUBLISHABLE_KEY);
stripe.confirmCardPayment(data.payment_intent_secret).then(function (result) {
if (result.error) {
// Display error.message in your UI.
modal_btn.attr('href', data.error.redirect).removeClass('hide');
fa_icon.attr('class', 'fa fa-close');
modal_btn.attr('class', '').addClass('btn btn-danger btn-ok btn-wide');
$('#createvm-modal-title').text(data.error.msg_title);
$('#createvm-modal-body').html(data.error.msg_body);
} else {
// The payment has succeeded. Display a success message.
modal_btn.attr('href', data.success.redirect).removeClass('hide');
fa_icon.attr('class', 'checkmark');
$('#createvm-modal-title').text(data.success.msg_title);
$('#createvm-modal-body').html(data.success.msg_body);
}
});
$('#3Dsecure-modal').show();
} else {
$('#createvm-modal-title').text(data.msg_title);
$('#createvm-modal-body').html(data.msg_body);
if (data.redirect) {
@ -142,12 +120,11 @@ $(document).ready(function() {
fa_icon.attr('class', 'fa fa-close');
modal_btn.attr('class', '').addClass('btn btn-danger btn-ok btn-wide');
}
}
},
error: function (xmlhttprequest, textstatus, message) {
fa_icon = $('.modal-icon > .fa');
fa_icon.attr('class', 'fa fa-close');
if (typeof (create_vm_error_message) !== 'undefined') {
if (typeof(create_vm_error_message) !== 'undefined') {
$('#createvm-modal-body').text(create_vm_error_message);
}
$('#btn-create-vm').prop('disabled', false);
@ -156,38 +133,6 @@ $(document).ready(function() {
});
return false;
});
} else {
create_vm_form.submit(placeOrderPaymentIntent);
function placeOrderPaymentIntent(e) {
e.preventDefault();
var stripe = Stripe(window.stripeKey);
stripe.confirmCardPayment(
window.paymentIntentSecret,
{
payment_method: window.pm_id
}
).then(function(result) {
window.result = result;
fa_icon = $('.modal-icon > .fa');
modal_btn = $('#createvm-modal-done-btn');
if (result.error) {
// Display error.message in your UI.
modal_btn.attr('href', error_url).removeClass('hide');
fa_icon.attr('class', 'fa fa-close');
modal_btn.attr('class', '').addClass('btn btn-danger btn-ok btn-wide');
$('#createvm-modal-title').text(error_title);
$('#createvm-modal-body').html(result.error.message + " " + error_msg);
} else {
// The payment has succeeded
// Display a success message
modal_btn.attr('href', success_url).removeClass('hide');
fa_icon.attr('class', 'checkmark');
$('#createvm-modal-title').text(success_title);
$('#createvm-modal-body').html(success_msg);
}
});
}
}
$('#createvm-modal').on('hidden.bs.modal', function () {
$(this).find('.modal-footer .btn').addClass('hide');
});

View file

@ -218,7 +218,7 @@
{% csrf_token %}
<div class="row">
<div class="col-sm-8">
<div class="dcl-place-order-text">{% blocktrans with vm_price=vm.total_price|floatformat:2|intcomma %}By clicking "Place order" you agree to our <a href="https://datacenterlight.ch/en-us/cms/terms-of-service/">Terms of Service</a> and this plan will charge your credit card account with {{ vm_price }} CHF/month.{% endblocktrans %}.</div>
<div class="dcl-place-order-text">{% blocktrans with vm_price=vm.total_price|floatformat:2|intcomma %}By clicking "Place order" this plan will charge your credit card account with {{ vm_price }} CHF/month{% endblocktrans %}.</div>
</div>
<div class="col-sm-4 order-confirm-btn text-right">
<button class="btn choice-btn" id="btn-create-vm" data-href="{% url 'hosting:order-confirmation' %}" data-toggle="modal" data-target="#createvm-modal">

View file

@ -51,7 +51,7 @@ urlpatterns = [
name='choice_ssh_keys'),
url(r'delete_ssh_key/(?P<pk>\d+)/?$', SSHKeyDeleteView.as_view(),
name='delete_ssh_key'),
url(r'delete_card/(?P<pk>[\w\-]+)/$', SettingsView.as_view(),
url(r'delete_card/(?P<pk>\d+)/?$', SettingsView.as_view(),
name='delete_card'),
url(r'create_ssh_key/?$', SSHKeyCreateView.as_view(),
name='create_ssh_key'),

View file

@ -1,7 +1,6 @@
import logging
import uuid
from datetime import datetime
from urllib.parse import quote
from time import sleep
import stripe
@ -565,11 +564,9 @@ class SettingsView(LoginRequiredMixin, FormView):
stripe_customer = None
if hasattr(user, 'stripecustomer'):
stripe_customer = user.stripecustomer
stripe_utils = StripeUtils()
cards_list_request = stripe_utils.get_available_payment_methods(
stripe_customer
cards_list = UserCardDetail.get_all_cards_list(
stripe_customer=stripe_customer
)
cards_list = cards_list_request.get('response_object')
context.update({
'cards_list': cards_list,
'stripe_key': settings.STRIPE_API_PUBLIC_KEY
@ -580,38 +577,48 @@ class SettingsView(LoginRequiredMixin, FormView):
def post(self, request, *args, **kwargs):
if 'card' in request.POST and request.POST['card'] is not '':
card_id = escape(request.POST['card'])
user_card_detail = UserCardDetail.objects.get(id=card_id)
UserCardDetail.set_default_card(
stripe_api_cus_id=request.user.stripecustomer.stripe_id,
stripe_source_id=card_id
stripe_source_id=user_card_detail.card_id
)
stripe_utils = StripeUtils()
card_details = stripe_utils.get_cards_details_from_payment_method(
card_id
)
if not card_details.get('response_object'):
logger.debug("Could not find card %s in stripe" % card_id)
messages.add_message(request, messages.ERROR,
_("Could not set a default card."))
return HttpResponseRedirect(reverse_lazy('hosting:settings'))
card_details_response = card_details['response_object']
msg = _(
("Your {brand} card ending in {last4} set as "
"default card").format(
brand=card_details_response['brand'],
last4=card_details_response['last4']
brand=user_card_detail.brand,
last4=user_card_detail.last4
)
)
messages.add_message(request, messages.SUCCESS, msg)
return HttpResponseRedirect(reverse_lazy('hosting:settings'))
if 'delete_card' in request.POST:
card = self.kwargs.get('pk')
try:
card = UserCardDetail.objects.get(pk=self.kwargs.get('pk'))
if (request.user.has_perm(self.permission_required[0], card)
and
request.user
.stripecustomer
.usercarddetail_set
.count() > 1):
if card.card_id is not None:
stripe_utils = StripeUtils()
stripe_utils.dissociate_customer_card(
request.user.stripecustomer.stripe_id,
card
card.card_id
)
if card.preferred:
UserCardDetail.set_default_card_from_stripe(
request.user.stripecustomer.stripe_id
)
card.delete()
msg = _("Card deassociation successful")
messages.add_message(request, messages.SUCCESS, msg)
else:
msg = _("You are not permitted to do this operation")
messages.add_message(request, messages.ERROR, msg)
except UserCardDetail.DoesNotExist:
msg = _("The selected card does not exist")
messages.add_message(request, messages.ERROR, msg)
return HttpResponseRedirect(reverse_lazy('hosting:settings'))
form = self.get_form()
if form.is_valid():
@ -686,22 +693,24 @@ class SettingsView(LoginRequiredMixin, FormView):
msg = _("Billing address updated successfully")
messages.add_message(request, messages.SUCCESS, msg)
else:
id_payment_method = request.POST.get('id_payment_method', None)
token = form.cleaned_data.get('token')
stripe_utils = StripeUtils()
card_details = stripe_utils.get_cards_details_from_payment_method(
id_payment_method
card_details = stripe_utils.get_cards_details_from_token(
token
)
if not card_details.get('response_object'):
form.add_error("__all__", card_details.get('error'))
return self.render_to_response(self.get_context_data())
stripe_customer = StripeCustomer.get_or_create(
email=request.user.email, id_payment_method=id_payment_method
email=request.user.email, token=token
)
card = card_details['response_object']
if UserCardDetail.get_user_card_details(stripe_customer, card):
msg = _('You seem to have already added this card')
messages.add_message(request, messages.ERROR, msg)
else:
acc_result = stripe_utils.associate_customer_card(
request.user.stripecustomer.stripe_id,
id_payment_method,
set_as_default=True
request.user.stripecustomer.stripe_id, token
)
if acc_result['response_object'] is None:
msg = _(
@ -1069,13 +1078,7 @@ class OrdersHostingDetailView(LoginRequiredMixin, DetailView, FormView):
billing_address_data = request.session.get('billing_address_data')
vm_template_id = template.get('id', 1)
stripe_api_cus_id = request.user.stripecustomer.stripe_id
logger.debug("template=%s specs=%s stripe_customer_id=%s "
"billing_address_data=%s vm_template_id=%s "
"stripe_api_cus_id=%s" % (
template, specs, stripe_customer_id, billing_address_data,
vm_template_id, stripe_api_cus_id)
)
if 'id_payment_method' in self.request.session:
if 'token' in self.request.session:
card_details = stripe_utils.get_cards_details_from_token(
request.session['token']
)
@ -1092,7 +1095,7 @@ class OrdersHostingDetailView(LoginRequiredMixin, DetailView, FormView):
)
if not ucd:
acc_result = stripe_utils.associate_customer_card(
stripe_api_cus_id, request.session['id_payment_method'],
stripe_api_cus_id, request.session['token'],
set_as_default=True
)
if acc_result['response_object'] is None:
@ -1190,24 +1193,8 @@ class OrdersHostingDetailView(LoginRequiredMixin, DetailView, FormView):
discount['stripe_coupon_id']
else ""),
tax_rates=[stripe_tax_rate.tax_rate_id] if stripe_tax_rate else [],
default_payment_method=request.session['id_payment_method']
)
stripe_subscription_obj = subscription_result.get('response_object')
latest_invoice = stripe.Invoice.retrieve(stripe_subscription_obj.latest_invoice)
ret = stripe.PaymentIntent.confirm(
latest_invoice.payment_intent
)
if ret.status == 'requires_source_action' or ret.status == 'requires_action':
pi = stripe.PaymentIntent.retrieve(
latest_invoice.payment_intent
)
context = {
'sid': stripe_subscription_obj.id,
'payment_intent_secret': pi.client_secret,
'STRIPE_PUBLISHABLE_KEY': settings.STRIPE_API_PUBLIC_KEY,
'showSCA': True
}
return JsonResponse(context)
# Check if the subscription was approved and is active
if (stripe_subscription_obj is None or
stripe_subscription_obj.status != 'active'):
@ -1305,7 +1292,7 @@ class InvoiceListView(LoginRequiredMixin, TemplateView):
if ('user_email' in self.request.GET
and self.request.user.email == settings.ADMIN_EMAIL):
user_email = self.request.GET['user_email']
context['user_email'] = '%s' % quote(user_email)
context['user_email'] = user_email
logger.debug(
"user_email = {}".format(user_email)
)
@ -1315,8 +1302,7 @@ class InvoiceListView(LoginRequiredMixin, TemplateView):
logger.debug("User does not exist")
cu = self.request.user
invs = stripe.Invoice.list(customer=cu.stripecustomer.stripe_id,
count=100,
status='paid')
count=100)
paginator = Paginator(invs.data, 10)
try:
invs_page = paginator.page(page)
@ -1911,7 +1897,7 @@ class VirtualMachineView(LoginRequiredMixin, View):
'subject': ("Deleted " if response['status']
else "ERROR deleting ") + admin_msg_sub,
'from_email': settings.DCL_SUPPORT_FROM_ADDRESS,
'to': ['dcl-orders@ungleich.ch'],
'to': ['info@ungleich.ch'],
'body': "\n".join(
["%s=%s" % (k, v) for (k, v) in admin_email_body.items()]),
}

View file

@ -277,7 +277,7 @@ class StripeCustomer(models.Model):
return "%s - %s" % (self.stripe_id, self.user.email)
@classmethod
def create_stripe_api_customer(cls, email=None, id_payment_method=None,
def create_stripe_api_customer(cls, email=None, token=None,
customer_name=None):
"""
This method creates a Stripe API customer with the given
@ -288,8 +288,7 @@ class StripeCustomer(models.Model):
stripe user.
"""
stripe_utils = StripeUtils()
stripe_data = stripe_utils.create_customer(
id_payment_method, email, customer_name)
stripe_data = stripe_utils.create_customer(token, email, customer_name)
if stripe_data.get('response_object'):
stripe_cus_id = stripe_data.get('response_object').get('id')
return stripe_cus_id
@ -297,7 +296,7 @@ class StripeCustomer(models.Model):
return None
@classmethod
def get_or_create(cls, email=None, token=None, id_payment_method=None):
def get_or_create(cls, email=None, token=None):
"""
Check if there is a registered stripe customer with that email
or create a new one

View file

@ -154,8 +154,6 @@ class OpenNebulaManager():
protocol=settings.OPENNEBULA_PROTOCOL)
)
raise ConnectionRefusedError
except Exception as ex:
logger.error(str(ex))
def _get_user_pool(self):
try:

View file

@ -1,21 +0,0 @@
#!/bin/sh
# Nico Schottelius, 2021-12-17
current=$(git describe --dirty)
last_tag=$(git describe --tags --abbrev=0)
registry=harbor.ungleich.svc.p10.k8s.ooo/ungleich-public
image_url=$registry/dynamicweb:${current}
if echo $current | grep -q -e 'dirty$'; then
echo Refusing to release a dirty tree build
exit 1
fi
if [ "$current" != "$last_tag" ]; then
echo "Last tag ($last_tag) is not current version ($current)"
echo "Only release proper versions"
exit 1
fi
docker tag dynamicweb:${current} ${image_url}
docker push ${image_url}

View file

@ -25,7 +25,7 @@ django-compressor==2.0
django-debug-toolbar==1.4
python-dotenv==0.10.3
django-extensions==1.6.7
django-filer==2.1.2
django-filer==1.2.0
django-filter==0.13.0
django-formtools==1.0
django-guardian==1.4.4
@ -83,7 +83,7 @@ stripe==2.41.0
wheel==0.29.0
django-admin-honeypot==1.0.0
coverage==4.3.4
git+https://github.com/ungleich/python-oca.git#egg=oca
git+https://github.com/ungleich/python-oca.git#egg=python-oca
djangorestframework==3.6.3
flake8==3.3.0
python-memcached==1.58

View file

@ -134,6 +134,8 @@
digitalglarus.ch<br/>
hack4lgarus.ch<br/>
ipv6onlyhosting.com<br/>
ipv6onlyhosting.ch<br/>
ipv6onlyhosting.net<br/>
django-hosting.ch<br/>
rails-hosting.ch<br/>
node-hosting.ch<br/>

View file

@ -3,7 +3,6 @@ import hashlib
import random
import ldap3
import logging
import unicodedata
from django.conf import settings
@ -102,7 +101,7 @@ class LdapManager:
"uidNumber": [str(uidNumber)],
"gidNumber": [str(settings.LDAP_CUSTOMER_GROUP_ID)],
"loginShell": ["/bin/bash"],
"homeDirectory": ["/home/{}".format(unicodedata.normalize('NFKD', user).encode('ascii','ignore'))],
"homeDirectory": ["/home/{}".format(user).encode("utf-8")],
"mail": email.encode("utf-8"),
"userPassword": [self._ssha_password(
password.encode("utf-8")

View file

@ -34,7 +34,6 @@ def handleStripeError(f):
logger.error(str(e))
return response
except stripe.error.RateLimitError as e:
logger.error(str(e))
response.update(
{'error': "Too many requests made to the API too quickly"})
return response
@ -70,7 +69,7 @@ class StripeUtils(object):
CURRENCY = 'chf'
INTERVAL = 'month'
SUCCEEDED_STATUS = 'succeeded'
RESOURCE_ALREADY_EXISTS_ERROR_CODE = 'resource_already_exists'
STRIPE_PLAN_ALREADY_EXISTS = 'Plan already exists'
STRIPE_NO_SUCH_PLAN = 'No such plan'
PLAN_EXISTS_ERROR_MSG = 'Plan {} exists already.\nCreating a local StripePlan now.'
PLAN_DOES_NOT_EXIST_ERROR_MSG = 'Plan {} does not exist.'
@ -83,29 +82,18 @@ class StripeUtils(object):
customer.save()
@handleStripeError
def associate_customer_card(self, stripe_customer_id, id_payment_method,
def associate_customer_card(self, stripe_customer_id, token,
set_as_default=False):
customer = stripe.Customer.retrieve(stripe_customer_id)
stripe.PaymentMethod.attach(
id_payment_method,
customer=stripe_customer_id,
)
card = customer.sources.create(source=token)
if set_as_default:
customer.invoice_settings.default_payment_method = id_payment_method
customer.default_source = card.id
customer.save()
return True
@handleStripeError
def dissociate_customer_card(self, stripe_customer_id, card_id):
customer = stripe.Customer.retrieve(stripe_customer_id)
if card_id.startswith("pm"):
logger.debug("PaymentMethod %s detached %s" % (card_id,
stripe_customer_id))
pm = stripe.PaymentMethod.retrieve(card_id)
stripe.PaymentMethod.detach(card_id)
pm.delete()
else:
logger.debug("card %s detached %s" % (card_id, stripe_customer_id))
card = customer.sources.retrieve(card_id)
card.delete()
@ -199,24 +187,6 @@ class StripeUtils(object):
}
return card_details
@handleStripeError
def get_cards_details_from_payment_method(self, payment_method_id):
payment_method = stripe.PaymentMethod.retrieve(payment_method_id)
# payment_method does not always seem to have a card with id
# if that is the case, fallback to payment_method_id for card_id
card_id = payment_method_id
if hasattr(payment_method.card, 'id'):
card_id = payment_method.card.id
card_details = {
'last4': payment_method.card.last4,
'brand': payment_method.card.brand,
'exp_month': payment_method.card.exp_month,
'exp_year': payment_method.card.exp_year,
'fingerprint': payment_method.card.fingerprint,
'card_id': card_id
}
return card_details
def check_customer(self, stripe_cus_api_id, user, token):
try:
customer = stripe.Customer.retrieve(stripe_cus_api_id)
@ -236,11 +206,11 @@ class StripeUtils(object):
return customer
@handleStripeError
def create_customer(self, id_payment_method, email, name=None):
def create_customer(self, token, email, name=None):
if name is None or name.strip() == "":
name = email
customer = self.stripe.Customer.create(
payment_method=id_payment_method,
source=token,
description=name,
email=email
)
@ -297,17 +267,11 @@ class StripeUtils(object):
stripe_plan_db_obj = StripePlan.objects.create(
stripe_plan_id=stripe_plan_id)
except stripe.error.InvalidRequestError as e:
logger.error(str(e))
logger.error("error_code = %s" % str(e.__dict__))
if self.RESOURCE_ALREADY_EXISTS_ERROR_CODE in e.error.code:
if self.STRIPE_PLAN_ALREADY_EXISTS in str(e):
logger.debug(
self.PLAN_EXISTS_ERROR_MSG.format(stripe_plan_id))
stripe_plan_db_obj, c = StripePlan.objects.get_or_create(
stripe_plan_db_obj = StripePlan.objects.create(
stripe_plan_id=stripe_plan_id)
if c:
logger.debug("Created stripe plan %s" % stripe_plan_id)
else:
logger.debug("Plan %s exists already" % stripe_plan_id)
return stripe_plan_db_obj
@handleStripeError
@ -336,14 +300,10 @@ class StripeUtils(object):
@handleStripeError
def subscribe_customer_to_plan(self, customer, plans, trial_end=None,
coupon="", tax_rates=list(),
default_payment_method=""):
coupon="", tax_rates=list()):
"""
Subscribes the given customer to the list of given plans
:param default_payment_method:
:param tax_rates:
:param coupon:
:param customer: The stripe customer identifier
:param plans: A list of stripe plans.
:param trial_end: An integer representing when the Stripe subscription
@ -357,17 +317,12 @@ class StripeUtils(object):
]
:return: The subscription StripeObject
"""
logger.debug("Subscribing %s to plan %s : coupon = %s" % (
customer, str(plans), str(coupon)
))
subscription_result = self.stripe.Subscription.create(
customer=customer, items=plans, trial_end=trial_end,
coupon=coupon,
default_tax_rates=tax_rates,
payment_behavior='allow_incomplete',
default_payment_method=default_payment_method
)
logger.debug("Done subscribing")
return subscription_result
@handleStripeError
@ -525,48 +480,6 @@ class StripeUtils(object):
)
return tax_id_obj
@handleStripeError
def get_payment_intent(self, amount, customer):
""" Create a stripe PaymentIntent of the given amount and return it
:param amount: the amount of payment_intent
:return:
"""
payment_intent_obj = stripe.PaymentIntent.create(
amount=amount,
currency='chf',
customer=customer,
setup_future_usage='off_session'
)
return payment_intent_obj
@handleStripeError
def get_available_payment_methods(self, customer):
""" Retrieves all payment methods of the given customer
:param customer: StripeCustomer object
:return: a list of available payment methods
"""
return_list = []
if customer is None:
return return_list
cu = stripe.Customer.retrieve(customer.stripe_id)
pms = stripe.PaymentMethod.list(
customer=customer.stripe_id,
type="card",
)
default_source = None
if cu.default_source:
default_source = cu.default_source
else:
default_source = cu.invoice_settings.default_payment_method
for pm in pms.data:
return_list.append({
'last4': pm.card.last4, 'brand': pm.card.brand, 'id': pm.id,
'exp_year': pm.card.exp_year,
'exp_month': '{:02d}'.format(pm.card.exp_month),
'preferred': pm.id == default_source
})
return return_list
def compare_vat_numbers(self, vat1, vat2):
_vat1 = vat1.replace(" ", "").replace(".", "").replace("-","")
_vat2 = vat2.replace(" ", "").replace(".", "").replace("-","")

View file

@ -1,17 +1,14 @@
import datetime
import logging
import json
import stripe
import stripe
# Create your views here.
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from datacenterlight.views import do_provisioning, do_provisioning_generic
from membership.models import StripeCustomer
from hosting.models import IncompleteSubscriptions, IncompletePaymentIntents
from utils.models import BillingAddress, UserBillingAddress
from utils.tasks import send_plain_email_task
@ -114,192 +111,7 @@ def handle_webhook(request):
'to': settings.DCL_ERROR_EMAILS_TO_LIST,
'body': "Response = %s" % str(tax_id_obj),
}
send_plain_email_task.delay(email_data)
elif event.type == 'invoice.paid':
#More info: https://stripe.com/docs/billing/migration/strong-customer-authentication#scenario-1-handling-fulfillment
invoice_obj = event.data.object
logger.debug("Webhook Event: invoice.paid")
logger.debug("invoice_obj %s " % str(invoice_obj))
logger.debug("invoice_obj.paid = %s %s" % (invoice_obj.paid, type(invoice_obj.paid)))
logger.debug("invoice_obj.billing_reason = %s %s" % (invoice_obj.billing_reason, type(invoice_obj.billing_reason)))
# We should check for billing_reason == "subscription_create" but we
# check for "subscription_update"
# because we are using older api.
# See https://stripe.com/docs/upgrades?since=2015-07-13
# The billing_reason attribute of the invoice object now can take the
# value of subscription_create, indicating that it is the first
# invoice of a subscription. For older API versions,
# billing_reason=subscription_create is represented as
# subscription_update.
if (invoice_obj.paid and
invoice_obj.billing_reason == "subscription_update"):
logger.debug("""invoice_obj.paid and
invoice_obj.billing_reason == subscription_update""")
logger.debug("Start provisioning")
try:
logger.debug("Looking for subscription %s" %
invoice_obj.subscription)
stripe_subscription_obj = stripe.Subscription.retrieve(
invoice_obj.subscription)
try:
incomplete_sub = IncompleteSubscriptions.objects.get(
subscription_id=invoice_obj.subscription)
request = ""
soc = ""
card_details_response = ""
gp_details = ""
template = ""
specs = ""
billing_address_data = ""
if incomplete_sub.request:
request = json.loads(incomplete_sub.request)
if incomplete_sub.specs:
specs = json.loads(incomplete_sub.specs)
if incomplete_sub.stripe_onetime_charge:
soc = json.loads(incomplete_sub.stripe_onetime_charge)
if incomplete_sub.gp_details:
gp_details = json.loads(incomplete_sub.gp_details)
if incomplete_sub.card_details_response:
card_details_response = json.loads(
incomplete_sub.card_details_response)
if incomplete_sub.template:
template = json.loads(
incomplete_sub.template)
if incomplete_sub.billing_address_data:
billing_address_data = json.loads(
incomplete_sub.billing_address_data)
logger.debug("*******")
logger.debug(str(incomplete_sub))
logger.debug("*******")
logger.debug("1*******")
logger.debug(request)
logger.debug("2*******")
logger.debug(card_details_response)
logger.debug("3*******")
logger.debug(soc)
logger.debug("4*******")
logger.debug(gp_details)
logger.debug("5*******")
logger.debug(template)
logger.debug("6*******")
do_provisioning(
request=request,
stripe_api_cus_id=incomplete_sub.stripe_api_cus_id,
card_details_response=card_details_response,
stripe_subscription_obj=stripe_subscription_obj,
stripe_onetime_charge=soc,
gp_details=gp_details,
specs=specs,
vm_template_id=incomplete_sub.vm_template_id,
template=template,
billing_address_data=billing_address_data,
real_request=None
)
except IncompleteSubscriptions.DoesNotExist as ex:
logger.error(str(ex))
except IncompleteSubscriptions.MultipleObjectsReturned as ex:
logger.error(str(ex))
email_data = {
'subject': "IncompleteSubscriptions error",
'from_email': settings.DCL_SUPPORT_FROM_ADDRESS,
'to': settings.DCL_ERROR_EMAILS_TO_LIST,
'body': "Response = %s" % str(ex),
}
send_plain_email_task.delay(email_data)
except Exception as ex:
logger.error(str(ex))
email_data = {
'subject': "invoice.paid Webhook error",
'from_email': settings.DCL_SUPPORT_FROM_ADDRESS,
'to': settings.DCL_ERROR_EMAILS_TO_LIST,
'body': "Response = %s" % str(ex),
}
send_plain_email_task.delay(email_data)
elif event.type == 'invoice.payment_failed':
invoice_obj = event.data.object
logger.debug("Webhook Event: invoice.payment_failed")
logger.debug("invoice_obj %s " % str(invoice_obj))
if (invoice_obj.payment_failed and
invoice_obj.billing_reason == "subscription_update"):
logger.debug("Payment failed, inform the users")
elif event.type == 'payment_intent.succeeded':
payment_intent_obj = event.data.object
logger.debug("Webhook Event: payment_intent.succeeded")
logger.debug("payment_intent_obj %s " % str(payment_intent_obj))
try:
logger.debug("Looking for IncompletePaymentIntents %s " %
payment_intent_obj.id)
incomplete_pm = IncompletePaymentIntents.objects.get(
payment_intent_id=payment_intent_obj.id)
logger.debug("incomplete_pm = %s" % str(incomplete_pm.__dict__))
request = ""
soc = ""
card_details_response = ""
gp_details = ""
template = ""
billing_address_data = ""
if incomplete_pm.request:
request = json.loads(incomplete_pm.request)
logger.debug("request = %s" % str(request))
if incomplete_pm.stripe_charge_id:
soc = incomplete_pm.stripe_charge_id
logger.debug("stripe_onetime_charge = %s" % str(soc))
if incomplete_pm.gp_details:
gp_details = json.loads(incomplete_pm.gp_details)
logger.debug("gp_details = %s" % str(gp_details))
if incomplete_pm.card_details_response:
card_details_response = json.loads(
incomplete_pm.card_details_response)
logger.debug("card_details_response = %s" % str(card_details_response))
if incomplete_pm.billing_address_data:
billing_address_data = json.loads(
incomplete_pm.billing_address_data)
logger.debug("billing_address_data = %s" % str(billing_address_data))
logger.debug("1*******")
logger.debug(request)
logger.debug("2*******")
logger.debug(card_details_response)
logger.debug("3*******")
logger.debug(soc)
logger.debug("4*******")
logger.debug(gp_details)
logger.debug("5*******")
logger.debug(template)
logger.debug("6*******")
logger.debug(billing_address_data)
incomplete_pm.completed_at = datetime.datetime.now()
charges = ""
if len(payment_intent_obj.charges.data) > 0:
for d in payment_intent_obj.charges.data:
if charges == "":
charges = "%s" % d.id
else:
charges = "%s,%s" % (charges, d.id)
logger.debug("Charge ids = %s" % charges)
incomplete_pm.stripe_charge_id=charges
do_provisioning_generic(
request=request,
stripe_api_cus_id=incomplete_pm.stripe_api_cus_id,
card_details_response=card_details_response,
stripe_subscription_id=None,
stripe_charge_id=charges,
gp_details=gp_details,
billing_address_data=billing_address_data
)
incomplete_pm.save()
except IncompletePaymentIntents.DoesNotExist as ex:
logger.error(str(ex))
except (IncompletePaymentIntents.MultipleObjectsReturned,
Exception) as ex:
logger.error(str(ex))
email_data = {
'subject': "IncompletePaymentIntents error",
'from_email': settings.DCL_SUPPORT_FROM_ADDRESS,
'to': settings.DCL_ERROR_EMAILS_TO_LIST,
'body': "Response = %s" % str(ex),
}
send_plain_email_task.delay(email_data)
else:
logger.error("Unhandled event : " + event.type)