diff --git a/plinth/modules/first_boot/forms.py b/plinth/modules/first_boot/forms.py index 61101f232..7dc576e9e 100644 --- a/plinth/modules/first_boot/forms.py +++ b/plinth/modules/first_boot/forms.py @@ -27,7 +27,7 @@ from django import forms from django.contrib import auth from django.contrib import messages from django.core.exceptions import ValidationError -from django.utils.translation import ugettext as _ +from django.utils.translation import ugettext as _, ugettext_lazy from plinth import actions from plinth import cfg @@ -35,18 +35,19 @@ from plinth.errors import ActionError, DomainRegistrationError from plinth.modules.pagekite.utils import PREDEFINED_SERVICES, run from plinth.modules.users.forms import GROUP_CHOICES from plinth.utils import format_lazy -LOGGER = logging.getLogger(__name__) + +logger = logging.getLogger(__name__) class State1Form(auth.forms.UserCreationForm): """Firstboot state 1: create a new user.""" def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') - super(State1Form, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def save(self, commit=True): """Create and log the user in.""" - user = super(State1Form, self).save(commit=commit) + user = super().save(commit=commit) if commit: try: actions.superuser_run( @@ -91,27 +92,35 @@ class State1Form(auth.forms.UserCreationForm): class SubdomainWidget(forms.widgets.TextInput): """Append the domain to the subdomain bootstrap input field""" + def __init__(self, domain, *args, **kwargs): + """Intialize the widget by storing the domain value.""" + super().__init__(*args, **kwargs) + self.domain = domain + def render(self, *args, **kwargs): - inputfield = super(SubdomainWidget, self).render(*args, **kwargs) - domain = State5Form.DOMAIN_APPENDIX + """Return the HTML for the widget.""" + inputfield = super().render(*args, **kwargs) return """
{0} {1} -
""".format(inputfield, domain) + """.format(inputfield, self.domain) class State5Form(forms.Form): """Set up freedombox.me pagekite subdomain""" - DOMAIN_APPENDIX = ".freedombox.me" - # webservice url for domain validation and registration - service_url = "http://freedombox.me/cgi-bin/freedomkite.pl" - code_help_text = _("The voucher you received with your {box_name} Danube " - "Edition") - code = forms.CharField(help_text=format_lazy(code_help_text, - box_name=_(cfg.box_name))) - domain = forms.SlugField(label=_("Subdomain"), - widget=SubdomainWidget, - help_text=_("The subdomain you want to register")) + DOMAIN_APPENDIX = '.freedombox.me' + # Webservice url for domain validation and registration + service_url = 'http://freedombox.me/cgi-bin/freedomkite.pl' + + code_help_text = format_lazy( + ugettext_lazy('The voucher you received with your {box_name} Danube ' + 'Edition'), box_name=ugettext_lazy(cfg.box_name)) + + code = forms.CharField(help_text=code_help_text) + + domain = forms.SlugField(label=_('Subdomain'), + widget=SubdomainWidget(domain=DOMAIN_APPENDIX), + help_text=_('The subdomain you want to register')) def clean_domain(self): """Append the domain to the users' subdomain""" @@ -119,61 +128,66 @@ class State5Form(forms.Form): def clean(self): """Validate user input (subdomain and code)""" - cleaned_data = super(State5Form, self).clean() - # if the subdomain is wrong don't look if the domain is available + cleaned_data = super().clean() + + # If the subdomain is wrong, don't look if the domain is + # available if self.errors: return cleaned_data self.domain_already_registered = False - code = cleaned_data.get("code") - domain = cleaned_data.get("domain") + code = cleaned_data.get('code') + domain = cleaned_data.get('domain') response = requests.get(self.service_url, params={'code': code}).json() - # The validation response looks like: - # 1. code invalid: {} + + # 1. Code is invalid: {} if 'domain' not in response: raise ValidationError(_('This code is not valid'), code='invalid') - # 2. code valid, domain registered: {'domain': 'xx.freedombox.me'} + # 2. Code is valid, domain registered: {'domain': 'xx.freedombox.me'} elif response['domain']: if response['domain'] == domain: self.domain_already_registered = True else: - msg = _('This code is bound to the domain %s' % - response['domain']) - raise ValidationError(msg, code='invalid') - # 3. code valid, no domain registered: {'domain': None} + message = _('This code is bound to the domain {domain}.') \ + .format(domain=response['domain']) + raise ValidationError(message, code='invalid') + # 3. Code is valid, no domain registered: {'domain': None} elif response['domain'] is None: - # make sure that the desired domain is available + # Make sure that the desired domain is available data = {'domain': domain} domain_response = requests.get(self.service_url, params=data) registered_domain = domain_response.json()['domain'] if registered_domain is not None: - msg = _('The requested Domain is already registered') - raise ValidationError(msg, code='invalid') + message = _('The requested domain is already registered.') + raise ValidationError(message, code='invalid') return cleaned_data def register_domain(self): """Register a domain (only if it's not already registered)""" - if not self.domain_already_registered: - data = {'domain': self.cleaned_data['domain'], - 'code': self.cleaned_data['code']} - response = requests.post(self.service_url, data) - if not response.ok: - msg = "Domain registration failed: %s" % response.text - LOGGER.error(msg) - raise DomainRegistrationError(msg) + if self.domain_already_registered: + return + + data = {'domain': self.cleaned_data['domain'], + 'code': self.cleaned_data['code']} + response = requests.post(self.service_url, data) + if not response.ok: + message = _('Domain registration failed: {response}.').format( + response=response.text) + logger.error(message) + raise DomainRegistrationError(message) def setup_pagekite(self): - """Configure pagekite and enable the pagekite service""" - # set kite name and secret + """Configure and enable PageKite service.""" + # Set kite name and secret run(['set-kite', '--kite-name', self.cleaned_data['domain']], input=self.cleaned_data['code'].encode()) - # set frontend + # Set frontend run(['set-frontend', '%s:80' % self.cleaned_data['domain']]) - # enable pagekite http+https service + # Enable PageKite HTTP + HTTPS service for service_name in ['http', 'https']: service = PREDEFINED_SERVICES[service_name]['params'] try: diff --git a/plinth/modules/first_boot/templates/firstboot_state5.html b/plinth/modules/first_boot/templates/firstboot_state5.html index 088cf24ba..18652d10c 100644 --- a/plinth/modules/first_boot/templates/firstboot_state5.html +++ b/plinth/modules/first_boot/templates/firstboot_state5.html @@ -24,43 +24,45 @@ {% block content %} -

