Merge remote-tracking branch 'fonfon/pagekite-augeas-new'

This commit is contained in:
James Valleroy committed 2015-05-16 10:35:58 -04:00
commit 44b045fef7
21 files changed
+1402 -524

No files matched your search

View File
Whitespace-only changes.
+10 -3
View File
@@ -19,9 +19,16 @@
Plinth module to configure PageKite
"""
from . import pagekite
from .pagekite import init
from gettext import gettext as _
from plinth import cfg
__all__ = ['pagekite', 'init']
__all__ = ['init']
depends = ['plinth.modules.apps']
def init():
"""Intialize the PageKite module"""
menu = cfg.main_menu.get('apps:index')
menu.add_urlname(_('Public Visibility (PageKite)'),
'glyphicon-flag', 'pagekite:index', 50)
+224
View File
@@ -0,0 +1,224 @@
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import copy
from gettext import gettext as _
import json
import logging
from django import forms
from django.contrib import messages
from django.core import validators
from plinth.errors import ActionError
from .util import _run, get_kite_details, BACKEND_HOST, KITE_NAME, \
KITE_SECRET, PREDEFINED_SERVICES
LOGGER = logging.getLogger(__name__)
class TrimmedCharField(forms.CharField):
"""Trim the contents of a CharField"""
def clean(self, value):
"""Clean and validate the field value"""
if value:
value = value.strip()
return super(TrimmedCharField, self).clean(value)
class ConfigurationForm(forms.Form):
"""Configure PageKite credentials and frontend"""
enabled = forms.BooleanField(label=_('Enable PageKite'), required=False)
server = forms.CharField(
label=_('Server'), required=False,
help_text=_('Select your pagekite.net server. Set "pagekite.net" to '
'use the default pagekite.net server'),
widget=forms.TextInput())
kite_name = TrimmedCharField(
label=_('Kite name'),
help_text=_('Example: mybox.pagekite.me'),
validators=[
validators.RegexValidator(r'^[\w-]{1,63}(\.[\w-]{1,63})*$',
_('Invalid kite name'))])
kite_secret = TrimmedCharField(
label=_('Kite secret'),
help_text=_('A secret associated with the kite or the default secret \
for your account if no secret is set on the kite'))
def save(self, request):
old = self.initial
new = self.cleaned_data
LOGGER.info('New status is - %s', new)
if old != new:
config_changed = False
if old['kite_name'] != new['kite_name'] or \
old['kite_secret'] != new['kite_secret']:
_run(['set-kite', '--kite-name', new['kite_name'],
'--kite-secret', new['kite_secret']])
messages.success(request, _('Kite details set'))
config_changed = True
if old['server'] != new['server']:
_run(['set-frontend', new['server']])
messages.success(request, _('Pagekite server set'))
config_changed = True
if old['enabled'] != new['enabled']:
if new['enabled']:
_run(['start-and-enable'])
messages.success(request, _('PageKite enabled'))
else:
_run(['stop-and-disable'])
messages.success(request, _('PageKite disabled'))
# Restart the service if the config was changed while the service
# was running, so changes take effect immediately.
elif config_changed and new['enabled']:
_run(['restart'])
class StandardServiceForm(forms.Form):
"""Creates a form out of PREDEFINED_SERVICES"""
def __init__(self, *args, **kwargs):
"""Add the fields from PREDEFINED_SERVICES"""
super(StandardServiceForm, self).__init__(*args, **kwargs)
kite = get_kite_details()
for name, service in PREDEFINED_SERVICES.items():
if name in ('http', 'https'):
help_text = service['help_text'].format(kite['kite_name'])
else:
help_text = service['help_text']
self.fields[name] = forms.BooleanField(label=service['label'],
help_text=help_text,
required=False)
def save(self, request):
formdata = self.cleaned_data
for service_name in PREDEFINED_SERVICES.keys():
if self.initial[service_name] != formdata[service_name]:
service = PREDEFINED_SERVICES[service_name]['params']
service = json.dumps(service)
if formdata[service_name]:
_run(['add-service', '--service', service])
messages.success(request, _('Service enabled: {name}')
.format(name=service_name))
else:
_run(['remove-service', '--service', service])
messages.success(request, _('Service disabled: {name}')
.format(name=service_name))
class BaseCustomServiceForm(forms.Form):
"""Basic form functionality to handle a custom service"""
choices = [("http", "http"), ("https", "https"), ("raw", "raw")]
protocol = forms.ChoiceField(choices=choices, label="protocol")
frontend_port = forms.IntegerField(min_value=0, max_value=65535,
label="external (frontend) port",
required=True)
backend_port = forms.IntegerField(min_value=0, max_value=65535,
label="internal (freedombox) port")
subdomains = forms.BooleanField(label="Enable Subdomains", required=False)
def convert_formdata_to_service(self, formdata):
"""Add information to make a service out of the form data"""
# convert integers to str (to compare values with DEFAULT_SERVICES)
for field in ('frontend_port', 'backend_port'):
formdata[field] = str(formdata[field])
# set kitename and kitesecret if not already set
if 'kitename' not in formdata:
if 'subdomains' in formdata and formdata['subdomains']:
formdata['kitename'] = "*.%s" % KITE_NAME
else:
formdata['kitename'] = KITE_NAME
if 'secret' not in formdata:
formdata['secret'] = KITE_SECRET
# merge protocol and frontend_port back to one entry (protocol)
if 'frontend_port' in formdata:
if formdata['frontend_port'] not in formdata['protocol']:
formdata['protocol'] = "%s/%s" % (formdata['protocol'],
formdata['frontend_port'])
if 'backend_host' not in formdata:
formdata['backend_host'] = BACKEND_HOST
return formdata
class DeleteCustomServiceForm(BaseCustomServiceForm):
def delete(self, request):
service = self.convert_formdata_to_service(self.cleaned_data)
_run(['remove-service', '--service', json.dumps(service)])
messages.success(request, _('Deleted custom service'))
class AddCustomServiceForm(BaseCustomServiceForm):
"""Adds the save() method and validation to not add predefined services"""
def matches_predefined_service(self, formdata):
"""Returns whether the user input matches a predefined service"""
service = self.convert_formdata_to_service(formdata)
match_found = False
for predefined_service_obj in PREDEFINED_SERVICES.values():
# manually add the port to compare predefined with custom services
# that's due to the (sometimes) implicit port in the configuration
predefined_service = copy.copy(predefined_service_obj['params'])
if predefined_service['protocol'] == 'http':
predefined_service['protocol'] = 'http/80'
elif predefined_service['protocol'] == 'https':
predefined_service['protocol'] = 'https/443'
# The formdata service has additional keys, so we can't compare
# the dicts directly.
# instead look whether predefined_service is a subset of service
if all(service[k] == v for k, v in predefined_service.items()):
match_found = True
break
return match_found
def clean(self):
cleaned_data = super(AddCustomServiceForm, self).clean()
try:
is_predefined = self.matches_predefined_service(cleaned_data)
except KeyError:
is_predefined = False
if is_predefined:
msg = _("""This service is available as a standard service. Please
use the 'Standard Services' page to enable it.""")
raise forms.ValidationError(msg)
return cleaned_data
def save(self, request):
service = self.convert_formdata_to_service(self.cleaned_data)
try:
_run(['add-service', '--service', json.dumps(service)])
messages.success(request, _('Added custom service'))
except ActionError as exception:
if "already exists" in str(exception):
messages.error(request, _('This service already exists'))
else:
raise
-199
View File
@@ -1,199 +0,0 @@
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
Plinth module for configuring PageKite service
"""
from django import forms
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core import validators
from django.core.urlresolvers import reverse_lazy
from django.template.response import TemplateResponse
from gettext import gettext as _
import logging
from plinth import actions
from plinth import cfg
from plinth import package
LOGGER = logging.getLogger(__name__)
subsubmenu = [{'url': reverse_lazy('pagekite:index'),
'text': _('About PageKite')},
{'url': reverse_lazy('pagekite:configure'),
'text': _('Configure PageKite')}]
def init():
"""Intialize the PageKite module"""
menu = cfg.main_menu.get('apps:index')
menu.add_urlname(_('Public Visibility (PageKite)'),
'glyphicon-flag', 'pagekite:index', 50)
@login_required
def index(request):
"""Serve introduction page"""
return TemplateResponse(request, 'pagekite_introduction.html',
{'title': _('Public Visibility (PageKite)'),
'subsubmenu': subsubmenu})
class TrimmedCharField(forms.CharField):
"""Trim the contents of a CharField"""
def clean(self, value):
"""Clean and validate the field value"""
if value:
value = value.strip()
return super(TrimmedCharField, self).clean(value)
class ConfigureForm(forms.Form): # pylint: disable-msg=W0232
"""Form to configure PageKite"""
enabled = forms.BooleanField(label=_('Enable PageKite'),
required=False)
server = forms.CharField(
label=_('Server'), required=False,
help_text=_('Currently only pagekite.net server is supported'),
widget=forms.TextInput(attrs={'placeholder': 'pagekite.net',
'disabled': 'disabled'}))
kite_name = TrimmedCharField(
label=_('Kite name'),
help_text=_('Example: mybox1-myacc.pagekite.me'),
validators=[
validators.RegexValidator(r'^[\w-]{1,63}(\.[\w-]{1,63})*$',
_('Invalid kite name'))])
kite_secret = TrimmedCharField(
label=_('Kite secret'),
help_text=_('A secret associated with the kite or the default secret \
for your account if no secret is set on the kite'))
http_enabled = forms.BooleanField(
label=_('Web Server (HTTP)'), required=False,
help_text=_('Site will be available at \
<a href="http://mybox1-myacc.pagekite.me">http://mybox1-myacc.pagekite.me \
</a>'))
ssh_enabled = forms.BooleanField(
label=_('Secure Shell (SSH)'), required=False,
help_text=_('See SSH client setup <a href="\
https://pagekite.net/wiki/Howto/SshOverPageKite/">instructions</a>'))
@login_required
@package.required(['pagekite'])
def configure(request):
"""Serve the configuration form"""
status = get_status()
form = None
if request.method == 'POST':
form = ConfigureForm(request.POST, prefix='pagekite')
# pylint: disable-msg=E1101
if form.is_valid():
_apply_changes(request, status, form.cleaned_data)
status = get_status()
form = ConfigureForm(initial=status, prefix='pagekite')
else:
form = ConfigureForm(initial=status, prefix='pagekite')
return TemplateResponse(request, 'pagekite_configure.html',
{'title': _('Configure PageKite'),
'status': status,
'form': form,
'subsubmenu': subsubmenu})
def get_status():
"""
Return the current status of PageKite configuration by
executing various actions.
"""
status = {}
# PageKite service enabled/disabled
output = _run(['get-status'])
status['enabled'] = (output.split()[0] == 'enabled')
# PageKite kite details
output = _run(['get-kite'])
kite_details = output.split()
status['kite_name'] = kite_details[0]
status['kite_secret'] = kite_details[1]
# Service status
status['service'] = {}
for service in ('http', 'ssh'):
output = _run(['get-service-status', service])
status[service + '_enabled'] = (output.split()[0] == 'enabled')
return status
def _apply_changes(request, old_status, new_status):
"""Apply the changes to PageKite configuration"""
LOGGER.info('New status is - %s', new_status)
if old_status != new_status:
_run(['stop'])
if old_status['enabled'] != new_status['enabled']:
if new_status['enabled']:
_run(['set-status', 'enable'])
messages.success(request, _('PageKite enabled'))
else:
_run(['set-status', 'disable'])
messages.success(request, _('PageKite disabled'))
if old_status['kite_name'] != new_status['kite_name'] or \
old_status['kite_secret'] != new_status['kite_secret']:
_run(['set-kite', '--kite-name', new_status['kite_name'],
'--kite-secret', new_status['kite_secret']])
messages.success(request, _('Kite details set'))
for service in ['http', 'ssh']:
if old_status[service + '_enabled'] != \
new_status[service + '_enabled']:
if new_status[service + '_enabled']:
_run(['set-service-status', service, 'enable'])
messages.success(request, _('Service enabled: {service}')
.format(service=service))
else:
_run(['set-service-status', service, 'disable'])
messages.success(request, _('Service disabled: {service}')
.format(service=service))
if old_status != new_status:
_run(['start'])
def _run(arguments, superuser=True):
"""Run a given command and raise exception if there was an error"""
command = 'pagekite-configure'
if superuser:
return actions.superuser_run(command, arguments)
else:
return actions.run(command, arguments)
@@ -30,17 +30,12 @@
<div id='pagekite-post-enabled-form'
style='display: {{ form.enabled.value|yesno:'block,none' }};'>
<h3>PageKite Account</h3>
{% include 'bootstrapform/field.html' with field=form.server %}
{% include 'bootstrapform/field.html' with field=form.kite_name %}
{% include 'bootstrapform/field.html' with field=form.kite_secret %}
{{ form.server|bootstrap_horizontal }}
{{ form.kite_name|bootstrap_horizontal }}
{{ form.kite_secret|bootstrap_horizontal }}
<h3>Services</h3>
{% include 'bootstrapform/field.html' with field=form.http_enabled %}
{% include 'bootstrapform/field.html' with field=form.ssh_enabled %}
</div>
<input type="submit" class="btn btn-primary" value="Update setup"/>
<input type="submit" class="btn btn-primary" value="Save settings"/>
</form>
{% endblock %}
@@ -0,0 +1,104 @@
{% extends "base.html" %}
{% comment %}
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
{% endcomment %}
{% load bootstrap %}
{% load pagekite_extras %}
{% block page_head %}
<style type="text/css">
div.custom-services span.service {
display: inline-block;
padding-top: 6px;
}
form.pull-right button {
margin: 10px 5px;
}
.add-service input.btn {
margin: 10px 0px;
}
</style>
{% endblock %}
{% block content %}
<div class="alert alert-warning" role="alert">
<b>Warning:</b><br>Your PageKite frontend server may not support all the
protocol/port combinations that you are able to define here. For example,
HTTPS on ports other than 443 is known to cause problems.
</div>
<div class="row custom-services">
<div class="col-lg-6">
<form class="form add-service" method="post">
<h4>Create a custom service</h4>
{{ form|bootstrap_horizontal:'col-lg-6' }}
{% csrf_token %}
<div class="form-group">
<div class=" col-lg-offset-6 col-lg-6">
<input type="submit" class="btn btn-primary" value="Add Service"/>
</div>
</div>
</form>
</div>
<div class="col-lg-5 col-lg-offset-1">
<h4>Existing custom services</h4>
{% if not custom_services %}
<i>You don't have any Custom Services enabled</i>
{% endif %}
<div class="list-group">
{% for service in custom_services %}
{% create_pagekite_service_url service kite_name as service_url %}
<div class="list-group-item clearfix">
<span class="service">
<span title="Connects {{ service_url }} to {{ service.backend_host }}:{{ service.backend_port }}">
{% if service_url|slice:":4" == "http" %}
<a href="{{ service_url }}">{{ service_url }}</a>
{% else %}
{{ service_url }}
{% endif %}
<br>
connected to {{ service.backend_host }}:{{ service.backend_port }}
</span>
</span>
<form class="form pull-right" method="post"
action="{% url 'pagekite:delete-custom-service' %}">
<div style='display:none'>
{% csrf_token %}
{{ service.form.as_p }}
</div>
<button type="submit" class="btn btn-default"
title="Delete this service">
<span class="glyphicon glyphicon-trash" aria-hidden="true">
</span>
</button>
</form>
</div>
{% endfor %}
</div>
</div>
</div>
{% endblock %}
@@ -22,7 +22,7 @@
<p>PageKite is a system for exposing {{ cfg.box_name }} services when
you don't have a direct connection to the Internet. You only need this
service if your {{ cfg.box_name }} services are unreachable from the
if your {{ cfg.box_name }} services are unreachable from the
rest of the Internet. This includes the following situations: </p>
<ul>
@@ -41,11 +41,10 @@ rest of the Internet. This includes the following situations: </p>
</ul>
<p>PageKite works around NAT, firewalls and IP-address limitations by
using a combination of tunnels and reverse proxies. Currently,
exposing web server and SSH server are supported. An intermediary
server with direct Internet access is required. Currently, only
pagekite.net server is supported and you will need an account
there. In future, it might be possible to use your buddy's
using a combination of tunnels and reverse proxies. You can use any
pagekite service provider, for example
<a href="https://pagekite.net">pagekite.net</a>.
In future it might be possible to use your buddy's
{{ cfg.box_name }} for this.</p>
<p>
@@ -0,0 +1,52 @@
{% extends "base.html" %}
{% comment %}
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
{% endcomment %}
{% load bootstrap %}
{% block page_head %}
<style type="text/css">
div.checkbox .help-block {
display: inline-block;
margin: 0px 10px;
}
input.btn {
margin: 10px 15px;
}
</style>
{% endblock %}
{% block content %}
<div class="alert alert-warning" role="alert">
<b>Warning:</b><br>
<p>Published services are accessible and attackable from the evil internet.<p>
<p>Exposing SSH with the default password for 'fbx' is a VERY BAD idea.</p>
</div>
<form class="form predefined" method="post">
{{ form.http|bootstrap_horizontal:'col-lg-0' }}
{{ form.https|bootstrap_horizontal:'col-lg-0' }}
{{ form.ssh|bootstrap_horizontal:'col-lg-0' }}
{% csrf_token %}
<input type="submit" class="btn btn-primary" value="Save Services"/>
</form>
{% endblock %}
@@ -0,0 +1,44 @@
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from django import template
from plinth.modules.pagekite.util import prepare_service_for_display
register = template.Library()
@register.assignment_tag
def create_pagekite_service_url(service, kite_name):
"""Create a URL out of a pagekite service
Parameters: - service: the service params dictionary
- kite_name: kite name from the pagekite configuration, not
from the service params
"""
# add extra information if it's missing
if 'subdomains' not in service:
service = prepare_service_for_display(service)
urlparams = {'protocol': service['protocol']}
if service['subdomains']:
urlparams['kite_name'] = "*.%s" % kite_name
else:
urlparams['kite_name'] = kite_name
url = "{protocol}://{kite_name}".format(**urlparams)
if 'frontend_port' in service and service['frontend_port']:
url = "%s:%s" % (url, service['frontend_port'])
return url
+16 -3
View File
@@ -20,10 +20,23 @@ URLs for the PageKite module
"""
from django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required
from .views import StandardServiceView, CustomServiceView, ConfigurationView, \
DeleteServiceView, index
urlpatterns = patterns( # pylint: disable-msg=C0103
'plinth.modules.pagekite.pagekite',
url(r'^apps/pagekite/$', 'index', name='index'),
url(r'^apps/pagekite/configure/$', 'configure', name='configure'),
'plinth.modules.pagekite.views',
url(r'^apps/pagekite/$', login_required(index), name='index'),
url(r'^apps/pagekite/configure/$',
login_required(ConfigurationView.as_view()), name='configure'),
url(r'^apps/pagekite/services/standard$',
login_required(StandardServiceView.as_view()),
name='standard-services'),
url(r'^apps/pagekite/services/custom$',
login_required(CustomServiceView.as_view()), name='custom-services'),
url(r'^apps/pagekite/services/custom/delete$',
login_required(DeleteServiceView.as_view()),
name='delete-custom-service'),
)
+147
View File
@@ -0,0 +1,147 @@
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from gettext import gettext as _
import json
import logging
from plinth import actions
LOGGER = logging.getLogger(__name__)
# defaults for the credentials; @kitename acts as a placeholder and is
# understood (and replaced with the actual kitename) by pagekite.
BACKEND_HOST = 'localhost'
KITE_NAME = '@kitename'
KITE_SECRET = '@kitesecret'
SERVICE_PARAMS = ['protocol', 'kitename', 'backend_host', 'backend_port',
'secret']
# Predefined services are used to build the PredefinedServiceForm
#
# ATTENTION: When changing the params, make sure that the AddCustomServiceForm
# still recognizes when you try to add a service equal to a predefined one
PREDEFINED_SERVICES = {
'http': {
'params': {'protocol': 'http',
'kitename': KITE_NAME,
'backend_port': '80',
'backend_host': BACKEND_HOST,
'secret': KITE_SECRET},
'label': _("Web Server (HTTP)"),
'help_text': _("Site will be available at "
"<a href=\"http://{0}\">http://{0}</a>"),
},
'https': {
'params': {'protocol': 'https',
'kitename': KITE_NAME,
'backend_port': '443',
'backend_host': BACKEND_HOST,
'secret': KITE_SECRET},
'label': _("Web Server (HTTPS)"),
'help_text': _("Site will be available at "
"<a href=\"https://{0}\">https://{0}</a>"),
},
'ssh': {
'params': {'protocol': 'raw/22',
'kitename': KITE_NAME,
'backend_port': '22',
'backend_host': BACKEND_HOST,
'secret': KITE_SECRET},
'label': _("Secure Shell (SSH)"),
'help_text': _("See SSH client setup <a href=\""
"https://pagekite.net/wiki/Howto/SshOverPageKite/\">"
"instructions</a>")
},
}
def get_kite_details():
output = _run(['get-kite'])
kite_details = output.split()
return {'kite_name': kite_details[0],
'kite_secret': kite_details[1]}
def get_pagekite_config():
"""
Return the current PageKite configuration by executing various actions.
"""
status = {}
# PageKite service enabled/disabled
# This assumes that if pagekite is running it's also enabled as a service
output = _run(['is-running'])
status['enabled'] = (output.split()[0] == 'yes')
# PageKite kite details
status.update(get_kite_details())
# PageKite frontend server
server = _run(['get-frontend'])
status['server'] = server.replace('\n', '')
return status
def get_pagekite_services():
"""Get enabled services. Returns two values:
1. predefined services: {'http': False, 'ssh': True, 'https': True}
2. custom services: [{'protocol': 'http', 'secret' 'nono', ..}, [..]}
"""
custom = []
predefined = {}
# set all predefined services to 'disabled' by default
[predefined.update({proto: False}) for proto in PREDEFINED_SERVICES.keys()]
# now, search for the enabled ones
for serviceline in _run(['get-services']).split('\n'):
if not serviceline: # skip empty lines
continue
service = json.loads(serviceline)
for name, predefined_service in PREDEFINED_SERVICES.items():
if service == predefined_service['params']:
predefined[name] = True
break
else:
custom.append(service)
return predefined, custom
def prepare_service_for_display(service):
""" Add extra information that is used when displaying a service
- protocol is split into 'protocol' and 'frontend_port'
- detect whether 'subdomains' are supported (as boolean)
"""
protocol = service['protocol']
if '/' in protocol:
service['protocol'], service['frontend_port'] = protocol.split('/')
service['subdomains'] = service['kitename'].startswith('*.')
return service
def _run(arguments, superuser=True):
"""Run a given command and raise exception if there was an error"""
command = 'pagekite'
if superuser:
return actions.superuser_run(command, arguments)
else:
return actions.run(command, arguments)
+133
View File
@@ -0,0 +1,133 @@
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from gettext import gettext as _
from django.core.urlresolvers import reverse, reverse_lazy
from django.http.response import HttpResponseRedirect
from django.template.response import TemplateResponse
from django.utils.decorators import method_decorator
from django.views.generic import View, TemplateView
from django.views.generic.edit import FormView
from plinth import package
from .util import get_pagekite_config, get_pagekite_services, \
get_kite_details, prepare_service_for_display
from .forms import ConfigurationForm, StandardServiceForm, \
AddCustomServiceForm, DeleteCustomServiceForm
required_packages = ('pagekite', 'augeas-tools', 'python-augeas')
subsubmenu = [{'url': reverse_lazy('pagekite:index'),
'text': _('About PageKite')},
{'url': reverse_lazy('pagekite:configure'),
'text': _('Configure PageKite')},
{'url': reverse_lazy('pagekite:standard-services'),
'text': _('Standard Services')},
{'url': reverse_lazy('pagekite:custom-services'),
'text': _('Custom Services')}]
def index(request):
"""Serve introduction page"""
return TemplateResponse(request, 'pagekite_introduction.html',
{'title': _('Public Visibility (PageKite)'),
'subsubmenu': subsubmenu})
class ContextMixin(object):
"""Mixin to add 'subsubmenu' and 'title' to the context.
Also adds the requirement of all necessary packages to be installed
"""
def get_context_data(self, **kwargs):
"""Use self.title and the module-level subsubmenu"""
context = super(ContextMixin, self).get_context_data(**kwargs)
context['title'] = getattr(self, 'title', '')
context['subsubmenu'] = subsubmenu
return context
@method_decorator(package.required(required_packages))
def dispatch(self, *args, **kwargs):
return super(ContextMixin, self).dispatch(*args, **kwargs)
class DeleteServiceView(ContextMixin, View):
def post(self, request):
form = DeleteCustomServiceForm(request.POST)
if form.is_valid():
form.delete(request)
return HttpResponseRedirect(reverse('pagekite:custom-services'))
class CustomServiceView(ContextMixin, TemplateView):
template_name = 'pagekite_custom_services.html'
def get_context_data(self, *args, **kwargs):
context = super(CustomServiceView, self).get_context_data(*args,
**kwargs)
unused, custom_services = get_pagekite_services()
for service in custom_services:
service['form'] = AddCustomServiceForm(initial=service)
context['custom_services'] = [prepare_service_for_display(service)
for service in custom_services]
context.update(get_kite_details())
return context
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
form = AddCustomServiceForm(prefix="custom")
context['form'] = form
return self.render_to_response(context)
def post(self, request):
form = AddCustomServiceForm(request.POST, prefix="custom")
if form.is_valid():
form.save(request)
form = AddCustomServiceForm(prefix="custom")
context = self.get_context_data()
context['form'] = form
return self.render_to_response(context)
class StandardServiceView(ContextMixin, FormView):
template_name = 'pagekite_standard_services.html'
title = 'PageKite Standard Services'
form_class = StandardServiceForm
success_url = reverse_lazy('pagekite:standard-services')
def get_initial(self):
return get_pagekite_services()[0]
def form_valid(self, form):
form.save(self.request)
return super(StandardServiceView, self).form_valid(form)
class ConfigurationView(ContextMixin, FormView):
template_name = 'pagekite_configure.html'
form_class = ConfigurationForm
prefix = 'pagekite'
success_url = reverse_lazy('pagekite:configure')
def get_initial(self):
return get_pagekite_config()
def form_valid(self, form):
form.save(self.request)
return super(ConfigurationView, self).form_valid(form)