Reorganize python sources into 'plinth' package

This commit is contained in:
Sunil Mohan Adapa committed 2014-08-29 12:57:27 +05:30
1 parent eaacd3864b
commit 65fa648d9f
109 files changed
+63 -61

No files matched your search

View File
Whitespace-only changes.
+25
View File
@@ -0,0 +1,25 @@
#
# 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 Apps section page
"""
from . import apps
from .apps import init
__all__ = ['apps', 'init']
+14
View File
@@ -0,0 +1,14 @@
from django.template.response import TemplateResponse
from gettext import gettext as _
from plinth import cfg
def init():
"""Initailize the apps module"""
cfg.main_menu.add_urlname("Apps", "icon-download-alt", "apps:index", 80)
def index(request):
"""Serve the apps index page"""
return TemplateResponse(request, 'apps.html', {'title': _('Applications')})
+31
View File
@@ -0,0 +1,31 @@
{% 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 %}
{% block main_block %}
<p>User Applications are web apps hosted on your
{{ cfg.product_name }}.</p>
<p>Eventually this box could be your photo sharing site, your instant
messaging site, your social networking site, your news site. Remember
web portals? We can be one of those too. Many of the services you
use on the web could soon be on site and under your control!</p>
{% endblock %}
+28
View File
@@ -0,0 +1,28 @@
#
# 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/>.
#
"""
URLs for the Apps module
"""
from django.conf.urls import patterns, url
urlpatterns = patterns( # pylint: disable-msg=C0103
'plinth.modules.apps.apps',
url(r'^apps/$', 'index', name='index')
)
+27
View File
@@ -0,0 +1,27 @@
#
# 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 basic system configuration
"""
from . import config
from .config import init
__all__ = ['config', 'init']
DEPENDS = ['system']
+167
View File
@@ -0,0 +1,167 @@
#
# 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 timezone, hostname etc.
"""
from django import forms
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core import validators
from django.template.response import TemplateResponse
from gettext import gettext as _
import logging
import re
import socket
from plinth import actions
from plinth import cfg
from plinth import util
LOGGER = logging.getLogger(__name__)
def get_hostname():
"""Return the hostname"""
return socket.gethostname()
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):
"""Main system configuration form"""
time_zone = forms.ChoiceField(
label=_('Time Zone'),
help_text=_('Set your timezone to get accurate timestamps. \
This information will be used to set your systemwide timezone'))
# We're more conservative than RFC 952 and RFC 1123
hostname = TrimmedCharField(
label=_('Hostname'),
help_text=_('Your hostname is the local name by which other machines \
on your LAN can reach you. It must be alphanumeric, start with an alphabet \
and must not be greater than 63 characters in length.'),
validators=[
validators.RegexValidator(r'^[a-zA-Z][a-zA-Z0-9]{,62}$',
_('Invalid hostname'))])
def __init__(self, *args, **kwargs):
# pylint: disable-msg=E1101, W0233
forms.Form.__init__(self, *args, **kwargs)
self.fields['time_zone'].choices = [(zone, zone)
for zone in self.get_time_zones()]
@staticmethod
def get_time_zones():
"""Return list of available time zones"""
time_zones = []
for line in open('/usr/share/zoneinfo/zone.tab'):
if re.match(r'^(#|\s*$)', line):
continue
try:
time_zones.append(line.split()[2])
except IndexError:
pass
time_zones.sort()
return time_zones
def init():
"""Initialize the module"""
menu = cfg.main_menu.get('system:index')
menu.add_urlname(_('Configure'), 'icon-cog', 'config:index', 10)
@login_required
def index(request):
"""Serve the configuration form"""
status = get_status()
form = None
is_expert = request.user.groups.filter(name='Expert').exists()
if request.method == 'POST' and is_expert:
form = ConfigurationForm(request.POST, prefix='configuration')
# pylint: disable-msg=E1101
if form.is_valid():
_apply_changes(request, status, form.cleaned_data)
status = get_status()
form = ConfigurationForm(initial=status,
prefix='configuration')
else:
form = ConfigurationForm(initial=status, prefix='configuration')
return TemplateResponse(request, 'config.html',
{'title': _('General Configuration'),
'form': form,
'is_expert': is_expert})
def get_status():
"""Return the current status"""
return {'hostname': get_hostname(),
'time_zone': util.slurp('/etc/timezone').rstrip()}
def _apply_changes(request, old_status, new_status):
"""Apply the form changes"""
if old_status['hostname'] != new_status['hostname']:
try:
set_hostname(new_status['hostname'])
except Exception as exception:
messages.error(request, _('Error setting hostname: %s') %
str(exception))
else:
messages.success(request, _('Hostname set'))
else:
messages.info(request, _('Hostname is unchanged'))
if old_status['time_zone'] != new_status['time_zone']:
try:
actions.superuser_run('timezone-change', [new_status['time_zone']])
except Exception as exception:
messages.error(request, _('Error setting time zone: %s') %
str(exception))
else:
messages.success(request, _('Time zone set'))
else:
messages.info(request, _('Time zone is unchanged'))
def set_hostname(hostname):
"""Sets machine hostname to hostname"""
# Hostname should be ASCII. If it's unicode but passed our
# valid_hostname check, convert to ASCII.
hostname = str(hostname)
LOGGER.info('Changing hostname to - %s', hostname)
actions.superuser_run('xmpp-pre-hostname-change')
actions.superuser_run('hostname-change', hostname)
actions.superuser_run('xmpp-hostname-change', hostname, async=True)
@@ -0,0 +1,43 @@
{% 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 main_block %}
{% if is_expert %}
<form class="form" method="post">
{% csrf_token %}
{{ form|bootstrap }}
<input type="submit" class="btn-primary" value="Submit"/>
</form>
{% else %}
<p>Only members of the expert group are allowed to see and modify
the system setup.</p>
{% endif %}
{% endblock %}
+28
View File
@@ -0,0 +1,28 @@
#
# 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/>.
#
"""
URLs for the Configuration module
"""
from django.conf.urls import patterns, url
urlpatterns = patterns( # pylint: disable-msg=C0103
'plinth.modules.config.config',
url(r'^sys/config/$', 'index', name='index'),
)
+27
View File
@@ -0,0 +1,27 @@
#
# 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 system diagnostics
"""
from . import diagnostics
from .diagnostics import init
__all__ = ['diagnostics', 'init']
DEPENDS = ['system']
+59
View File
@@ -0,0 +1,59 @@
#
# 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 running diagnostics
"""
from django.contrib.auth.decorators import login_required
from django.template.response import TemplateResponse
from gettext import gettext as _
from plinth import actions
from plinth import cfg
from plinth.errors import ActionError
def init():
"""Initialize the module"""
menu = cfg.main_menu.get('system:index')
menu.add_urlname("Diagnostics", "icon-screenshot", "diagnostics:index", 30)
@login_required
def index(request):
"""Serve the index page"""
return TemplateResponse(request, 'diagnostics.html',
{'title': _('System Diagnostics')})
@login_required
def test(request):
"""Run diagnostics and the output page"""
output = ''
error = ''
try:
output = actions.superuser_run("diagnostic-test")
except ActionError as exception:
output, error = exception.args[1:]
except Exception as exception:
error = str(exception)
return TemplateResponse(request, 'diagnostics_test.html',
{'title': _('Diagnostic Test'),
'diagnostics_output': output,
'diagnostics_error': error})
@@ -0,0 +1,31 @@
{% 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 %}
{% block main_block %}
<p>The system diagnostic test will run a number of checks on your
system to confirm that network services are running and configured
properly. It may take a minute to complete.</p>
<p><a class="btn btn-primary btn-large" href="{% url 'diagnostics:test' %}">
Run diagnostic test &raquo;
</a></p>
{% endblock %}
@@ -0,0 +1,33 @@
{% 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 %}
{% block main_block %}
{% if diagnostics_error %}
<p>The diagnostic test encountered an error:<p>
<pre>{{ diagnostics_error }}</pre>
{% endif %}
{% if diagnostics_output %}
<p>Output of diagnostic test:</p>
<pre>{{ diagnostics_output }}</pre>
{% endif %}
{% endblock %}
+29
View File
@@ -0,0 +1,29 @@
#
# 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/>.
#
"""
URLs for the Diagnostics module
"""
from django.conf.urls import patterns, url
urlpatterns = patterns( # pylint: disable-msg=C0103
'plinth.modules.diagnostics.diagnostics',
url(r'^sys/diagnostics/$', 'index', name='index'),
url(r'^sys/diagnostics/test/$', 'test', name='test'),
)
+1
View File
@@ -0,0 +1 @@
../apps/
+1
View File
@@ -0,0 +1 @@
../config/
+1
View File
@@ -0,0 +1 @@
../diagnostics/
+1
View File
@@ -0,0 +1 @@
../expert_mode/
+1
View File
@@ -0,0 +1 @@
../firewall/
+1
View File
@@ -0,0 +1 @@
../first_boot/
+1
View File
@@ -0,0 +1 @@
../help/
+1
View File
@@ -0,0 +1 @@
../lib/
+1
View File
@@ -0,0 +1 @@
../owncloud/
+1
View File
@@ -0,0 +1 @@
../packages/
+1
View File
@@ -0,0 +1 @@
../pagekite/
+1
View File
@@ -0,0 +1 @@
../system/
+1
View File
@@ -0,0 +1 @@
../tor/
+1
View File
@@ -0,0 +1 @@
../users/
+1
View File
@@ -0,0 +1 @@
../xmpp/
+27
View File
@@ -0,0 +1,27 @@
#
# 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 expert mode configuration
"""
from . import expert_mode
from .expert_mode import init
__all__ = ['expert_mode', 'init']
DEPENDS = ['system']
+64
View File
@@ -0,0 +1,64 @@
from django import forms
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.template.response import TemplateResponse
from gettext import gettext as _
from plinth import cfg
from plinth.modules.lib.auth import get_group
class ExpertsForm(forms.Form): # pylint: disable-msg=W0232
"""Form to configure expert mode"""
expert_mode = forms.BooleanField(
label=_('Expert Mode'), required=False)
def init():
"""Initialize the module"""
menu = cfg.main_menu.get('system:index')
menu.add_urlname(_('Expert Mode'), 'icon-cog', 'expert_mode:index', 10)
@login_required
def index(request):
"""Serve the configuration form"""
status = get_status(request)
form = None
if request.method == 'POST':
form = ExpertsForm(request.POST, prefix='experts')
# pylint: disable-msg=E1101
if form.is_valid():
_apply_changes(request, form.cleaned_data)
status = get_status(request)
form = ExpertsForm(initial=status, prefix='experts')
else:
form = ExpertsForm(initial=status, prefix='experts')
return TemplateResponse(request, 'expert_mode.html',
{'title': _('Expert Mode'),
'form': form})
def get_status(request):
"""Return the current status"""
return {'expert_mode': request.user.groups.filter(name='Expert').exists()}
def _apply_changes(request, new_status):
"""Apply expert mode configuration"""
message = (messages.info, _('Settings unchanged'))
expert_group = get_group('Expert')
if new_status['expert_mode']:
if not expert_group in request.user.groups.all():
request.user.groups.add(expert_group)
message = (messages.success, _('Expert mode enabled'))
else:
if expert_group in request.user.groups.all():
request.user.groups.remove(expert_group)
message = (messages.success, _('Expert mode disabled'))
message[0](request, message[1])
@@ -0,0 +1,49 @@
{% 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 main_block %}
<p>The {{ cfg.box_name }} can be administered in two modes, 'basic'
and 'expert'. Basic mode hides a lot of features and configuration
options that most users will never need to think about. Expert mode
allows you to get into the details.</p>
<p>Most users can operate the {{ cfg.box_name }} by configuring the
limited number of options visible in Basic mode. For the sake of
simplicity and ease of use, we hid most of {{ cfg.product_name }}'s
less frequently used options. But if you want more sophisticated
features, you can enable Expert mode, and {{ cfg.product_name }}
will present more advanced menu options.</p>
<p>You should be aware that it might be possible to render your
{{ cfg.box_name }} inaccessible via Expert mode options.</p>
<form class="form" method="post">
{% csrf_token %}
{{ form|bootstrap }}
<input type="submit" class="btn-primary" value="Submit"/>
</form>
{% endblock %}
+28
View File
@@ -0,0 +1,28 @@
#
# 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/>.
#
"""
URLs for the Expert Mode module
"""
from django.conf.urls import patterns, url
urlpatterns = patterns( # pylint: disable-msg=C0103
'plinth.modules.expert_mode.expert_mode',
url(r'^sys/expert/$', 'index', name='index'),
)
+27
View File
@@ -0,0 +1,27 @@
#
# 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 to configure a firewall
"""
from . import firewall
from .firewall import init
__all__ = ['firewall', 'init']
DEPENDS = ['system']
+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/>.
#
"""
Plinth module to configure a firewall
"""
from django.contrib.auth.decorators import login_required
from django.template.response import TemplateResponse
from gettext import gettext as _
import logging
from plinth import actions
from plinth import cfg
import plinth.service as service_module
LOGGER = logging.getLogger(__name__)
def init():
"""Initailze firewall module"""
menu = cfg.main_menu.get('system:index')
menu.add_urlname(_('Firewall'), 'icon-flag', 'firewall:index', 50)
service_module.ENABLED.connect(on_service_enabled)
@login_required
def index(request):
"""Serve introcution page"""
if not get_installed_status():
return TemplateResponse(request, 'firewall.html',
{'title': _('Firewall'),
'firewall_status': 'not_installed'})
if not get_enabled_status():
return TemplateResponse(request, 'firewall.html',
{'title': _('Firewall'),
'firewall_status': 'not_running'})
internal_enabled_services = get_enabled_services(zone='internal')
external_enabled_services = get_enabled_services(zone='external')
return TemplateResponse(
request, 'firewall.html',
{'title': _('Firewall'),
'services': service_module.SERVICES.values(),
'internal_enabled_services': internal_enabled_services,
'external_enabled_services': external_enabled_services})
def get_installed_status():
"""Return whether firewall is installed"""
output = _run(['get-installed'], superuser=True)
return output.split()[0] == 'installed'
def get_enabled_status():
"""Return whether firewall is installed"""
output = _run(['get-status'], superuser=True)
return output.split()[0] == 'running'
def get_enabled_services(zone):
"""Return the status of various services currently enabled"""
output = _run(['get-enabled-services', '--zone', zone], superuser=True)
return output.split()
def add_service(port, zone):
"""Enable a service in firewall"""
_run(['add-service', port, '--zone', zone], superuser=True)
def remove_service(port, zone):
"""Remove a service in firewall"""
_run(['remove-service', port, '--zone', zone], superuser=True)
def on_service_enabled(sender, service_id, enabled, **kwargs):
"""
Enable/disable firewall ports when a service is
enabled/disabled.
"""
del sender # Unused
del kwargs # Unused
internal_enabled_services = get_enabled_services(zone='internal')
external_enabled_services = get_enabled_services(zone='external')
LOGGER.info('Service enabled - %s, %s', service_id, enabled)
service = service_module.SERVICES[service_id]
for port in service.ports:
if enabled:
if port not in internal_enabled_services:
add_service(port, zone='internal')
if (service.is_external and
port not in external_enabled_services):
add_service(port, zone='external')
else:
# service already configured.
pass
else:
if port in internal_enabled_services:
enabled_services_on_port = [
service_.is_enabled()
for service_ in service_module.SERVICES.values()
if port in service_.ports and
service_id != service_.service_id]
if not any(enabled_services_on_port):
remove_service(port, zone='internal')
if port in external_enabled_services:
enabled_services_on_port = [
service_.is_enabled()
for service_ in service_module.SERVICES.values()
if port in service_.ports and
service_id != service_.service_id and
service_.is_external]
if not any(enabled_services_on_port):
remove_service(port, zone='external')
def _run(arguments, superuser=False):
"""Run an given command and raise exception if there was an error"""
command = 'firewall'
if superuser:
return actions.superuser_run(command, arguments)
else:
return actions.run(command, arguments)
@@ -0,0 +1,94 @@
{% 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 %}
{% block main_block %}
<p>Firewall is a network security system that controls the incoming
and outgoing network traffic on your {{ cfg.box_name }}. Keeping a
firewall enabled and properly configured reduces risk of security
threat from the Internet.</p>
<p>The following is the current status:</p>
{% if firewall_status = 'not_installed' %}
<p>Firewall is not installed. Please install it. Firewall comes
pre-installed with {{ cfg.box_name }}. On any Debian based system
(such as {{ cfg.box_name }}) you may install it using the command 'aptitude
install firewalld'</p>
{% elif firewall_status = 'not_running' %}
<p>Firewall daemon is not running. Please run it. Firewall comes
enabled by default on {{ cfg.box_name }}. On any Debian based system
(such as {{ cfg.box_name }}) you may run it using the command 'service
firewalld start' or in case of a system with systemd 'systemctl start
firewalld'</p>
{% else %}
<table class='table table-autowidth'>
<thead>
<th>Service/Port</th>
<th>Status</th>
</thead>
<tbody>
{% for service in services %}
<tr>
<td><strong>{{ service.name }}</strong></td>
<td>
{% if service.is_enabled %}
<span class='label label-success'>Enabled</span>
{% else %}
<span class='label label-important'>Disabled</span>
{% endif %}
</td>
</tr>
{% for port in service.ports %}
<tr>
<td class='cell-indented'><em>{{ port }}</em></td>
<td>
{% if port in internal_enabled_services and port in external_enabled_services %}
<span class='label label-success'>Permitted</span>
{% elif port in internal_enabled_services %}
<span class='label label-warning'>Permitted (internal only)</span>
{% elif port in external_enabled_services %}
<span class='label label-warning'>Permitted (external only)</span>
{% else %}
<span class='label label-important'>Blocked</span>
{% endif %}
</td>
</tr>
{% endfor %}
{% endfor %}
</tbody>
</table>
<p><em>The operation of the firewall is automatic. When you enable a
service it is automatically permitted in the firewall and you disable
a service is automatically disabled in the firewall.</em></p>
{% endif %}
{% endblock %}
+28
View File
@@ -0,0 +1,28 @@
#
# 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/>.
#
"""
URLs for the Firewall module
"""
from django.conf.urls import patterns, url
urlpatterns = patterns( # pylint: disable-msg=C0103
'plinth.modules.firewall.firewall',
url(r'^sys/firewall/$', 'index', name='index')
)
+24
View File
@@ -0,0 +1,24 @@
#
# 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 first boot wizard
"""
from . import first_boot
__all__ = ['first_boot']
+188
View File
@@ -0,0 +1,188 @@
"""
First Boot: Initial Plinth Configuration.
See docs/design/first-connection.mdwn for details.
The Plinth first-connection process has several stages:
0. The user connects to Plinth for the first time and is redirected from
the home page to the Hello page.
1. The user sets the Box's name, the administrator's name and
password, and the box's PGP key (optional).
2. The box generates and the user receives any PGP keys.
3. The box detects the network's configuration and restarts networking.
4. The user interacts with the box normally.
"""
from django import forms
from django.contrib import messages
from django.core import validators
from django.core.urlresolvers import reverse
from django.http.response import HttpResponseRedirect
from django.template.response import TemplateResponse
from gettext import gettext as _
from plinth import cfg
from plinth.modules.config import config
from plinth.modules.lib.auth import add_user
from withsqlite.withsqlite import sqlite_db
## TODO: flesh out these tests values
def valid_box_key(value):
"""Check whether box key is valid"""
del value # Unused
return True
class State0Form(forms.Form): # pylint: disable-msg=W0232
"""First boot state 0 form"""
hostname = forms.CharField(
label=_('Name your FreedomBox'),
help_text=_('For convenience, your FreedomBox needs a name. It \
should be something short that does not contain spaces or punctuation. \
"Willard" would be a good name while "Freestyle McFreedomBox!!!" would \
not. It must be alphanumeric, start with an alphabet and must not be greater \
than 63 characters in length.'),
validators=[
validators.RegexValidator(r'^[a-zA-Z][a-zA-Z0-9]{,62}$',
_('Invalid hostname'))])
username = forms.CharField(label=_('Username'))
password = forms.CharField(label=_('Password'),
widget=forms.PasswordInput())
box_key = forms.CharField(
label=_('Box\'s key (optional)'), required=False,
widget=forms.Textarea(), validators=[valid_box_key],
help_text=_('Cryptographic keys are used so that Box\'s identity can \
proved when talking to you. This key can be auto-generated, but if one \
already exists (from a prior FreedomBox, for example), you can paste it \
below. This key should not be the same as your key because you are not your \
FreedomBox!'))
def index(request):
"""Serve the index first boot page"""
return state0(request)
def generate_box_key():
"""Generate a box key"""
return "fake key"
def state0(request):
"""
In this state, we do time config over HTTP, name the box and
server key selection.
All the parameters are form inputs. They get passed in when
the form is submitted. This method checks the inputs and if
they validate, uses them to take action. If they do not
validate, it displays the form to give the user a chance to
input correct values. It might display an error message (in
the message parameter).
message is an optional string that we can display to the
user. It's a good place to put error messages.
"""
try:
if _read_state() >= 5:
return HttpResponseRedirect(reverse('index'))
except KeyError:
pass
## Until LDAP is in place, we'll put the box key in the cfg.store_file
status = get_state0()
form = None
if request.method == 'POST':
form = State0Form(request.POST, prefix='firstboot')
# pylint: disable-msg=E1101
if form.is_valid():
success = _apply_state0(request, status, form.cleaned_data)
if success:
# Everything is good, permanently mark and move to page 2
_write_state(1)
return HttpResponseRedirect(reverse('first_boot:state1'))
else:
form = State0Form(initial=status, prefix='firstboot')
return TemplateResponse(request, 'firstboot_state0.html',
{'title': _('First Boot!'),
'form': form})
def get_state0():
"""Return the state for form state 0"""
with sqlite_db(cfg.store_file, table="thisbox", autocommit=True) as \
database:
return {'hostname': config.get_hostname(),
'box_key': database.get('box_key', None)}
def _apply_state0(request, old_state, new_state):
"""Apply changes in state 0 form"""
success = True
with sqlite_db(cfg.store_file, table="thisbox", autocommit=True) as \
database:
database['about'] = 'Information about this FreedomBox'
if new_state['box_key']:
database['box_key'] = new_state['box_key']
elif not old_state['box_key']:
database['box_key'] = generate_box_key()
if old_state['hostname'] != new_state['hostname']:
config.set_hostname(new_state['hostname'])
error = add_user(new_state['username'], new_state['password'],
'First user, please change', '', True)
if error:
messages.error(
request, _('User account creation failed: %s') % error)
success = False
else:
messages.success(request, _('User account created'))
return success
def state1(request):
"""
State 1 is when we have a box name and key. In this state,
our task is to provide a certificate and maybe to guide the
user through installing it. We automatically move to State 2,
which is an HTTPS connection.
TODO: HTTPS failure in State 2 should returns to state 1.
"""
# TODO complete first_boot handling
# Make sure the user is not stuck on a dead end for now.
_write_state(5)
return TemplateResponse(request, 'firstboot_state1.html',
{'title': _('Installing the Certificate')})
def _read_state():
"""Read the current state from database"""
with sqlite_db(cfg.store_file, table='firstboot',
autocommit=True) as database:
return database['state']
def _write_state(state):
"""Write state to database"""
with sqlite_db(cfg.store_file, table='firstboot',
autocommit=True) as database:
database['state'] = state
+55
View File
@@ -0,0 +1,55 @@
#
# 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/>.
#
"""
Django middleware to redirect to firstboot wizard if it has not be run
yet.
"""
from django.core.urlresolvers import reverse
from django.http.response import HttpResponseRedirect
import logging
import cfg
from withsqlite.withsqlite import sqlite_db
LOGGER = logging.getLogger(__name__)
class FirstBootMiddleware(object):
"""Forward to firstboot page if firstboot isn't finished yet."""
@staticmethod
def process_request(request):
"""Handle a request as Django middleware request handler."""
# Prevent redirecting to first boot wizard in a loop by
# checking if we are already in first boot wizard.
if request.path.startswith(reverse('first_boot:index')):
return
with sqlite_db(cfg.store_file, table='firstboot') as database:
if 'state' not in database:
# Permanent redirect causes the browser to cache the redirect,
# preventing the user from navigating to /plinth until the
# browser is restarted.
return HttpResponseRedirect(reverse('first_boot:index'))
if database['state'] < 5:
LOGGER.info('First boot state - %d', database['state'])
return HttpResponseRedirect(reverse('first_boot:state%d' %
database['state']))
@@ -0,0 +1,28 @@
{% 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 %}
<div class="well sidebar-nav">
<h3>Getting Help</h3>
<p>We've done our best to make your FreedomBox easy to use. If
you have questions during setup, there are a few places to turn
for help. TODO: add links to such help.</p>
</div>
@@ -0,0 +1,55 @@
{% 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 main_block %}
<h2>Welcome to Your FreedomBox!</h2>
<p>Welcome. It looks like this FreedomBox isn't set up yet. We'll
need to ask you a just few questions to get started.</p>
<form class="form" method="post">
{% csrf_token %}
{% include 'bootstrapform/field.html' with field=form.hostname %}
<p><strong>Initial user and password.</strong> Access to this web
interface is protected by knowing a username and password.
Provide one here to register the initial privileged user. The
password can be changed and other users added later.</p>
{% include 'bootstrapform/field.html' with field=form.username %}
{% include 'bootstrapform/field.html' with field=form.password %}
{% include 'bootstrapform/field.html' with field=form.box_key %}
<input type="submit" class="btn-primary" value="Box it up!"/>
</form>
{% endblock %}
{% block sidebar_right_block %}
{% include "firstboot_sidebar.html" %}
{% endblock %}
@@ -0,0 +1,41 @@
{% 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 main_block %}
<p>Welcome screen not completely implemented yet. Press <a
href="{% url 'apps:index' %}">continue</a> to see the rest of the
web interface.</p>
<ul>
<li>TODO: explain all this cert stuff to the user.</li>
<li>TODO: add instrux for installing certificate.</li>
<li>TODO: add steps for after you have installed certificate.</li>
</ul>
{% endblock %}
{% block sidebar_right_block %}
{% include "firstboot_sidebar.html" %}
{% endblock %}
+30
View File
@@ -0,0 +1,30 @@
#
# 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/>.
#
"""
URLs for the First Boot module
"""
from django.conf.urls import patterns, url
urlpatterns = patterns( # pylint: disable-msg=C0103
'plinth.modules.first_boot.first_boot',
url(r'^firstboot/$', 'index', name='index'),
url(r'^firstboot/state0/$', 'state0', name='state0'),
url(r'^firstboot/state1/$', 'state1', name='state1')
)
+25
View File
@@ -0,0 +1,25 @@
#
# 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 help pages
"""
from . import help # pylint: disable-msg=W0622
from .help import init
__all__ = ['help', 'init']
+47
View File
@@ -0,0 +1,47 @@
import os
from gettext import gettext as _
from django.http import Http404
from django.template.response import TemplateResponse
from plinth import cfg
def init():
"""Initialize the Help module"""
menu = cfg.main_menu.add_urlname(_('Documentation'), 'icon-book',
'help:index', 101)
menu.add_urlname(_('Where to Get Help'), 'icon-search',
'help:index_explicit', 5)
menu.add_urlname(_('Developer\'s Manual'), 'icon-info-sign',
'help:helppage', 10, url_args=('plinth',))
menu.add_urlname(_('FAQ'), 'icon-question-sign', 'help:helppage', 20,
url_args=('faq',))
menu.add_item(_('%s Wiki' % cfg.box_name), 'icon-pencil',
'http://wiki.debian.org/FreedomBox', 30)
menu.add_urlname(_('About'), 'icon-star', 'help:about', 100)
def index(request):
"""Serve the index page"""
return TemplateResponse(request, 'help.html',
{'title': _('Documentation and FAQ')})
def about(request):
"""Serve the about page"""
title = _('About the {box_name}').format(box_name=cfg.box_name)
return TemplateResponse(request, 'about.html', {'title': title})
def helppage(request, page):
"""Serve a help page from the 'doc' directory"""
try:
with open(os.path.join('doc', '%s.part.html' % page), 'r') \
as input_file:
main = input_file.read()
except IOError:
raise Http404
title = _('%s Documentation') % cfg.product_name
return TemplateResponse(request, 'base.html',
{'title': title, 'main': main})
+62
View File
@@ -0,0 +1,62 @@
{% extends 'base.html' %}
{% load static %}
{% 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 %}
{% block main_block %}
<img src="{% static 'theme/img/freedombox-logo-250px.png' %}"
class="main-graphic" />
<p>We live in a world where our use of the network is mediated by
those who often do not have our best interests at heart. By building
software that does not rely on a central service, we can regain
control and privacy. By keeping our data in our homes, we gain useful
legal protections over it. By giving back power to the users over
their networks and machines, we are returning the Internet to its
intended peer-to-peer architecture.</p>
<p>In order to bring about the new network order, it is
paramount that it is easy to convert to it. The hardware it
runs on must be cheap. The software it runs on must be easy to
install and administrate by anybody. It must be easy to
transition from existing services.</p>
<p><a class="btn btn-primary btn-large"
href="http://wiki.debian.org/FreedomBox" target="_blank">Learn more
&raquo;</a></p>
{% endblock %}
{% block sidebar_right_block %}
<div class="well sidebar-nav">
<h3>Our Goal</h3>
<p>There are a number of projects working to realize a future of
distributed services; we aim to bring them all together in a
convenient package.</p>
<p>For more information about the FreedomBox project, see the
<a href="http://wiki.debian.org/FreedomBox">Debian Wiki</a>.</p>
</div>
{% endblock %}
+45
View File
@@ -0,0 +1,45 @@
{% 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 %}
{% block main_block %}
<p>There are a variety of places to go for help with
{{ cfg.product_name }} and the box it runs on.</p>
<p>This front end has a <a href="{% url 'help:helppage' 'plinth' %}">
developer's manual</a>. It isn't complete, but it is the first place
to look. Feel free to offer suggestions, edits, and screenshots for
completing it!</p>
<p><a href="http://wiki.debian.org/FreedomBox" target="_blank">A
section of the Debian wiki</a> is devoted to the {{ cfg.box_name }}.
At some point the documentation in the wiki and the documentation in
the manual should dovetail.</p>
<p>There are Debian gurus in the #debian channels of both
irc.freenode.net and irc.oftc.net. They probably don't know much
about the {{ cfg.box_name }} and almost surely know nothing of this
front end, but they are an incredible resource for general Debian
issues.</p>
<p>There is no <a href="{% url 'help:helppage' 'faq' %}">FAQ</a> because
the question frequency is currently zero for all questions.</p>
{% endblock %}
+34
View File
@@ -0,0 +1,34 @@
#
# 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/>.
#
"""
URLs for the Help module
"""
from django.conf.urls import patterns, url
urlpatterns = patterns( # pylint: disable-msg=C0103
'plinth.modules.help.help',
# having two urls for one page is a hack to help the current url/menu
# system highlight the correct menu item. Every submenu-item with the same
# url prefix as the main-menu is highlighted automatically.
url(r'^help/$', 'index', name='index'),
url(r'^help/index/$', 'index', name='index_explicit'),
url(r'^help/about/$', 'about', name='about'),
url(r'^help/page/(plinth|hacking|faq)/$', 'helppage', name='helppage'),
)
+24
View File
@@ -0,0 +1,24 @@
#
# 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 library modules
"""
from . import auth
__all__ = ['auth']
+29
View File
@@ -0,0 +1,29 @@
from django.contrib.auth.models import Group, User
def add_user(username, passphrase, name='', email='', expert=False):
"""Add a new user with specified username and passphrase"""
if not username:
return 'Must specify a username!'
if not passphrase:
return 'Must specify a passphrase!'
user = User.objects.create_user(username, email=email,
password=passphrase)
user.first_name = name
user.save()
if expert:
user.groups.add(get_group('Expert'))
def get_group(name):
"""Return an existing or newly created group with given name"""
try:
group = Group.objects.get(name__exact=name)
except Group.DoesNotExist:
group = Group(name=name)
group.save()
return group
+32
View File
@@ -0,0 +1,32 @@
#
# 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/>.
#
"""
URLs for the Lib module
"""
from django.conf.urls import patterns, url
from django.core.urlresolvers import reverse_lazy
urlpatterns = patterns( # pylint: disable-msg=C0103
'',
url(r'^accounts/login/$', 'django.contrib.auth.views.login',
{'template_name': 'login.html'}, name='login'),
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout',
{'next_page': reverse_lazy('index')}, name='logout')
)
+27
View File
@@ -0,0 +1,27 @@
#
# 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 to configure ownCloud
"""
from . import owncloud
from .owncloud import init
__all__ = ['owncloud', 'init']
DEPENDS = ['apps']
+77
View File
@@ -0,0 +1,77 @@
from django import forms
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.template.response import TemplateResponse
from gettext import gettext as _
from plinth import actions
from plinth import cfg
from plinth import service
SERVICE = None
class OwnCloudForm(forms.Form): # pylint: disable-msg=W0232
"""ownCloud configuration form"""
enabled = forms.BooleanField(label=_('Enable ownCloud'), required=False)
def init():
"""Initialize the ownCloud module"""
menu = cfg.main_menu.get('apps:index')
menu.add_urlname('Owncloud', 'icon-picture', 'owncloud:index', 35)
status = get_status()
global SERVICE # pylint: disable-msg=W0603
SERVICE = service.Service('owncloud', _('ownCloud'), ['http', 'https'],
is_external=True, enabled=status['enabled'])
@login_required
def index(request):
"""Serve the ownCloud configuration page"""
status = get_status()
form = None
if request.method == 'POST':
form = OwnCloudForm(request.POST, prefix='owncloud')
# pylint: disable-msg=E1101
if form.is_valid():
_apply_changes(request, status, form.cleaned_data)
status = get_status()
form = OwnCloudForm(initial=status, prefix='owncloud')
else:
form = OwnCloudForm(initial=status, prefix='owncloud')
return TemplateResponse(request, 'owncloud.html',
{'title': _('ownCloud'),
'form': form})
def get_status():
"""Return the current status"""
output = actions.run('owncloud-setup', 'status')
return {'enabled': 'enable' in output.split()}
def _apply_changes(request, old_status, new_status):
"""Apply the changes"""
if old_status['enabled'] == new_status['enabled']:
messages.info(request, _('Setting unchanged'))
return
if new_status['enabled']:
messages.success(request, _('ownCloud enabled'))
option = 'enable'
else:
messages.success(request, _('ownCloud disabled'))
option = 'noenable'
actions.superuser_run('owncloud-setup', [option], async=True)
# Send a signal to other modules that the service is
# enabled/disabled
SERVICE.notify_enabled(None, new_status['enabled'])
@@ -0,0 +1,61 @@
{% 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 main_block %}
<form class="form" method="post">
{% csrf_token %}
{{ form|bootstrap }}
<p>When enabled, the owncloud installation will be available
from <a href="/owncloud">owncloud</a> on the web server. Visit
this URL to set up the initial administration account for
owncloud.</p>
<p><strong>Note: Setting up owncloud for the first time might take
5 minutes or more, depending on download bandwidth from the
Debian APT sources.</strong></p>
<input type="submit" class="btn-primary" value="Update setup"/>
</form>
{% endblock %}
{% block sidebar_right_block %}
<div class="well sidebar-nav">
<h3>ownCloud</h3>
<p>ownCloud gives you universal access to your files through a web
interface or WebDAV. It also provides a platform to easily view
& sync your contacts, calendars and bookmarks across all your
devices and enables basic editing right on the web. Installation
has minimal server requirements, doesn't need special
permissions and is quick. ownCloud is extendable via a simple
but powerful API for applications and plugins.</p>
</div>
{% endblock %}
+28
View File
@@ -0,0 +1,28 @@
#
# 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/>.
#
"""
URLs for the ownCloud module
"""
from django.conf.urls import patterns, url
urlpatterns = patterns( # pylint: disable-msg=C0103
'plinth.modules.owncloud.owncloud',
url(r'^apps/owncloud/$', 'index', name='index'),
)
+27
View File
@@ -0,0 +1,27 @@
#
# 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 to manage packages
"""
from . import packages
from .packages import init
__all__ = ['packages', 'init']
DEPENDS = ['system']
+111
View File
@@ -0,0 +1,111 @@
from django import forms
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.template.response import TemplateResponse
from gettext import gettext as _
from plinth import actions
from plinth import cfg
def get_modules_available():
"""Return list of all modules"""
output = actions.run('module-manager', ['list-available'])
return output.split()
def get_modules_enabled():
"""Return list of all modules"""
output = actions.run('module-manager', ['list-enabled'])
return output.split()
class PackagesForm(forms.Form):
"""Packages form"""
def __init__(self, *args, **kwargs):
# pylint: disable-msg=E1002, E1101
super(forms.Form, self).__init__(*args, **kwargs)
modules_available = get_modules_available()
for module in modules_available:
label = _('Enable {module}').format(module=module)
self.fields[module + '_enabled'] = forms.BooleanField(
label=label, required=False)
def init():
"""Initialize the Packages module"""
menu = cfg.main_menu.get('system:index')
menu.add_urlname('Package Manager', 'icon-gift', 'packages:index', 20)
@login_required
def index(request):
"""Serve the form"""
status = get_status()
form = None
if request.method == 'POST':
form = PackagesForm(request.POST, prefix='packages')
# pylint: disable-msg=E1101
if form.is_valid():
_apply_changes(request, status, form.cleaned_data)
status = get_status()
form = PackagesForm(initial=status, prefix='packages')
else:
form = PackagesForm(initial=status, prefix='packages')
return TemplateResponse(request, 'packages.html',
{'title': _('Add/Remove Plugins'),
'form': form})
def get_status():
"""Return the current status"""
modules_available = get_modules_available()
modules_enabled = get_modules_enabled()
return {module + '_enabled': module in modules_enabled
for module in modules_available}
def _apply_changes(request, old_status, new_status):
"""Apply form changes"""
for field, enabled in new_status.items():
if not field.endswith('_enabled'):
continue
if old_status[field] == new_status[field]:
continue
module = field.split('_enabled')[0]
if enabled:
try:
actions.superuser_run(
'module-manager', ['enable', cfg.python_root, module])
except Exception:
# TODO: need to get plinth to load the module we just
# enabled
messages.error(
request, _('Error enabling module - {module}').format(
module=module))
else:
messages.success(
request, _('Module enabled - {module}').format(
module=module))
else:
try:
actions.superuser_run(
'module-manager', ['disable', cfg.python_root, module])
except Exception:
# TODO: need a smoother way for plinth to unload the
# module
messages.error(
request, _('Error disabling module - {module}').format(
module=module))
else:
messages.success(
request, _('Module disabled - {module}').format(
module=module))
@@ -0,0 +1,61 @@
{% 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 main_block %}
<p>aptitude purge modules</p>
<p>aptitude install modules</p>
<p>The modules should depend on the appropriate Debian packages.</p>
<h2>Manage Plugins</h2>
<form class="form" method="post">
{% csrf_token %}
{{ form|bootstrap }}
<p>Enabling a plugin will cause a corresponding page to appear in
Plinth.</p>
<input type="submit" class="btn-primary" value="Update setup"/>
</form>
{% endblock %}
{% block sidebar_right_block %}
<div class="well sidebar-nav">
<h3>Help</h3>
<p>On this page, you can add or remove {{ cfg.product_name }}
plugins to your {{ cfg.box_name }}.</p>
<p>Plugins are just Debian packages, so Debian's usual package
management features should make this job fairly easy.</p>
</div>
{% endblock %}
+28
View File
@@ -0,0 +1,28 @@
#
# 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/>.
#
"""
URLs for the Packages module
"""
from django.conf.urls import patterns, url
urlpatterns = patterns( # pylint: disable-msg=C0103
'plinth.modules.packages.packages',
url(r'^sys/packages/$', 'index', name='index')
)
+27
View File
@@ -0,0 +1,27 @@
#
# 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 to configure PageKite
"""
from . import pagekite
from .pagekite import init
__all__ = ['pagekite', 'init']
DEPENDS = ['apps']
+204
View File
@@ -0,0 +1,204 @@
#
# 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 import RequestContext
from django.template.loader import render_to_string
from django.template.response import TemplateResponse
from gettext import gettext as _
import logging
from plinth import actions
from plinth import cfg
LOGGER = logging.getLogger(__name__)
def init():
"""Intialize the PageKite module"""
menu = cfg.main_menu.get('apps:index')
menu.add_urlname(_('Public Visibility (PageKite)'), 'icon-flag',
'pagekite:index', 50)
@login_required
def index(request):
"""Serve introdution page"""
menu = {'title': _('PageKite'),
'items': [{'url': reverse_lazy('pagekite:configure'),
'text': _('Configure PageKite')}]}
sidebar_right = render_to_string('menu_block.html', {'menu': menu},
RequestContext(request))
return TemplateResponse(request, 'pagekite_introduction.html',
{'title': _('Public Visibility (PageKite)'),
'sidebar_right': sidebar_right})
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
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'),
'form': form})
def get_status():
"""
Return the current status of PageKite configuration by
executing various actions.
"""
status = {}
# Check if PageKite is installed
output = _run(['get-installed'])
if output.split()[0] != 'installed':
return None
# 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 an 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)
@@ -0,0 +1,75 @@
{% 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 main_block %}
{% if pagekite_status = 'not_installed' %}
<p>PageKite is not installed, please install it. PageKite comes
pre-installed with {{ cfg.box_name }}. On any Debian based system
(such as {{ cfg.box_name }}) you may install it using the command
'aptitude install pagekite'</p>
{% else %}
<form class="form" method="post">
{% csrf_token %}
{% include 'bootstrapform/field.html' with field=form.enabled %}
<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 %}
<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-primary" value="Update setup"/>
</form>
{% endif %}
{% endblock %}
{% block js_block %}
{{ js|safe }}
<script type="text/javascript">
(function($) {
$('#id_pagekite-enabled').change(function() {
if ($('#id_pagekite-enabled').prop('checked')) {
$('#pagekite-post-enabled-form').show('slow');
} else {
$('#pagekite-post-enabled-form').hide('slow');
}
});
})(jQuery);
</script>
{% endblock %}
@@ -0,0 +1,56 @@
{% 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 %}
{% block main_block %}
<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
rest of the Internet. This includes the following situations: </p>
<ul>
<li>{{ cfg.box_name }} is behind a restricted firewall.</li>
<li>{{ cfg.box_name }} is connected to a (wireless) router which you
don't control.</li>
<li>Your ISP does not provide you an external IP address and instead
provides Internet connection through NAT.</li>
<li>Your ISP does not provide you a static IP address and your IP
address changes evertime you connect to Internet.</li>
<li>Your ISP limits incoming connections.</li>
</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
{{ cfg.box_name }} for this.</p>
<p>
<a class='btn btn-primary btn-lg'
href="{% url 'pagekite:configure' %}">Configure
PageKite</a>
</p>
{% endblock %}
+29
View File
@@ -0,0 +1,29 @@
#
# 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/>.
#
"""
URLs for the PageKite module
"""
from django.conf.urls import patterns, url
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'),
)
+25
View File
@@ -0,0 +1,25 @@
#
# 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 to configure santiago port
"""
from . import santiago
__all__ = ['santiago']
+124
View File
@@ -0,0 +1,124 @@
"""
santiago is the interface that listens over a tor hidden service. It
accepts json requests and responds with json data structures filled
with information. There is authentication involved, although I
haven't figured that one all the way through yet.
"""
import os, sys
import cherrypy
from gettext import gettext as _
from plugin_mount import PagePlugin
from modules.auth import require
import cfg
import util as u
santiago_port = 52854
#import gnupg
#def check_sig(query, sig):
# "Verify that the sig and the query match"
# gpg = gnupg.GPG(gnupghome='/home/james/')
# return True
class Santiago(PagePlugin):
order = 90 # order of running init in PagePlugins
def __init__(self):
super(Santiago, self).__init__()
self.register_page("santiago")
self.santiago_address = self.get_santiago_address() #TODO: multiple santiago ports
#set a listener on the santiago address
def get_santiago_address(self):
if 'santiago' in cfg.users['admin'] and 'address' in cfg.users['admin']['santiago']:
return cfg.users['admin']['santiago']['address']
else:
admin = cfg.users['admin']
admin['santiago'] = {}
with open ("/etc/tor/torrc", 'r') as INF:
rc = INF.read()
self.santiago_dir = os.path.join(cfg.file_root, "data", "santiago", "tor")
self.tor_dir = os.path.join(self.santiago_dir, "general")
u.mkdir(self.santiago_dir)
os.system( 'chmod a+w %s' % self.santiago_dir)
hidden_service_config = "HiddenServiceDir %s\nHiddenServicePort 80 127.0.0.1:%d" % (self.tor_dir, santiago_port)
if hidden_service_config in rc:
## get info from dir (but how? we need perms)
## just fake it for now
admin['santiago']['address'] = "b5wycujkfh2jxfdo.onion"
cfg.users['admin'] = admin
return cfg.users['admin']['santiago']['address']
print "Need to add these two lines to /etc/torrc:\n%s" % hidden_service_config
return ""
def check_for_hidden_service(self):
pass
@cherrypy.expose
def index(self, *args, **kw):
"""
A request is a dict with some required keys:
req - this is the request. It is a dict that has keys of use to serving the request.
version - the version number of this description (currently 1)
entropy - a random string of at least 256 bytes.
signature - an optional signature
"""
if (cherrypy.request.local.port != santiago_port
#or not check_sig(kw['q'], kw['sig'])
#or cherrypy.request.method.upper() != "POST"
):
raise cherrypy.HTTPError(404)
return kw['q']
from pprint import pformat
#return str(cherrypy.request.params)
return '''
<html><head><title>CP Info</title></head>
<body><pre>%s</pre></body></html>
''' % pformat({
'args': args,
'kw': kw,
'request': dict([(k, getattr(cherrypy.request, k))
for k in dir(cherrypy.request)
if not k.startswith('_')]),
})
#try:
# query = json.loads(q)
#except:
# raise cherrypy.HTTPError(404)
## client requests proxy methods
## we send back a list of proxy methods (complete with routes/IP addresses to connect to)
return str(cherrypy.request.local.port)
a = "<br />".join(dir(cherrypy.request))
a += cherrypy.request.query_string + "!!!!!!!!!!!!"
a += str(cherrypy.request.local.port)
return a
return "test " + cherrypy.request.method.upper() + " "+t
## Plinth page to config santiago
class santiago(PagePlugin):
def __init__(self):
super(Santiago, self).__init__(self)
self.menu = cfg.html_root.privacy.menu.add_item("Santiago", "icon-leaf", "/privacy/santiago", 10)
self.register_page("privacy.santiago")
@cherrypy.expose
@require()
def index(self):
return "Santiago's config goes here."
+26
View File
@@ -0,0 +1,26 @@
#
# 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 system section page
"""
from . import system
from system import init
__all__ = ['system', 'init']
+15
View File
@@ -0,0 +1,15 @@
from gettext import gettext as _
from django.template.response import TemplateResponse
from plinth import cfg
def init():
"""Initialize the system module"""
cfg.main_menu.add_urlname(_('System'), 'icon-cog', 'system:index', 100)
def index(request):
"""Serve the index page"""
return TemplateResponse(request, 'system.html',
{'title': _('System Configuration')})
@@ -0,0 +1,29 @@
{% 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 %}
{% block main_block %}
<p>In this section, you can control the {{ cfg.product_name }}'s
underlying system, as opposed to its various applications and
services. These options affect the {{ cfg.product_name }} at its most
general level. This is where you add/remove users, install
applications, reboot, etc.</p>
{% endblock %}
+28
View File
@@ -0,0 +1,28 @@
#
# 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/>.
#
"""
URLs for the System module
"""
from django.conf.urls import patterns, url
urlpatterns = patterns( # pylint: disable-msg=C0103
'plinth.modules.system.system',
url(r'^sys/$', 'index', name='index'),
)
+27
View File
@@ -0,0 +1,27 @@
#
# 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 to configure Tor
"""
from . import tor
from .tor import init
__all__ = ['tor', 'init']
DEPENDS = ['apps']
+47
View File
@@ -0,0 +1,47 @@
{% 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 %}
{% block main_block %}
<p>Tor is an anonymous communication system. You can learn more about
it from the <a href="https://www.torproject.org/">Tor Project</a>
website. For best protection when web surfing, the Tor Project
recommends that you use
the <a href="https://www.torproject.org/download/download-easy.html.en">Tor
Browser Bundle</a>.</p>
<p>A Tor SOCKS port is available on your FreedomBox on TCP port
9050.</p>
<p>Your FreedomBox is configured as a Tor bridge with obfsproxy, so it
can help circumvent censorship. If your FreedomBox is behind a router
or firewall, you should make sure the following ports are open, and
port-forwarded, if necessary:</p>
<table class="table table-bordered table-condensed span2">
{% for name, port in tor_ports.items %}
<tr>
<td>{{ name }}</td>
<td>{{ port }}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
+52
View File
@@ -0,0 +1,52 @@
#
# 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 Tor
"""
from django.contrib.auth.decorators import login_required
from django.template.response import TemplateResponse
from gettext import gettext as _
from plinth import actions
from plinth import cfg
def init():
"""Initialize the Tor module"""
menu = cfg.main_menu.get('apps:index')
menu.add_urlname("Tor", "icon-eye-close", "tor:index", 30)
@login_required
def index(request):
"""Service the index page"""
output = actions.superuser_run("tor-get-ports")
port_info = output.split("\n")
tor_ports = {}
for line in port_info:
try:
(key, val) = line.split()
tor_ports[key] = val
except ValueError:
continue
return TemplateResponse(request, 'tor.html',
{'title': _('Tor Control Panel'),
'tor_ports': tor_ports})
+28
View File
@@ -0,0 +1,28 @@
#
# 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/>.
#
"""
URLs for the Tor module
"""
from django.conf.urls import patterns, url
urlpatterns = patterns( # pylint: disable-msg=C0103
'plinth.modules.tor.tor',
url(r'^apps/tor/$', 'index', name='index')
)
+27
View File
@@ -0,0 +1,27 @@
#
# 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 to manage users
"""
from . import users
from .users import init
__all__ = ['users', 'init']
DEPENDS = ['system']
@@ -0,0 +1,50 @@
{% 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 main_block %}
<form class="form" method="post">
{% csrf_token %}
{{ form|bootstrap }}
<input type="submit" class="btn-primary" value="Add User"/>
</form>
{% endblock %}
{% block sidebar_right_block %}
<div class="well sidebar-nav">
<h3>Add User</h3>
<p>Adding a user via this administrative
interface <strong>might</strong> create a system user. For
example, if you provide a user with ssh access, she will need a
system account. If you don't know what that means, don't worry
about it.</p>
</div>
{% endblock %}
@@ -0,0 +1,55 @@
{% 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 main_block %}
<form class="form" method="post">
{% csrf_token %}
{{ form|bootstrap }}
<input type="submit" class="btn-primary" value="Delete User"/>
</form>
{% endblock %}
{% block sidebar_right_block %}
<div class="well sidebar-nav">
<h3>Edit Users</h3>
<p>Click on a user's name to go to a screen for editing that
user's account.</p>
<h3>Delete Users</h3>
<p>Check the box next to a users' names and then click "Delete
User" to remove users from {{ cfg.product_name }} and the
{{ cfg.box_name }} system.</p>
<p>Deleting users is permanent!</p>
</div>
{% endblock %}
+30
View File
@@ -0,0 +1,30 @@
#
# 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/>.
#
"""
URLs for the Users module
"""
from django.conf.urls import patterns, url
urlpatterns = patterns( # pylint: disable-msg=C0103
'plinth.modules.users.users',
url(r'^sys/users/$', 'index', name='index'),
url(r'^sys/users/add/$', 'add', name='add'),
url(r'^sys/users/edit/$', 'edit', name='edit')
)
+152
View File
@@ -0,0 +1,152 @@
from django import forms
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core import validators
from django.core.urlresolvers import reverse_lazy
from django.template import RequestContext
from django.template.loader import render_to_string
from django.template.response import TemplateResponse
from gettext import gettext as _
import logging
from plinth import cfg
from plinth.modules.lib.auth import add_user
LOGGER = logging.getLogger(__name__)
def init():
"""Intialize the module"""
menu = cfg.main_menu.get('system:index')
menu.add_urlname(_('Users and Groups'), 'icon-user', 'users:index', 15)
@login_required
def index(request):
"""Return a rendered users page"""
menu = {'title': _('Users and Groups'),
'items': [{'url': reverse_lazy('users:add'),
'text': _('Add User')},
{'url': reverse_lazy('users:edit'),
'text': _('Edit Users')}]}
sidebar_right = render_to_string('menu_block.html', {'menu': menu},
RequestContext(request))
return TemplateResponse(request, 'base.html',
{'title': _('Manage Users and Groups'),
'sidebar_right': sidebar_right})
class UserAddForm(forms.Form): # pylint: disable-msg=W0232
"""Form to add a new user"""
username = forms.CharField(
label=_('Username'),
help_text=_('Must be lower case alphanumeric and start with \
and alphabet'),
validators=[
validators.RegexValidator(r'^[a-z][a-z0-9]*$',
_('Invalid username'))])
password = forms.CharField(label=_('Password'),
widget=forms.PasswordInput())
full_name = forms.CharField(label=_('Full name'), required=False)
email = forms.EmailField(label=_('Email'), required=False)
@login_required
def add(request):
"""Serve the form"""
form = None
if request.method == 'POST':
form = UserAddForm(request.POST, prefix='user')
# pylint: disable-msg=E1101
if form.is_valid():
_add_user(request, form.cleaned_data)
form = UserAddForm(prefix='user')
else:
form = UserAddForm(prefix='user')
return TemplateResponse(request, 'users_add.html',
{'title': _('Add User'),
'form': form})
def _add_user(request, data):
"""Add a user"""
if User.objects.filter(username=data['username']).exists():
messages.error(request, _('User "{username}" already exists').format(
username=data['username']))
return
add_user(data['username'], data['password'], data['full_name'],
data['email'], False)
messages.success(request, _('User "{username}" added').format(
username=data['username']))
class UserEditForm(forms.Form): # pylint: disable-msg=W0232
"""Form to edit/delete a user"""
def __init__(self, *args, **kwargs):
# pylint: disable-msg=E1002
super(forms.Form, self).__init__(*args, **kwargs)
for user in User.objects.all():
label = '%s (%s)' % (user.first_name, user.username)
field = forms.BooleanField(label=label, required=False)
# pylint: disable-msg=E1101
self.fields['delete_user_' + user.username] = field
@login_required
def edit(request):
"""Serve the edit form"""
form = None
if request.method == 'POST':
form = UserEditForm(request.POST, prefix='user')
# pylint: disable-msg=E1101
if form.is_valid():
_apply_edit_changes(request, form.cleaned_data)
form = UserEditForm(prefix='user')
else:
form = UserEditForm(prefix='user')
return TemplateResponse(request, 'users_edit.html',
{'title': _('Edit or Delete User'),
'form': form})
def _apply_edit_changes(request, data):
"""Apply form changes"""
for field, value in data.items():
if not value:
continue
if not field.startswith('delete_user_'):
continue
username = field.split('delete_user_')[1]
requesting_user = request.user.username
LOGGER.info('%s asked to delete %s', requesting_user, username)
if username == requesting_user:
messages.error(
request, _('Can not delete current account - "%s"') % username)
continue
if not User.objects.filter(username=username).exists():
messages.error(request, _('User "%s" does not exist') % username)
continue
try:
User.objects.filter(username=username).delete()
messages.success(request, _('User "%s" deleted') % username)
except IOError as exception:
messages.error(request, _('Error deleting "%s" - %s') %
(username, exception))
+27
View File
@@ -0,0 +1,27 @@
#
# 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 to configure XMPP server
"""
from . import xmpp
from .xmpp import init
__all__ = ['xmpp', 'init']
DEPENDS = ['apps']
@@ -0,0 +1,34 @@
{% 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 main_block %}
<form class="form" method="post">
{% csrf_token %}
{{ form|bootstrap }}
<input type="submit" class="btn-primary" value="Update setup"/>
</form>
{% endblock %}
@@ -0,0 +1,34 @@
{% 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 main_block %}
<form class="form" method="post">
{% csrf_token %}
{{ form|bootstrap }}
<input type="submit" class="btn-primary" value="Register XMPP Account"/>
</form>
{% endblock %}
+30
View File
@@ -0,0 +1,30 @@
#
# 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/>.
#
"""
URLs for the XMPP module
"""
from django.conf.urls import patterns, url
urlpatterns = patterns( # pylint: disable-msg=C0103
'plinth.modules.xmpp.xmpp',
url(r'^apps/xmpp/$', 'index', name='index'),
url(r'^apps/xmpp/configure/$', 'configure', name='configure'),
url(r'^apps/xmpp/register/$', 'register', name='register')
)
+165
View File
@@ -0,0 +1,165 @@
from django import forms
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse_lazy
from django.template import RequestContext
from django.template.loader import render_to_string
from django.template.response import TemplateResponse
from gettext import gettext as _
import logging
from plinth import actions
from plinth import cfg
from plinth import service
LOGGER = logging.getLogger(__name__)
SIDE_MENU = {
'title': _('XMPP'),
'items': [
{
'url': reverse_lazy('xmpp:configure'),
'text': _('Configure XMPP Server'),
},
{
'url': reverse_lazy('xmpp:register'),
'text': _('Register XMPP Account'),
}
]
}
def init():
"""Initialize the XMPP module"""
menu = cfg.main_menu.get('apps:index')
menu.add_item('Chat', 'icon-comment', '/../jwchat', 20)
menu.add_urlname('XMPP', 'icon-comment', 'xmpp:index', 40)
service.Service(
'xmpp-client', _('Chat Server - client connections'),
is_external=True, enabled=True)
service.Service(
'xmpp-server', _('Chat Server - server connections'),
is_external=True, enabled=True)
service.Service(
'xmpp-bosh', _('Chat Server - web interface'), is_external=True,
enabled=True)
@login_required
def index(request):
"""Serve XMPP page"""
main = "<p>XMPP Server Accounts and Configuration</p>"
sidebar_right = render_to_string('menu_block.html', {'menu': SIDE_MENU},
RequestContext(request))
return TemplateResponse(request, 'base.html',
{'title': _('XMPP Server'),
'main': main,
'sidebar_right': sidebar_right})
class ConfigureForm(forms.Form): # pylint: disable-msg=W0232
"""Configuration form"""
inband_enabled = forms.BooleanField(
label=_('Allow In-Band Registration'), required=False,
help_text=_('When enabled, anyone who can reach this server will be \
allowed to register an account through an XMPP client'))
@login_required
def configure(request):
"""Serve the configuration form"""
status = get_status()
form = None
if request.method == 'POST':
form = ConfigureForm(request.POST, prefix='xmpp')
# pylint: disable-msg=E1101
if form.is_valid():
_apply_changes(request, status, form.cleaned_data)
status = get_status()
form = ConfigureForm(initial=status, prefix='xmpp')
else:
form = ConfigureForm(initial=status, prefix='xmpp')
sidebar_right = render_to_string('menu_block.html', {'menu': SIDE_MENU},
RequestContext(request))
return TemplateResponse(request, 'xmpp_configure.html',
{'title': _('Configure XMPP Server'),
'form': form,
'sidebar_right': sidebar_right})
def get_status():
"""Return the current status"""
output = actions.run('xmpp-setup', 'status')
return {'inband_enabled': 'inband_enable' in output.split()}
def _apply_changes(request, old_status, new_status):
"""Apply the form changes"""
LOGGER.info('Status - %s, %s', old_status, new_status)
if old_status['inband_enabled'] == new_status['inband_enabled']:
messages.info(request, _('Setting unchanged'))
return
if new_status['inband_enabled']:
messages.success(request, _('Inband registration enabled'))
option = 'inband_enable'
else:
messages.success(request, _('Inband registration disabled'))
option = 'noinband_enable'
LOGGER.info('Option - %s', option)
actions.superuser_run('xmpp-setup', [option])
class RegisterForm(forms.Form): # pylint: disable-msg=W0232
"""Configuration form"""
username = forms.CharField(label=_('Username'))
password = forms.CharField(
label=_('Password'), widget=forms.PasswordInput())
@login_required
def register(request):
"""Serve the registration form"""
form = None
if request.method == 'POST':
form = RegisterForm(request.POST, prefix='xmpp')
# pylint: disable-msg=E1101
if form.is_valid():
_register_user(request, form.cleaned_data)
form = RegisterForm(prefix='xmpp')
else:
form = RegisterForm(prefix='xmpp')
sidebar_right = render_to_string('menu_block.html', {'menu': SIDE_MENU},
RequestContext(request))
return TemplateResponse(request, 'xmpp_register.html',
{'title': _('Register XMPP Account'),
'form': form,
'sidebar_right': sidebar_right})
def _register_user(request, data):
"""Register a new XMPP user"""
output = actions.superuser_run(
'xmpp-register', [data['username'], data['password']])
if 'successfully registered' in output:
messages.success(request, _('Registered account for %s') %
data['username'])
else:
messages.error(request,
_('Failed to register account for %s: %s') %
(data['username'], output))