dynamicweb/hosting/forms.py

223 lines
8 KiB
Python
Raw Normal View History

import datetime
2017-08-31 07:23:00 +00:00
import logging
import subprocess
2017-08-31 19:28:30 +00:00
2017-09-13 12:31:13 +00:00
import tempfile
from django import forms
from django.conf import settings
from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
2017-08-31 07:23:00 +00:00
from membership.models import CustomUser
from utils.hosting_utils import get_all_public_keys
2018-09-25 00:18:31 +00:00
from .models import UserHostingKey, GenericProduct
2017-08-31 07:23:00 +00:00
logger = logging.getLogger(__name__)
def generate_ssh_key_name():
return '{prefix}{date_time_str}'.format(
prefix=settings.DCL_SSH_KEY_NAME_PREFIX,
date_time_str=datetime.datetime.now().strftime('%m%d%y%H%M%S')
)
class HostingUserLoginForm(forms.Form):
email = forms.CharField(widget=forms.EmailInput())
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
fields = ['email', 'password']
def clean(self):
email = self.cleaned_data.get('email')
password = self.cleaned_data.get('password')
if self.errors:
return self.cleaned_data
is_auth = authenticate(email=email, password=password)
if not is_auth:
2017-07-29 12:49:10 +00:00
raise forms.ValidationError(
2017-08-03 16:30:41 +00:00
_("Your username and/or password were incorrect."))
elif is_auth.validated == 0:
2017-07-29 12:49:10 +00:00
raise forms.ValidationError(
_("Your account is not activated yet."))
return self.cleaned_data
def clean_email(self):
email = self.cleaned_data.get('email')
try:
CustomUser.objects.get(email=email)
return email
except CustomUser.DoesNotExist:
2017-08-31 07:23:00 +00:00
raise forms.ValidationError(_("User does not exist"))
class ProductModelChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
return obj.product_name
2018-09-22 06:16:26 +00:00
class GenericPaymentForm(forms.Form):
product_name = ProductModelChoiceField(
2018-09-25 00:18:31 +00:00
queryset=GenericProduct.objects.all().order_by('product_name'),
empty_label=_("Choose a product"),
)
amount = forms.FloatField(
2018-10-03 06:27:22 +00:00
widget=forms.TextInput(
attrs={'placeholder': _('Amount in CHF'),
'readonly': 'readonly', }
2018-10-03 06:27:22 +00:00
),
max_value=999999,
min_value=1,
label=_('Amount in CHF')
2018-10-03 06:27:22 +00:00
)
recurring = forms.BooleanField(required=False,
2018-10-03 06:27:22 +00:00
label=_("Recurring monthly"), )
description = forms.CharField(
widget=forms.Textarea(attrs={'style': "height: 60px;"}),
required=False
)
2018-09-22 06:16:26 +00:00
class Meta:
model = GenericProduct
2018-09-25 00:18:31 +00:00
fields = ['product_name', 'amount', 'recurring', 'description']
2018-09-22 06:16:26 +00:00
def clean_amount(self):
amount = self.cleaned_data.get('amount')
if (float(self.cleaned_data.get('product_name').get_actual_price()) !=
amount):
raise forms.ValidationError(_("Amount field does not match"))
return amount
def clean_recurring(self):
recurring = self.cleaned_data.get('recurring')
if (self.cleaned_data.get('product_name').product_is_subscription !=
(True if recurring else False)):
raise forms.ValidationError(_("Recurring field does not match"))
return recurring
2018-09-22 06:16:26 +00:00
class ProductPaymentForm(GenericPaymentForm):
def __init__(self, *args, **kwargs):
2018-10-03 07:38:49 +00:00
product_id = kwargs.pop('product_id', None)
if product_id is not None:
self.product = GenericProduct.objects.get(id=product_id)
super(ProductPaymentForm, self).__init__(*args, **kwargs)
self.fields['product_name'] = forms.CharField(
widget=forms.TextInput(
attrs={'placeholder': _('Product name'),
'readonly': 'readonly' }
)
)
2018-10-03 07:38:49 +00:00
def clean_amount(self):
amount = self.cleaned_data.get('amount')
if (self.product is None or
float(self.product.get_actual_price()) != amount):
raise forms.ValidationError(_("Amount field does not match"))
return amount
def clean_recurring(self):
recurring = self.cleaned_data.get('recurring')
if (self.product.product_is_subscription !=
(True if recurring else False)):
raise forms.ValidationError(_("Recurring field does not match"))
return recurring
class HostingUserSignupForm(forms.ModelForm):
2017-10-25 21:54:29 +00:00
confirm_password = forms.CharField(label=_("Confirm Password"),
widget=forms.PasswordInput())
password = forms.CharField(label=_("Password"),
widget=forms.PasswordInput())
class Meta:
model = CustomUser
fields = ['name', 'email', 'password']
widgets = {
2017-08-31 07:23:00 +00:00
'name': forms.TextInput(
2017-10-25 21:54:29 +00:00
attrs={'placeholder': _('Enter your name or company name')}),
}
def clean_confirm_password(self):
password = self.cleaned_data.get('password')
confirm_password = self.cleaned_data.get('confirm_password')
if not confirm_password == password:
raise forms.ValidationError("Passwords don't match")
return confirm_password
class UserHostingKeyForm(forms.ModelForm):
private_key = forms.CharField(widget=forms.HiddenInput(), required=False)
public_key = forms.CharField(widget=forms.Textarea(
2017-08-31 07:23:00 +00:00
attrs={'class': 'form_public_key',
'placeholder': _('Paste here your public key')}),
required=False,
)
user = forms.models.ModelChoiceField(queryset=CustomUser.objects.all(),
2017-08-31 07:23:00 +00:00
required=False,
widget=forms.HiddenInput())
name = forms.CharField(required=False, widget=forms.TextInput(
2017-08-31 07:23:00 +00:00
attrs={'class': 'form_key_name',
'placeholder': _('Give a name to your key')}))
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
super(UserHostingKeyForm, self).__init__(*args, **kwargs)
2017-07-31 14:13:15 +00:00
self.fields['name'].label = _('Key name')
2017-08-31 07:23:00 +00:00
def clean_public_key(self):
"""
2017-09-13 12:31:13 +00:00
Validates a public ssh key using `ssh-keygen -lf key.pub`
Also checks if a given key already exists in the database and
alerts the user of it.
2017-08-31 07:23:00 +00:00
:return:
"""
if 'generate' in self.request.POST:
return self.data.get('public_key')
2017-08-31 07:23:00 +00:00
KEY_ERROR_MESSAGE = _("Please input a proper SSH key")
2017-09-13 00:57:46 +00:00
openssh_pubkey_str = self.data.get('public_key').strip()
if openssh_pubkey_str in get_all_public_keys(self.request.user):
key_name = UserHostingKey.objects.filter(
user_id=self.request.user.id,
public_key=openssh_pubkey_str).first().name
KEY_EXISTS_MESSAGE = _(
2017-09-13 19:20:24 +00:00
"This key exists already with the name \"%(name)s\"") % {
2018-10-03 06:27:22 +00:00
'name': key_name}
raise forms.ValidationError(KEY_EXISTS_MESSAGE)
with tempfile.NamedTemporaryFile(delete=True) as tmp_public_key_file:
2017-09-12 21:01:19 +00:00
tmp_public_key_file.write(openssh_pubkey_str.encode('utf-8'))
tmp_public_key_file.flush()
try:
subprocess.check_output(
['ssh-keygen', '-lf', tmp_public_key_file.name])
except subprocess.CalledProcessError as cpe:
logger.debug(
2017-09-12 21:03:21 +00:00
"Not a correct ssh format {error}".format(error=str(cpe)))
raise forms.ValidationError(KEY_ERROR_MESSAGE)
return openssh_pubkey_str
2017-08-31 07:23:00 +00:00
def clean_name(self):
return self.data.get('name')
def clean_user(self):
return self.request.user
def clean(self):
cleaned_data = self.cleaned_data
if 'generate' in self.request.POST:
self.cleaned_data['name'] = generate_ssh_key_name()
private_key, public_key = UserHostingKey.generate_keys()
cleaned_data.update({
'private_key': private_key,
'public_key': public_key
})
return cleaned_data
class Meta:
model = UserHostingKey
fields = ['user', 'name', 'public_key']