{% trans "Set up a freedombox.me subdomain with your voucher" %}

+

{% trans "Setup a freedombox.me subdomain with your voucher" %}

-

-{% url 'first_boot:state10' as finish_firstboot_url %} -{% blocktrans trimmed %} - Skip the setup if you do not have a - voucher or want to configure pagekite without using a freedombox.me subdomain. -{% endblocktrans %} -

+

+ {% url 'first_boot:state10' as finish_firstboot_url %} + {% blocktrans trimmed %} + Skip this step if you + do not have a voucher or want to configure PageKite later with a + different domain or credentials. + {% endblocktrans %} +

-

-{% blocktrans trimmed %} - You can use a redeemed voucher but it will only work with the initially - registered subdomain. -{% endblocktrans %} -

+

+ {% blocktrans trimmed %} + You can use an already redeemed voucher but it will only work + with the initially registered subdomain. + {% endblocktrans %} +

-
-
-
- {% csrf_token %} - {{ form|bootstrap_horizontal:'col-lg-3' }} -
-
- - - {% trans "Skip Registration" %} - +
+
+ + {% csrf_token %} + + {{ form|bootstrap_horizontal:'col-lg-3' }} +
+
+ + + {% trans "Skip Registration" %} + +
-
- - + +
-
{% endblock %} {% block page_js %} diff --git a/plinth/modules/first_boot/views.py b/plinth/modules/first_boot/views.py index 36af8be46..628b925b6 100644 --- a/plinth/modules/first_boot/views.py +++ b/plinth/modules/first_boot/views.py @@ -43,8 +43,10 @@ class State1View(CreateView): success_url = reverse_lazy('first_boot:state10') def __init__(self, *args, **kwargs): + """Initialize the view object.""" if cfg.danube_edition: self.success_url = reverse_lazy('first_boot:state5') + return super(State1View, self).__init__(*args, **kwargs) def get_form_kwargs(self): @@ -72,26 +74,26 @@ def state10(request): class State5View(FormView): - """ - State 5 is is the (optional) setup of the pagekite freedombox.me subdomain - """ + """State 5 is the (optional) setup of the Pagekite subdomain.""" template_name = 'firstboot_state5.html' form_class = State5Form success_url = reverse_lazy('first_boot:state10') def get(self, *args, **kwargs): + """Respond to GET request.""" kvstore.set('firstboot_state', 5) return super(State5View, self).get(*args, **kwargs) def form_valid(self, form): + """Act on valid form submission.""" try: form.register_domain() - except DomainRegistrationError as err: - messages.error(self.request, err) + except DomainRegistrationError as error: + messages.error(self.request, error) return HttpResponseRedirect(reverse_lazy('first_boot:state5')) else: form.setup_pagekite() - msg = _("Pagekite setup finished. The HTTP and HTTPS services \ - are activated now.") - messages.success(self.request, msg) + message = _('Pagekite setup finished. The HTTP and HTTPS services ' + 'are activated now.') + messages.success(self.request, message) return super(State5View, self).form_valid(form) diff --git a/setup.py b/setup.py index 361e845c7..cb0596a06 100755 --- a/setup.py +++ b/setup.py @@ -185,8 +185,8 @@ setuptools.setup( 'django-stronghold', 'psutil', 'python-augeas', - 'requests', 'pyyaml', + 'requests', ], tests_require=['coverage >= 3.7'], include_package_data=True,