diff --git a/.gitignore b/.gitignore index 5bce3ed73..a30ed9e0c 100644 --- a/.gitignore +++ b/.gitignore @@ -19,7 +19,6 @@ doc/TODO.mdwn doc/oneline.txt doc/plinth.1 plinth.config -templates/*.py TODO \#* .#* diff --git a/INSTALL b/INSTALL index a8d6138d6..a32ae8fb8 100644 --- a/INSTALL +++ b/INSTALL @@ -2,10 +2,9 @@ ## Installing Plinth -Install the python-cheetah package, pandoc, python-augeas, and -bjsonrpc: +Install the dependencies: -apt-get install python-cheetah pandoc python-augeas python-bjsonrpc python-cherrypy3 python-simplejson +apt-get install pandoc psmisc python2.7 python-bcrypt python-cherrypy3 python-django python-passlib python-bootstrapform libjs-twitter-bootstrap sudo Unzip and untar the source into a directory. Change to the directory containing the program. Run: @@ -23,15 +22,13 @@ and the default password is "secret". * cherrypy - python web engine v3+ -* cheetah - Debian has python-cheetah package - * python - tested with version 2.6.6 * *GNU Make* is used to build the templates and such. -* bjsonrpc - used for configuration management layer +* *libjs-twitter-bootstrap* - A responsive, mobile first front-end framework -* python-augeas and augeas - used for configuration management +* *python-bootstrapform* - Render django forms for Twitter Bootstrap The documentation has some dependencies too. diff --git a/LICENSES b/LICENSES index 74ccf00e7..ab1641ef1 100644 --- a/LICENSES +++ b/LICENSES @@ -73,12 +73,10 @@ specified and linked otherwise. - share/apache2/plinth-ssl.conf :: - - share/init.d/plinth :: - - sudoers/plinth :: - -- templates/base.tmpl :: [[file:templates/base.tmpl::the%20GNU%20Affero%20General%20Public][GNU Affero General Public License, Version 3 or later]] -- templates/err.tmpl :: - -- templates/__init__.py :: - -- templates/login_nav.tmpl :: - -- templates/Makefile :: - -- templates/two_col.tmpl :: - +- templates/base.html:: [[file:templates/base.tmpl::the%20GNU%20Affero%20General%20Public][GNU Affero General Public License, Version 3 or later]] +- templates/err.html:: - +- templates/login_nav.html:: - +- templates/two_col.html:: - - tests/actions_test.py :: - - tests/auth_test.py :: - - tests/testdata/users.sqlite3 :: - @@ -87,8 +85,6 @@ specified and linked otherwise. - themes/default/FreedomBox-Logo.7z :: [[http://thread.gmane.org/gmane.linux.debian.freedombox.user/4124/focus=4439][GPL3+/CC-BY-SA]] - themes/default/readme.md :: [[file:themes/default/readme.md::This%20theme%20is%20free%20software%20offered%20to%20you%20under%20the%20terms%20of%20the%20GNU%20Affero%20General%20Public%20License,%20Version%203%20or%20later:][GNU Affero General Public License Version 3]] - themes/default/screenshot.png :: - -- themes/default/css/bootstrap.css :: [[file:themes/default/css/bootstrap.css::*%20Licensed%20under%20the%20Apache%20License%20v2.0][Apache License v2.0]] -- themes/default/css/bootstrap-responsive.css :: [[file:themes/default/css/bootstrap-responsive.css::*%20Licensed%20under%20the%20Apache%20License%20v2.0][Apache License v2.0]] - themes/default/img/apple-touch-icon-114px-precomposed.png :: - - themes/default/img/apple-touch-icon-57px-precomposed.png :: - - themes/default/img/apple-touch-icon-72px-precomposed.png :: - @@ -111,23 +107,5 @@ specified and linked otherwise. - themes/default/img/freedombox-logotype.png :: - - themes/default/img/glyphicons-halflings.png :: - - themes/default/img/glyphicons-halflings-white.png :: - -- themes/default/js/functions.js :: - -- themes/default/js/menu.js :: - -- themes/default/js/plinth.js :: - -- themes/default/js/plugins.js :: [[file:themes/default/js/plugins.js::/%20paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/][CC0]] - themes/default/js/libs/jquery.min.js :: Symlink to external target: [[file:themes/default/js/libs/jquery.min.js::*%20Dual%20licensed%20under%20the%20MIT%20or%20GPL%20Version%202%20licenses.][MIT/GPL2]] - themes/default/js/libs/modernizr.min.js :: Symlink to external target: MIT -- themes/default/js/libs/bootstrap/alert.js :: [[file:themes/default/js/libs/bootstrap/alert.js::*%20Licensed%20under%20the%20Apache%20License,%20Version%202.0%20(the%20"License")%3B][Apache License v2.0]] -- themes/default/js/libs/bootstrap/bootstrap.js :: [[file:themes/default/js/libs/bootstrap/bootstrap.js::*%20Licensed%20under%20the%20Apache%20License,%20Version%202.0%20(the%20"License")%3B][Apache License v2.0]] -- themes/default/js/libs/bootstrap/bootstrap.min.js :: - -- themes/default/js/libs/bootstrap/button.js :: [[file:themes/default/js/libs/bootstrap/button.js::*%20Licensed%20under%20the%20Apache%20License,%20Version%202.0%20(the%20"License")%3B][Apache License v2.0]] -- themes/default/js/libs/bootstrap/carousel.js :: [[file:themes/default/js/libs/bootstrap/carousel.js::*%20Licensed%20under%20the%20Apache%20License,%20Version%202.0%20(the%20"License")%3B][Apache License v2.0]] -- themes/default/js/libs/bootstrap/collapse.js :: [[file:themes/default/js/libs/bootstrap/collapse.js::*%20Licensed%20under%20the%20Apache%20License,%20Version%202.0%20(the%20"License")%3B][Apache License v2.0]] -- themes/default/js/libs/bootstrap/dropdown.js :: [[file:themes/default/js/libs/bootstrap/dropdown.js::*%20Licensed%20under%20the%20Apache%20License,%20Version%202.0%20(the%20"License")%3B][Apache License v2.0]] -- themes/default/js/libs/bootstrap/modal.js :: [[file:themes/default/js/libs/bootstrap/modal.js::*%20Licensed%20under%20the%20Apache%20License,%20Version%202.0%20(the%20"License")%3B][Apache License v2.0]] -- themes/default/js/libs/bootstrap/popover.js :: [[file:themes/default/js/libs/bootstrap/popover.js::*%20Licensed%20under%20the%20Apache%20License,%20Version%202.0%20(the%20"License")%3B][Apache License v2.0]] -- themes/default/js/libs/bootstrap/scrollspy.js :: [[file:themes/default/js/libs/bootstrap/scrollspy.js::*%20Licensed%20under%20the%20Apache%20License,%20Version%202.0%20(the%20"License")%3B][Apache License v2.0]] -- themes/default/js/libs/bootstrap/tab.js :: [[file:themes/default/js/libs/bootstrap/tab.js::*%20Licensed%20under%20the%20Apache%20License,%20Version%202.0%20(the%20"License")%3B][Apache License v2.0]] -- themes/default/js/libs/bootstrap/tooltip.js :: [[file:themes/default/js/libs/bootstrap/tooltip.js::*%20Licensed%20under%20the%20Apache%20License,%20Version%202.0%20(the%20"License")%3B][Apache License v2.0]] -- themes/default/js/libs/bootstrap/transition.js :: [[file:themes/default/js/libs/bootstrap/transition.js::*%20Licensed%20under%20the%20Apache%20License,%20Version%202.0%20(the%20"License")%3B][Apache License v2.0]] -- themes/default/js/libs/bootstrap/typeahead.js :: [[file:themes/default/js/libs/bootstrap/typeahead.js::*%20Licensed%20under%20the%20Apache%20License,%20Version%202.0%20(the%20"License")%3B][Apache License v2.0]] diff --git a/Makefile b/Makefile index 44e4356df..bf6f8c021 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,5 @@ MAKE=make -CSS=$(wildcard *.css) -CSS=$(subst .tiny,,$(shell find themes -type f -name '*.css')) -COMPRESSED_CSS := $(patsubst %.css,%.tiny.css,$(CSS)) PWD=`pwd` # hosting variables @@ -13,11 +10,11 @@ DATADIR=/usr/share/plinth PYDIR=$(DATADIR)/python/plinth ## Catch-all targets -default: config dirs template css docs +default: config dirs docs all: default predepend: - sudo sh -c "apt-get install augeas-tools libpython2.7 pandoc psmisc python2.7 python-augeas python-bcrypt python-bjsonrpc python-cheetah python-cherrypy3 python-django python-passlib python-simplejson sudo" + sudo sh -c "apt-get install pandoc psmisc python2.7 python-bcrypt python-cherrypy3 python-django python-passlib python-bootstrapform libjs-twitter-bootstrap sudo" git submodule init git submodule update touch predepend @@ -54,14 +51,6 @@ dirs: config: Makefile @test -f plinth.config || cp plinth.sample.config plinth.config -%.tiny.css: %.css - @cat $< | python -c 'import re,sys;print re.sub("\s*([{};,:])\s*", "\\1", re.sub("/\*.*?\*/", "", re.sub("\s+", " ", sys.stdin.read())))' > $@ -css: $(COMPRESSED_CSS) - -template: - @$(MAKE) -s -C templates -templates: template - docs: @$(MAKE) -s -C doc doc: docs @@ -71,14 +60,12 @@ html: clean: @rm -f cherrypy.config data/cherrypy_sessions/* - @find themes -name "*.tiny.css" -exec rm {} \; @find . -name "*~" -exec rm {} \; @find . -name ".#*" -exec rm {} \; @find . -name "#*" -exec rm {} \; @find . -name "*.pyc" -exec rm {} \; @find . -name "*.bak" -exec rm {} \; @$(MAKE) -s -C doc clean - @$(MAKE) -s -C templates clean rm -f plinth.config rm -f predepend diff --git a/doc/Makefile b/doc/Makefile index adaf5e2f1..c45bdbc99 100644 --- a/doc/Makefile +++ b/doc/Makefile @@ -41,7 +41,7 @@ $(SOURCES): @rm -f $@ @ln -s ../$(patsubst %.mdwn,%,$@) $@ -../TODO : $(TODO_SOURCES) ../*.py ../modules/*.py ../Makefile Makefile ../templates/Makefile +../TODO : $(TODO_SOURCES) ../*.py ../modules/*.py ../Makefile Makefile grep -ro --exclude=.git* --exclude=plinth.1 --exclude=*.tex --exclude=*.html \ --exclude=README.mdwn --exclude=INSTALL.mdwn \ --exclude=TODO.mdwn --exclude=COPYING.mdwn \ diff --git a/doc/modules.mdwn b/doc/modules.mdwn index 6d8851a4c..6726dcd23 100644 --- a/doc/modules.mdwn +++ b/doc/modules.mdwn @@ -51,15 +51,6 @@ metaclasses can be created to make new classes of plugins. Any place that might be affected by arbitrary addition of modules should have its own metaclass. -### FromPlugin - -Each form displayed in the interface should inherit from FormPlugin. -This will allow the system to display multiple forms on the page in -the correct order. Forms will likely also want to inherit from -PagePlugin because after the user clicks submit, the plugin usually -displays a responsive message or an error (along with the form to fill -out again). - ## Coding Practices for Modules All the diff --git a/doc/style.css b/doc/style.css index 1d1829961..499266614 120000 --- a/doc/style.css +++ b/doc/style.css @@ -1 +1 @@ -../static/theme/style.css \ No newline at end of file +../static/theme/css/bootstrap.min.css \ No newline at end of file diff --git a/doc/themes.mdwn b/doc/themes.mdwn index 3546182a9..9d95cbc73 100644 --- a/doc/themes.mdwn +++ b/doc/themes.mdwn @@ -1,8 +1,9 @@ # Themes and Templates The visual look and feel of the front end is described in theme files -while Cheetah templates -handle layout. +while Django +templates handle layout. ## Themes @@ -17,43 +18,35 @@ runtime, but it is theoretically possible. ## Templates -Plinth uses the Cheetah templating system. Templates are stored in +Plinth uses the Django templating system. Templates are stored in `/templates`. Template requirements are not specified. -TODO: formalize the template spec so template writers know what they need to implement and where they can deviate. +TODO: formalize the template spec so template writers know what they +need to implement and where they can deviate. In this section, I'll attempt to document some of the assumptions the program has about templates. The goal is that if you write a tempate that implements the spec, it should work just fine. ### The Template Stack + The template is a hierarchical stack, where some templates extend on others. At the base of this stack is `base.tmpl`. It should specify -variables as blocks (rather than using the $ notation). This allows +sections as blocks (rather than using the variables). This allows other templates to easily override the base template. -Next up is the `page.tmpl`. It extends `base.tmpl` and simply -replaces all the blocks with interpolable variables. Most of the -time, `page.tmpl` is what you will actually use to create pages. - `err.tmpl` builds on top of `page.tmpl` by adding some decoration to the title field. ### Layout -Plinth expects a `main` block. This is where the -meat of the content goes. It is the center pain in the default -layout. There is a `title` block that the program will fill with text -describing the current page. `sidebar_left` contains the submenu -navigation menu, and `sidebar_right` is where we put all short text -that helps the admin fill out forms. They don't have to be sidebars, -and they don't have to go on the left and right. +Plinth expects a `main` block. This is where the meat of the content +goes. It is the center pain in the default layout. There is a +`title` block that the program will fill with text describing the +current page. `sidebar_left` contains the submenu navigation menu, +and `sidebar_right` is where we put all short text that helps the +admin fill out forms. They don't have to be sidebars, and they don't +have to go on the left and right. It is possible to override the `footer`, but I haven't yet found a reason to do so. - -## Cheetah - -This section is for Cheetah hints that are especially useful in this context. - -TODO: add Cheetah hints diff --git a/fabfile.py b/fabfile.py index 7801834aa..c8bde9722 100644 --- a/fabfile.py +++ b/fabfile.py @@ -7,10 +7,7 @@ # plinth box import os,sys, subprocess -try: - import simplejson as json -except ImportError: - import json +import json import fabric.api from fabric.api import local, env, cd, put, get, task @@ -150,7 +147,7 @@ def apache(): @task def deps(): "Basic plinth dependencies" - sudo('apt-get install --no-install-recommends -y python make python-cheetah pandoc python-simplejson python-pyme python-augeas python-bjsonrpc') + sudo('apt-get install --no-install-recommends -y python make pandoc python-pyme python-django python-bootstrapform libjs-twitter-bootstrap') @task def update(): diff --git a/filedict.py b/filedict.py index d4f9a35ad..94f779759 100644 --- a/filedict.py +++ b/filedict.py @@ -5,13 +5,9 @@ Author: Erez Shinan Date : 31-May-2009 """ -try: - import simplejson as json ## jlv replaced pickle with json -except ImportError: - import json +import json import UserDict -##import cPickle as pickle import sqlite3 diff --git a/menu.py b/menu.py index 93860dcdb..84b26c19d 100644 --- a/menu.py +++ b/menu.py @@ -1,19 +1,16 @@ from urlparse import urlparse -try: - import simplejson as json -except ImportError: - import json import cherrypy import cfg + class Menu(): """One menu item.""" def __init__(self, label="", icon="", url="#", order=50): """label is the text that is displayed on the menu. - icon is the icon to be displayed next to the label. - Choose from the Glyphicon set: - http://twitter.github.com/bootstrap/base-css.html#icons + icon is the icon to be displayed next to the label. + Choose from the Glyphicon set: + http://twitter.github.com/bootstrap/base-css.html#icons url is the url location that will be activated when the menu item is selected. @@ -35,11 +32,13 @@ class Menu(): def sort_items(self): """Sort the items in self.items by order.""" self.items = sorted(self.items, key=lambda x: x.order, reverse=False) + def add_item(self, label, icon, url, order=50, basehref=True): """This method creates a menu item with the parameters, adds that menu item to this menu, and returns the item. - If BASEHREF is true and url start with a slash, prepend the cfg.server_dir to it""" + If BASEHREF is true and url start with a slash, prepend the + cfg.server_dir to it""" if basehref and url.startswith("/"): url = cfg.server_dir + url @@ -62,27 +61,3 @@ class Menu(): for item in self.items: if path.startswith(item.url): return item - - def serializable(self, render_subs=False): - """Return the items in self.items as a serializable object we can pass to json. - Note: this doesn't serialize all the data in this object.""" - - so = [] - for item in self.items: - i = { 'label':item.label, 'icon':item.icon, 'url':item.url} - if item.active_p(): - i['active']=True - if item.items and render_subs: - i['subs'] = item.serializable() - so.append(i) - return so - def encode(self, name="", render_subs=False): - """return a string containing a javascript data structure - assigned to the menu name - - if render_subs is True, we render submenus too""" - - return ('') diff --git a/modules/installed/apps/apps.py b/modules/installed/apps/apps.py index e463cd634..43f8fcafd 100644 --- a/modules/installed/apps/apps.py +++ b/modules/installed/apps/apps.py @@ -2,37 +2,25 @@ import cherrypy from gettext import gettext as _ from modules.auth import require from plugin_mount import PagePlugin -from forms import Form import cfg +import util + class Apps(PagePlugin): def __init__(self, *args, **kwargs): PagePlugin.__init__(self, *args, **kwargs) self.register_page("apps") self.menu = cfg.main_menu.add_item("Apps", "icon-download-alt", "/apps", 80) - self.menu.add_item("Chat", "icon-comment", "http://freedombox.local", 30) + self.menu.add_item("Chat", "icon-comment", "/../jwchat", 30) self.menu.add_item("Photo Gallery", "icon-picture", "/apps/photos", 35) @cherrypy.expose def index(self): - main = """ -
User Applications are web apps hosted on your %s.
- -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!
- """ % (cfg.product_name) - return self.fill_template(title="User Applications", main=main, sidebar_right='') + return util.render_template(template='apps', + title=_('User Applications')) @cherrypy.expose @require() def photos(self): - return self.fill_template(title="Photo Gallery", main='', sidebar_right=""" -Photo GalleryYour photos might well be the most valuable -digital property you have, so why trust it to companies that have no -investment in the sentimental value of your family snaps? Keep those -photos local, backed up, easily accessed and free from the whims of -some other websites business model.
-""") + return util.render_template(template='photos', + title=_('Photo Gallery')) diff --git a/modules/installed/apps/owncloud.py b/modules/installed/apps/owncloud.py index 6fc1d6622..7ed4dfcdb 100644 --- a/modules/installed/apps/owncloud.py +++ b/modules/installed/apps/owncloud.py @@ -1,82 +1,85 @@ import cherrypy +from django import forms from gettext import gettext as _ from modules.auth import require -from plugin_mount import PagePlugin, FormPlugin -from forms import Form +from plugin_mount import PagePlugin import actions import cfg import service -from util import Message +import util -class Owncloud(PagePlugin, FormPlugin): + +class OwnCloudForm(forms.Form): # pylint: disable-msg=W0232 + """ownCloud configuration form""" + enabled = forms.BooleanField(label=_('Enable ownCloud'), required=False) + + # XXX: Only present due to issue with submitting empty form + dummy = forms.CharField(label='Dummy', initial='dummy', + widget=forms.HiddenInput()) + + +class OwnCloud(PagePlugin): + """ownCloud configuration page""" order = 90 def __init__(self, *args, **kwargs): PagePlugin.__init__(self, *args, **kwargs) - self.register_page("apps.owncloud") - cfg.html_root.apps.menu.add_item("Owncloud", "icon-picture", "/apps/owncloud", 35) + self.register_page('apps.owncloud') + cfg.html_root.apps.menu.add_item('Owncloud', 'icon-picture', + '/apps/owncloud', 35) + + status = self.get_status() self.service = service.Service('owncloud', _('ownCloud'), ['http', 'https'], is_external=True, - enabled=self.is_enabled) - - def is_enabled(self): - """Return whether ownCloud is enabled""" - output, error = actions.run('owncloud-setup', 'status') - if error: - raise Exception('Error getting ownCloud status: %s' % error) - - return 'enable' in output.split() + enabled=status['enabled']) @cherrypy.expose @require() def index(self, **kwargs): - owncloud_enable = self.is_enabled() + """Serve the ownCloud configuration page""" + status = self.get_status() - if 'submitted' in kwargs: - owncloud_enable = self.process_form(kwargs) - - main = self.form(owncloud_enable) - sidebar_right=""" -ownCloud -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. -
-""" - return self.fill_template(title="Owncloud", main=main, sidebar_right=sidebar_right) + form = None + messages = [] - def form(self, owncloud_enable, message=None): - form = Form(title="Configuration", - action=cfg.server_dir + "/apps/owncloud/index", - name="configure_owncloud", - message=message) - form.checkbox(_("Enable Owncloud"), name="owncloud_enable", id="owncloud_enable", checked=owncloud_enable) - # hidden field is needed because checkbox doesn't post if not checked - form.hidden(name="submitted", value="True") - form.html(_("""When enabled, the owncloud installation will be available from owncloud on the web server. Visit this URL to set up the initial administration account for owncloud.
""")) - form.html(_("""Note: Setting up owncloud for the first time might take 5 minutes or more, depending on download bandwidth from the Debian APT sources.
""")) - form.submit(_("Update setup")) - return form.render() + if kwargs: + form = OwnCloudForm(kwargs, prefix='owncloud') + # pylint: disable-msg=E1101 + if form.is_valid(): + self._apply_changes(status, form.cleaned_data, messages) + status = self.get_status() + form = OwnCloudForm(initial=status, prefix='owncloud') + else: + form = OwnCloudForm(initial=status, prefix='owncloud') - def process_form(self, kwargs): - checkedinfo = { - 'enable' : False, - } + return util.render_template(template='owncloud', title=_('ownCloud'), + form=form, messages=messages) - opts = [] - for k in kwargs.keys(): - if 'on' == kwargs[k]: - shortk = k.split("owncloud_").pop() - checkedinfo[shortk] = True + @staticmethod + def get_status(): + """Return the current status""" + output, error = actions.run('owncloud-setup', 'status') + if error: + raise Exception('Error getting ownCloud status: %s' % error) - for key in checkedinfo.keys(): - if checkedinfo[key]: - opts.append(key) - else: - opts.append('no'+key) - actions.superuser_run("owncloud-setup", opts, async=True) + return {'enabled': 'enable' in output.split()} + + def _apply_changes(self, old_status, new_status, messages): + """Apply the changes""" + if old_status['enabled'] == new_status['enabled']: + messages.append(('info', _('Setting unchanged'))) + return + + if new_status['enabled']: + messages.append(('success', _('ownCloud enabled'))) + option = 'enable' + else: + messages.append(('success', _('ownCloud disabled'))) + option = 'noenable' + + actions.superuser_run('owncloud-setup', [option], async=True) # Send a signal to other modules that the service is # enabled/disabled - self.service.notify_enabled(self, checkedinfo['enable']) - - return checkedinfo['enable'] + self.service.notify_enabled(self, new_status['enabled']) diff --git a/modules/installed/apps/templates/apps.html b/modules/installed/apps/templates/apps.html new file mode 100644 index 000000000..a05062282 --- /dev/null +++ b/modules/installed/apps/templates/apps.html @@ -0,0 +1,31 @@ +{% extends 'login_nav.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, seeUser Applications are web apps hosted on your +{{ cfg.product_name }}.
+ +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!
+ +{% endblock %} diff --git a/modules/installed/apps/templates/owncloud.html b/modules/installed/apps/templates/owncloud.html new file mode 100644 index 000000000..1e7efebd0 --- /dev/null +++ b/modules/installed/apps/templates/owncloud.html @@ -0,0 +1,63 @@ +{% extends "login_nav.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, seeYour photos might well be the most valuable digital property you +have, so why trust it to companies that have no investment in the +sentimental value of your family snaps? Keep those photos local, +backed up, easily accessed and free from the whims of some other +websites business model.
+ +{% endblock %} diff --git a/modules/installed/first_boot.py b/modules/installed/first_boot.py index 47315f9a7..8fdde7b31 100644 --- a/modules/installed/first_boot.py +++ b/modules/installed/first_boot.py @@ -1,16 +1,5 @@ -from urlparse import urlparse -import os, cherrypy, re -from gettext import gettext as _ -from plugin_mount import PagePlugin, PluginMount, FormPlugin -from modules.auth import require, add_user -from forms import Form -import util as u -from withsqlite.withsqlite import sqlite_db -import cfg -import config -from model import User - -"""First Boot: Initial Plinth Configuration. +""" +First Boot: Initial Plinth Configuration. See docs/design/first-connection.mdwn for details. @@ -27,27 +16,76 @@ The Plinth first-connection process has several stages: 3. The box detects the network's configuration and restarts networking. 4. The user interacts with the box normally. - """ +import cherrypy +from django import forms +from django.core import validators +from gettext import gettext as _ +from plugin_mount import PagePlugin +from modules.auth import add_user +from withsqlite.withsqlite import sqlite_db +import cfg +import config +import util + + +## 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!')) + class FirstBoot(PagePlugin): + """First boot wizard""" + def __init__(self, *args, **kwargs): PagePlugin.__init__(self, *args, **kwargs) - self.register_page("firstboot") # this is the url this page will hang off of (/firstboot) + + # this is the url this page will hang off of (/firstboot) + self.register_page('firstboot') + self.register_page('firstboot/state0') + self.register_page('firstboot/state1') @cherrypy.expose def index(self, *args, **kwargs): return self.state0(*args, **kwargs) - ## TODO: flesh out these tests values - def valid_box_key_p(self, key): - return True def generate_box_key(self): return "fake key" @cherrypy.expose - def state0(self, message="", hostname="", box_key="", submitted=False, username="", password="", **kwargs): + def state0(self, **kwargs): """ In this state, we do time config over HTTP, name the box and server key selection. @@ -64,68 +102,70 @@ class FirstBoot(PagePlugin): """ # FIXME: reject connection attempt if db["state"] >= 5. + ## Until LDAP is in place, we'll put the box key in the cfg.store_file + status = self.get_state0() - ## Until LDAP is in place, we'll put the box name and key in the cfg.store_file - ## Must resist the sick temptation to write an LDAP interface to the sqlite file - with sqlite_db(cfg.store_file, table="thisbox", autocommit=True) as db: - db['about'] = "This table is for information about this FreedomBox" - if hostname: - if '' == config.valid_hostname(hostname): - config.set_hostname(hostname) - else: - message += _("Invalid box name: %s") % config.valid_hostname(hostname) + form = None + messages = [] + + if kwargs: + form = State0Form(kwargs, prefix='firstboot') + # pylint: disable-msg=E1101 + if form.is_valid(): + success = self._apply_state0(status, form.cleaned_data, + messages) + + if success: + # Everything is good, permanently mark and move to page 2 + with sqlite_db(cfg.store_file, table="firstboot", + autocommit=True) as database: + database['state'] = 1 + + raise cherrypy.InternalRedirect('state1') + else: + form = State0Form(initial=status, prefix='firstboot') + + return util.render_template(template='firstboot_state0', + title=_('First Boot!'), form=form, + messages=messages) + + @staticmethod + 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(self, old_state, new_state, messages): + """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'] = self.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.append( + ('error', _('User account creation failed: %s') % error)) + success = False else: - hostname = config.get_hostname() - if box_key: - if self.valid_box_key_p(box_key): - db['box_key'] = box_key - else: - message += _("Invalid key!") - elif 'box_key' in db and db['box_key']: - box_key = _("We already have a key for this box on file.") # TODO: Think this through and handle more gracefully. Seriously. - elif submitted and not box_key: - box_key = self.generate_box_key() - db['box_key'] = box_key - if username and password: - error = add_user(username, password, 'First user - please change', '', True) - if error: - message += _("User account creation failed: %s") % error - validuser = False - else: - validuser = True - else: - validuser = False + messages.append(('success', _('User account created'))) - if hostname and box_key and '' == config.valid_hostname(hostname) and self.valid_box_key_p(box_key) and validuser: - ## Update state to 1 and head there - with sqlite_db(cfg.store_file, table="firstboot", autocommit=True) as db: - db['state']=1 - raise cherrypy.InternalRedirect('state1') - - main = "Welcome. It looks like this FreedomBox isn't set up yet. We'll need to ask you a just few questions to get started.
" - form = Form(title="Welcome to Your FreedomBox!", - action="", # stay at firstboot - name="whats_my_name", - message=message) - form.html("For convenience, your FreedomBox needs a name. It should be something short that doesn't contain spaces or punctuation. 'Willard' would be a good name. 'Freestyle McFreedomBox!!!' would not.
") - form.text_input('Name your FreedomBox', id="hostname", value=hostname) - form.html("Initial user and password. 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.
") - form.text_input('Username:', id="username", value=username) - form.text_input('Password:', id="password", type='password') - form.html("%(box_name)s uses cryptographic keys so it can prove its identity when talking to you. %(box_name)s can make a key for itself, 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!
" % {'box_name':cfg.box_name}) - form.text_box("If you want, paste your box's key here.", id="box_key", value=box_key) - form.hidden(name="submitted", value="True") - form.submit("Box it up!") - - main += form.render() - return self.fill_template( - template="base", - title=_("First Boot!"), - main=main, - sidebar_right=sidebar_right) + return success + @staticmethod @cherrypy.expose - def state1(self, message=None): + def state1(): """ 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 @@ -134,31 +174,11 @@ class FirstBoot(PagePlugin): TODO: HTTPS failure in State 2 should returns to state 1. """ - main = """ -Welcome screen not completely implemented yet. Press continue to see the rest of the web interface.
- -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.
""") + return util.render_template(template='firstboot_state1', + title=_('Installing the Certificate')) diff --git a/modules/installed/help/help.py b/modules/installed/help/help.py index e05123bf5..927f9e6c6 100644 --- a/modules/installed/help/help.py +++ b/modules/installed/help/help.py @@ -3,6 +3,9 @@ import cherrypy from gettext import gettext as _ from plugin_mount import PagePlugin import cfg +import util + + class Help(PagePlugin): order = 20 # order of running init in PagePlugins def __init__(self, *args, **kwargs): @@ -17,61 +20,15 @@ class Help(PagePlugin): @cherrypy.expose def index(self): - main=""" -There are a variety of places to go for help with Plinth - and the box it runs on.
- -This front end has a developer's manual. It isn't - complete, but it is the first place to look. Feel free to - offer suggestions, edits, and screenshots for completing - it!
- -A section of - the Debian wiki is devoted to the %(box)s. At some - point the documentation in the wiki and the documentation in - the manual should dovetail.
- -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 %(box)s and almost surely know nothing of - this front end, but they are an incredible resource for - general Debian issues.
- -There is no FAQ because - the question frequency is currently zero for all - questions.
- """ % {'box':cfg.box_name} - return self.fill_template(title="Documentation and FAQ", main=main) + return util.render_template(template='help', + title=_('Documentation and FAQ')) @cherrypy.expose def about(self): - return self.fill_template(title=_("About the %s" % cfg.box_name), main=""" -
- 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.
+ return util.render_template( + template='about', + title=_('About the {box_name}').format(box_name=cfg.box_name)) -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.
- """, - sidebar_right=_("""Our GoalThere are a number of projects working to realize a future - of distributed services; we aim to bring them all together in - a convenient package.
- -For more information about the FreedomBox project, see the - Debian - Wiki.
- """)) class View(PagePlugin): def __init__(self, *args, **kwargs): @@ -82,7 +39,8 @@ class View(PagePlugin): def default(self, page=''): if page not in ['design', 'plinth', 'hacking', 'faq']: raise cherrypy.HTTPError(404, "The path '/help/view/%s' was not found." % page) - return self.fill_template(template="err", main="Sorry, as much as I would like to show you that page, I don't seem to have a page named %s!
" % page) + with open(os.path.join("doc", "%s.part.html" % page), 'r') as IF: main = IF.read() - return self.fill_template(title=_("%s Documentation" % cfg.product_name), main=main) + return util.render_template(title=_("%s Documentation" % + cfg.product_name), main=main) diff --git a/modules/installed/help/templates/about.html b/modules/installed/help/templates/about.html new file mode 100644 index 000000000..2f4a39b81 --- /dev/null +++ b/modules/installed/help/templates/about.html @@ -0,0 +1,61 @@ +{% extends 'login_nav.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
+
+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.
+ +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.
+ + + +{% endblock %} + +{% block sidebar_right_block %} + + + +{% endblock %} diff --git a/modules/installed/help/templates/help.html b/modules/installed/help/templates/help.html new file mode 100644 index 000000000..17aaedea4 --- /dev/null +++ b/modules/installed/help/templates/help.html @@ -0,0 +1,45 @@ +{% extends 'login_nav.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, seeThere are a variety of places to go for help with +{{ cfg.product_name }} and the box it runs on.
+ +This front end has a +developer's manual. It isn't complete, but it is the first place +to look. Feel free to offer suggestions, edits, and screenshots for +completing it!
+ +A +section of the Debian wiki is devoted to the {{ cfg.box_name }}. +At some point the documentation in the wiki and the documentation in +the manual should dovetail.
+ +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.
+ +There is no FAQ because +the question frequency is currently zero for all questions.
+ +{% endblock %} diff --git a/modules/installed/lib/auth.py b/modules/installed/lib/auth.py index 71b10c387..974ecef93 100644 --- a/modules/installed/lib/auth.py +++ b/modules/installed/lib/auth.py @@ -67,12 +67,14 @@ def check_credentials(username, passphrase): cfg.log(error) return error - bad_authentication = "Bad user-name or password." + bad_authentication = "Bad username or password." hashed_password = None - if username in cfg.users: - if "passphrase" in cfg.users[username]: - hashed_password = cfg.users[username]['passphrase'] + if username not in cfg.users or 'passphrase' not in cfg.users[username]: + cfg.log(bad_authentication) + return bad_authentication + + hashed_password = cfg.users[username]['passphrase'] try: # time-dependent comparison when non-ASCII characters are used. diff --git a/modules/installed/lib/auth_page.py b/modules/installed/lib/auth_page.py index 49d7a8de4..1d9b49ca3 100644 --- a/modules/installed/lib/auth_page.py +++ b/modules/installed/lib/auth_page.py @@ -1,43 +1,73 @@ +""" +Controller to provide login and logout actions +""" + import cherrypy import cfg +from django import forms +from gettext import gettext as _ from plugin_mount import PagePlugin -from modules.forms import Form -from auth import * -# Controller to provide login and logout actions +import auth +import util + + +class LoginForm(forms.Form): # pylint: disable-msg=W0232 + """Login form""" + from_page = forms.CharField(widget=forms.HiddenInput(), required=False) + + username = forms.CharField(label=_('Username')) + password = forms.CharField(label=_('Passphrase'), + widget=forms.PasswordInput()) + + def clean(self): + """Check for valid credentials""" + # pylint: disable-msg=E1101 + if 'username' in self._errors or 'password' in self._errors: + return self.cleaned_data + + error_msg = auth.check_credentials(self.cleaned_data['username'], + self.cleaned_data['password']) + if error_msg: + raise forms.ValidationError(error_msg, code='invalid_credentials') + + return self.cleaned_data + class AuthController(PagePlugin): + """Login and logout pages""" + def __init__(self, *args, **kwargs): PagePlugin.__init__(self, *args, **kwargs) - self.register_page("auth") + + self.register_page('auth') def on_login(self, username): """Called on successful login""" - + def on_logout(self, username): """Called on logout""" - - def get_loginform(self, username, msg='', from_page=cfg.server_dir+"/"): - form = Form(title="Login", action=cfg.server_dir + "/auth/login", message=msg) - form.text_input(name="from_page", value=from_page, type="hidden") - form.text_input("Username", name="username", value=username) - form.text_input("Passphrase", name="passphrase", type="password") - form.submit(label="Login") - return self.fill_template(main=form.render(), sidebar_right=" ") - @cherrypy.expose - def login(self, username=None, passphrase=None, from_page=cfg.server_dir+"/", **kwargs): - if username is None or passphrase is None: - return self.get_loginform("", from_page=from_page) - - error_msg = check_credentials(username, passphrase) - if error_msg: - return self.get_loginform(username, error_msg, from_page) + def login(self, from_page=cfg.server_dir+"/", **kwargs): + """Serve the login page""" + form = None + + if kwargs: + form = LoginForm(kwargs, prefix='auth') + # pylint: disable-msg=E1101 + if form.is_valid(): + username = form.cleaned_data['username'] + cherrypy.session[cfg.session_key] = username + cherrypy.request.login = username + self.on_login(username) + raise cherrypy.HTTPRedirect(from_page or + (cfg.server_dir + "/")) else: - cherrypy.session[cfg.session_key] = cherrypy.request.login = username - self.on_login(username) - raise cherrypy.HTTPRedirect(from_page or (cfg.server_dir + "/")) - + form = LoginForm(prefix='auth') + + return util.render_template(template='form', title=_('Login'), + form=form, submit_text=_('Login')) + @cherrypy.expose def logout(self, from_page=cfg.server_dir+"/"): sess = cherrypy.session @@ -46,4 +76,5 @@ class AuthController(PagePlugin): if username: cherrypy.request.login = None self.on_logout(username) + raise cherrypy.HTTPRedirect(from_page or (cfg.server_dir + "/")) diff --git a/modules/installed/lib/forms.py b/modules/installed/lib/forms.py deleted file mode 100644 index 4980efd37..000000000 --- a/modules/installed/lib/forms.py +++ /dev/null @@ -1,151 +0,0 @@ -""" -The Form class is a helper class that takes parameters and method -calls and can return html for a form with appropriate hooks for css -styling. It should allow you to display a form but have the -formatting and styling added by the class. You can worry less about -how it looks while still getting consistent, decent-looking forms. - -Take a look at the FirstBoot class for an example of forms in action. - -Copyright 2011-2013 James Vasile - -This software is released to you (yes, you) under the terms of the GNU -Affero General Public License, version 3 or later, available at -Privacy controls are not yet implemented. This page is a - placeholder and a promise: privacy is important enough that it - is a founding consideration, not an afterthought.
- """ - return self.fill_template(title=_("Privacy Control Panel"), main=main, -sidebar_right=_("""Statement of PrinciplesWhen we say your -privacy is important, it's not just an empty pleasantry. We really -mean it. Your privacy control panel should give you fine-grained -control over exactly who can access your %s and the -information on it.
- -Your personal information should not leave this box without your -knowledge and direction. And if companies or government wants this -information, they have to ask you for it. This gives you a -chance to refuse and also tells you who wants your data.
-""") % cfg.product_name) + return util.render_template(template='privacy_config', + title=_('Privacy Control Panel')) diff --git a/modules/installed/privacy/templates/privacy_config.html b/modules/installed/privacy/templates/privacy_config.html new file mode 100644 index 000000000..cc3becb15 --- /dev/null +++ b/modules/installed/privacy/templates/privacy_config.html @@ -0,0 +1,46 @@ +{% extends "login_nav.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, seePrivacy controls are not yet implemented. This page is a +placeholder and a promise: privacy is important enough that it is a +founding consideration, not an afterthought.
+ +{% endblock %} + +{% block sidebar_right_block %} + + + +{% endblock %} diff --git a/modules/installed/privacy/templates/tor.html b/modules/installed/privacy/templates/tor.html new file mode 100644 index 000000000..85ebe5745 --- /dev/null +++ b/modules/installed/privacy/templates/tor.html @@ -0,0 +1,47 @@ +{% extends "login_nav.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, seeTor is an anonymous communication system. You can learn more about +it from the Tor Project +website. For best protection when web surfing, the Tor Project +recommends that you use +the Tor +Browser Bundle.
+ +A Tor SOCKS port is available on your FreedomBox on TCP port +9050.
+ +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:
+ +| {{ name }} | +{{ port }} | +
Tor is an anonymous communication system. You can learn more about it from the Tor Project website. For best protection when web surfing, the Tor Project recommends that you use the Tor Browser Bundle.
-A Tor SOCKS port is available on your FreedomBox on TCP port 9050.
-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:
- """) - - main += '| " + str(key) + " | " - main += "" + str(ports[key]) + " |
Eventually we will display a bunch of info, graphs and logs about the routing functions here.
+ return util.render_template(title="Router Information", main=""" +Eventually we will display a bunch of info, graphs and logs about +the routing functions here.
""") diff --git a/modules/installed/router/pagekite.py b/modules/installed/router/pagekite.py index 666d1a0fe..799a8860d 100644 --- a/modules/installed/router/pagekite.py +++ b/modules/installed/router/pagekite.py @@ -20,14 +20,14 @@ Plinth module for configuring PageKite service """ import cherrypy +from django import forms +from django.core import validators from gettext import gettext as _ import actions import cfg -from forms import Form from modules.auth import require -from plugin_mount import PagePlugin, FormPlugin -import re +from plugin_mount import PagePlugin import util @@ -39,83 +39,103 @@ class PageKite(PagePlugin): PagePlugin.__init__(self, *args, **kwargs) self.register_page("router.setup.pagekite") - self.register_page("router.setup.pagekite.configure") cfg.html_root.router.setup.menu.add_item( _("Public Visibility (PageKite)"), "icon-flag", "/router/setup/pagekite", 50) + @staticmethod @cherrypy.expose @require() - def index(self, **kwargs): - """Serve introcution page""" + def index(**kwargs): + """Serve introdution page""" del kwargs # Unused - main = _(""" -PageKite is a system for exposing {box_name} services when you -don't have a direct connection to the Internet. You only need this -service if your {box_name} services are unreachable from the rest of -the Internet. This includes the following situations:
+ menu = {'title': _('PageKite'), + 'items': [{'url': '/router/setup/pagekite/configure', + 'text': _('Configure PageKite')}]} + sidebar_right = util.render_template(template='menu_block', menu=menu) -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 {box_name} -for this.
- - -""").format(box_name=cfg.box_name, server_dir=cfg.server_dir) - - sidebar_right = _(''' -PageKite -''').format(server_dir=cfg.server_dir) - - return self.fill_template(title=_("Public Visibility (PageKite)"), - main=main, sidebar_right=sidebar_right) + return util.render_template(template='pagekite_introduction', + title=_("Public Visibility (PageKite)"), + sidebar_right=sidebar_right) -class configure(FormPlugin, PagePlugin): # pylint: disable-msg=C0103 +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 \ +http://mybox1-myacc.pagekite.me \ +')) + + ssh_enabled = forms.BooleanField( + label=_('Secure Shell (SSH)'), required=False, + help_text=_('See SSH client setup instructions')) + + +class Configure(PagePlugin): # pylint: disable-msg=C0103 """Main configuration form""" order = 65 - url = ["/router/setup/pagekite/configure"] + def __init__(self, *args, **kwargs): + PagePlugin.__init__(self, *args, **kwargs) - js = """ - -""" + if kwargs: + form = ConfigureForm(kwargs, prefix='pagekite') + # pylint: disable-msg=E1101 + if form.is_valid(): + self._apply_changes(status, form.cleaned_data, messages) + status = self.get_status() + form = ConfigureForm(initial=status, prefix='pagekite') + else: + form = ConfigureForm(initial=status, prefix='pagekite') + + return util.render_template(template='pagekite_configure', + title=_('Configure PageKite'), form=form, + messages=messages) def get_status(self): """ @@ -144,99 +164,11 @@ $('#pagekite-enable').change(function() { status['service'] = {} for service in ('http', 'ssh'): output = self._run(['get-service-status', service]) - status['service'][service] = (output.split()[0] == 'enabled') + status[service + '_enabled'] = (output.split()[0] == 'enabled') return status - def main(self, *args, **kwargs): - """Build and return the main content area which is the form""" - del args # unused - - status = self.get_status() - - if not status: - return _(''' -PageKite is not installed, please install it. PageKite comes -pre-installed with {box_name}. On any Debian based system (such as -{box_name}) you may install it using the command 'aptitude install -pagekite'
''').format(box_name=cfg.box_name) - - try: - message = kwargs['message'].text - except KeyError: - message = None - form = Form( - title="Configure PageKite", - action=cfg.server_dir + "/router/setup/pagekite/configure/", - name="configure_pagekite_form", message=message) - - form.checkbox(_("Enable PageKite"), name="pagekite_enable", - id="pagekite-enable", checked=status['enabled']) - - show_form = "block" if status['enabled'] else "none" - form.html(''' -wireless setup: essid, etc.
") + def wireless(): + """Serve the wireless page""" + return util.render_template(title="Wireless", + main="wireless setup: essid, etc.
") + @staticmethod @cherrypy.expose @require() - def firewall(self): - return self.fill_template(title="Firewall", main="Iptables twiddling.
") + def firewall(): + """Serve the firewall page""" + return util.render_template(title="Firewall", + main="Iptables twiddling.
") + @staticmethod @cherrypy.expose @require() - def hotspot(self): - return self.fill_template(title="Hotspot and Mesh", main="connection sharing setup.
") + def hotspot(): + """Serve the hotspot page""" + return util.render_template(title="Hotspot and Mesh", + main="connection sharing setup.
") +class WANForm(forms.Form): # pylint: disable-msg=W0232 + """WAN setup form""" + connection_type = forms.ChoiceField( + label=_('Connection Type'), + choices=[('dhcp', _('DHCP')), ('static_ip', _('Static IP'))]) -class setup(PagePlugin): + wan_ip = forms.IPAddressField(label=_('WAN IP Address'), required=False) + + subnet_mask = forms.IPAddressField(label=_('Subnet Mask'), required=False) + + dns_1 = forms.IPAddressField(label=_('Static DNS 1'), required=False) + + dns_2 = forms.IPAddressField(label=_('Static DNS 2'), required=False) + + dns_3 = forms.IPAddressField(label=_('Static DNS 3'), required=False) + + +class Setup(PagePlugin): + """Router setup page""" def __init__(self, *args, **kwargs): - self.register_page("router.setup") - self.menu = cfg.html_root.router.menu.add_item("General Setup", "icon-cog", "/router/setup", 10) - self.menu.add_item("Dynamic DNS", "icon-flag", "/router/setup/ddns", 20) - self.menu.add_item("MAC Address Clone", "icon-barcode", "/router/setup/mac_address", 30) + PagePlugin.__init__(self, args, kwargs) + + self.register_page('router.setup') + + self.menu = cfg.html_root.router.menu.add_item( + 'General Setup', 'icon-cog', '/router/setup', 10) + self.menu.add_item('Dynamic DNS', 'icon-flag', '/router/setup/ddns', + 20) + self.menu.add_item('MAC Address Clone', 'icon-barcode', + '/router/setup/mac_address', 30) @cherrypy.expose @require() - def index(self): - parts = self.forms('/router/setup') - parts['title'] = "General Router Setup" - parts['sidebar_right']="""IntroductionYour %s is a replacement for your -wireless router. By default, it should do everything your usual -router does. With the addition of some extra modules, its abilities -can rival those of high-end routers costing hundreds of dollars.
-""" % cfg.box_name + parts['sidebar_right'] - if not cfg.users.expert(): - parts['main'] += """In basic mode, you don't need to do any - router setup before you can go online. Just plug your - %(product)s in to your cable or DSL modem and the router - will try to get you on the internet using DHCP.
+ def index(self, **kwargs): + """Return the setup page""" + status = self.get_status() -If that fails, you might need to resort to the expert - options. Enable expert mode in the "%(product)s System / - Configure" menu.
""" % {'product':cfg.box_name} + form = None + messages = [] + + if kwargs: + form = WANForm(kwargs, prefix='router') + # pylint: disable-msg=E1101 + if form.is_valid(): + self._apply_changes(status, form.cleaned_data, messages) + status = self.get_status() + form = WANForm(initial=status, prefix='router') else: - parts['main'] += "router name, domain name, router IP, dhcp
" - return self.fill_template(**parts) + form = WANForm(initial=status, prefix='router') + return util.render_template(template='router_setup', + title=_('General Router Setup'), + form=form, messages=messages) + + @staticmethod @cherrypy.expose @require() - def ddns(self): - return self.fill_template(title="Dynamic DNS", main="Masquerade setup
") + def ddns(): + """Return the DDNS page""" + return util.render_template(title="Dynamic DNS", + main="Masquerade setup
") + @staticmethod @cherrypy.expose @require() - def mac_address(self): - return self.fill_template(title="MAC Address Cloning", - main="Your router can pretend to have a different MAC address on any interface.
") + def mac_address(): + """Return the MAC address page""" + return util.render_template( + title="MAC Address Cloning", + main="Your router can pretend to have a different MAC address \ +on any interface.
") + @staticmethod + def get_status(): + """Return the current status""" + store = util.filedict_con(cfg.store_file, 'router') + return {'connection_type': store.get('connection_type', 'dhcp')} -class wan(FormPlugin, PagePlugin): - url = ["/router/setup"] - order = 10 + @staticmethod + def _apply_changes(old_status, new_status, messages): + """Apply the changes""" + print 'Apply changes - %s, %s', old_status, new_status + if old_status['connection_type'] == new_status['connection_type']: + return - js = """ -""" - - def sidebar_right(self, *args, **kwargs): - side='' - if cfg.users.expert(): - side += """WAN Connection Type -DHCP allows your router to automatically - connect with the upstream network. If you are unsure what - option to choose, stick with DHCP. It is usually - correct. - -
If you want to setup your connection - manually, you can enter static IP information. This option is - for those who know what they're doing. As such, it is only - available in expert mode.
""" - return side - - def main(self, wan_ip0=0, wan_ip1=0, wan_ip2=0, wan_ip3=0, - subnet0=0, subnet1=0, subnet2=0, subnet3=0, - gateway0=0, gateway1=0, gateway2=0, gateway3=0, - dns10=0, dns11=0, dns12=0, dns13=0, - dns20=0, dns21=0, dns22=0, dns23=0, - dns30=0, dns31=0, dns32=0, dns33=0, - message=None, **kwargs): - if not cfg.users.expert(): - return '' - - store = filedict_con(cfg.store_file, 'router') - defaults = {'connect_type': 'DHCP'} - for key, value in defaults.items(): - if not key in kwargs: - try: - kwargs[key] = store[key] - except KeyError: - store[key] = kwargs[key] = value - - form = Form(title="WAN Connection", - action=cfg.server_dir + "/router/setup/wan/index", - name="wan_connection_form", - message=message) - form.dropdown('Connection Type', vals=["DHCP", "Static IP"], id="connect_type") - form.html('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'
+ +{% else %} + + {% include 'messages.html' %} + + + +{% endif %} + +{% endblock %} + +{% block js_block %} + {{ js|safe }} + + +{% endblock %} diff --git a/modules/installed/router/templates/pagekite_introduction.html b/modules/installed/router/templates/pagekite_introduction.html new file mode 100644 index 000000000..f6619c9a1 --- /dev/null +++ b/modules/installed/router/templates/pagekite_introduction.html @@ -0,0 +1,56 @@ +{% extends "login_nav.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, seePageKite 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:
+ +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.
+ + + +{% endblock %} diff --git a/modules/installed/router/templates/router_setup.html b/modules/installed/router/templates/router_setup.html new file mode 100644 index 000000000..c484c5585 --- /dev/null +++ b/modules/installed/router/templates/router_setup.html @@ -0,0 +1,117 @@ +{% extends "login_nav.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, seeIn basic mode, you don't need to do any router setup before you + can go online. Just plug your {{ cfg.product_name }} in to your + cable or DSL modem and the router will try to get you on the + internet using DHCP.
+ +If that fails, you might need to resort to the expert options. + Enable expert mode in the "{{ cfg.product_name }} / System / + Configure" menu.
+ +{% endif %} + +{% endblock %} + +{% block sidebar_right_block %} + + + +{% endblock %} + +{% block js_block %} + {{ js|safe }} + + + +{% endblock %} diff --git a/modules/installed/santiago/santiago.py b/modules/installed/santiago/santiago.py index 6d179c50b..b052daab7 100644 --- a/modules/installed/santiago/santiago.py +++ b/modules/installed/santiago/santiago.py @@ -7,10 +7,6 @@ haven't figured that one all the way through yet. import os, sys import cherrypy -try: - import simplejson as json -except ImportError: - import json from gettext import gettext as _ from plugin_mount import PagePlugin from modules.auth import require diff --git a/modules/installed/services/services.py b/modules/installed/services/services.py index 5a7427c2c..0bf5fb698 100644 --- a/modules/installed/services/services.py +++ b/modules/installed/services/services.py @@ -2,6 +2,8 @@ import cherrypy from modules.auth import require from plugin_mount import PagePlugin import cfg +import util + class Services(PagePlugin): order = 9 # order of running init in PagePlugins @@ -18,9 +20,4 @@ class Services(PagePlugin): @cherrypy.expose @require() def openid(self): - return self.fill_template(title="Open ID", main='', sidebar_right=""" -One Login for Every SiteYour %s is also an OpenID -machine. It can generate credentials that allow you to log in to many -websites without the need to remember or enter a separate username and -password at each one.
-""" % cfg.box_name) + return util.render_template(template='openid', title="Open ID") diff --git a/modules/installed/services/templates/openid.html b/modules/installed/services/templates/openid.html new file mode 100644 index 000000000..69d6ab8a6 --- /dev/null +++ b/modules/installed/services/templates/openid.html @@ -0,0 +1,29 @@ +{% extends "login_nav.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, seeOne Login for Every Site
+ +Your {{ cfg.box_name }} is also an OpenID machine. It can generate +credentials that allow you to log in to many websites without the need +to remember or enter a separate username and password at each one.
+ +{% endblock %} diff --git a/modules/installed/services/templates/xmpp_configure.html b/modules/installed/services/templates/xmpp_configure.html new file mode 100644 index 000000000..718d7d353 --- /dev/null +++ b/modules/installed/services/templates/xmpp_configure.html @@ -0,0 +1,36 @@ +{% extends "login_nav.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, seeXMPP Server Accounts and Configuration
" + + sidebar_right = util.render_template(template='menu_block', + menu=SIDE_MENU) + return util.render_template(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')) + + # XXX: Only present due to issue with submitting empty form + dummy = forms.CharField(label='Dummy', initial='dummy', + widget=forms.HiddenInput()) + + +class Configure(PagePlugin): + """Configuration page""" + + def __init__(self, *args, **kwargs): + PagePlugin.__init__(self, *args, **kwargs) + self.register_page("services.xmpp.configure") + @cherrypy.expose @require() def index(self, **kwargs): - main = "XMPP Server Accounts and Configuration
" - sidebar_right = 'Configure XMPP ServerWhen enabled, anyone who can reach this server will be allowed to register an account through an XMPP client.
")) - form.submit(_("Update setup")) - return form.render() + return {'inband_enabled': 'inband_enable' in output.split()} - def process_form(self, **kwargs): - checkedinfo = { - 'inband_enable' : False, - } + @staticmethod + def sidebar_right(**kwargs): + """Return rendered string for sidebar on the right""" + del kwargs # Unused - opts = [] - for k in kwargs.keys(): - if 'on' == kwargs[k]: - shortk = k.split("xmpp_").pop() - checkedinfo[shortk] = True + return util.render_template(template='menu_block', menu=SIDE_MENU) - for key in checkedinfo.keys(): - if checkedinfo[key]: - opts.append(key) - else: - opts.append('no'+key) - actions.run("xmpp-setup", opts) + @staticmethod + def _apply_changes(old_status, new_status, messages): + """Apply the form changes""" + cfg.log.info('Status - %s, %s' % (old_status, new_status)) - main = self.main(checkedinfo['inband_enable']) - return self.fill_template(title="XMPP Server Configuration", main=main, sidebar_left=self.sidebar_left, sidebar_right=self.sidebar_right) + if old_status['inband_enabled'] == new_status['inband_enabled']: + messages.append(('info', _('Setting unchanged'))) + return -class register(FormPlugin, PagePlugin): - url = ["/services/xmpp/register"] + if new_status['inband_enabled']: + messages.append(('success', _('Inband registration enabled'))) + option = 'inband_enable' + else: + messages.append(('success', _('Inband registration disabled'))) + option = 'noinband_enable' - sidebar_left = '' - sidebar_right = _("Register XMPP Account") + cfg.log.info('Option - %s' % option) - def main(self, username='', message=None, *args, **kwargs): - form = Form(title="Register XMPP Account", - action=cfg.server_dir + "/services/xmpp/register/index", - name="register_xmpp_form", - message=message) - form.text_input(_("Username"), name="username", value=username) - form.text_input(_("Password"), name="password", type="password") - form.submit(label=_("Register XMPP Account"), name="register") - return form.render() + _output, error = actions.superuser_run('xmpp-setup', [option]) + del _output + if error: + raise Exception('Error running command - %s' % error) - def process_form(self, username=None, password=None, **kwargs): - msg = Message() - if not username: msg.add = _("Must specify a username!") - if not password: msg.add = _("Must specify a password!") +class RegisterForm(forms.Form): # pylint: disable-msg=W0232 + """Configuration form""" + username = forms.CharField(label=_('Username')) - if username and password: - output, error = actions.superuser_run( - "xmpp-register", [username, password]) - if error: - raise Exception("something is wrong: " + error) + password = forms.CharField( + label=_('Password'), widget=forms.PasswordInput()) - if "successfully registered" in output: - msg.add = _("Registered account for %s." % username) - else: - msg.add = _("Failed to register account for %s: %s" % (username, output)) - cfg.log(msg.text) - main = self.main(username, msg=msg.text) - return self.fill_template( - title="XMPP Server Configuration", - main=main, - sidebar_left=self.sidebar_left, - sidebar_right=self.sidebar_right) +class Register(PagePlugin): + """User registration page""" + + def __init__(self, *args, **kwargs): + PagePlugin.__init__(self, *args, **kwargs) + self.register_page('services.xmpp.register') + + @cherrypy.expose + @require() + def index(self, **kwargs): + """Serve the registration form""" + form = None + messages = [] + + if kwargs: + form = RegisterForm(kwargs, prefix='xmpp') + # pylint: disable-msg=E1101 + if form.is_valid(): + self._register_user(form.cleaned_data, messages) + form = RegisterForm(prefix='xmpp') + else: + form = RegisterForm(prefix='xmpp') + + sidebar_right = util.render_template(template='menu_block', + menu=SIDE_MENU) + return util.render_template(template='xmpp_register', + title=_('Register XMPP Account'), + form=form, messages=messages, + sidebar_right=sidebar_right) + + @staticmethod + def _register_user(data, messages): + """Register a new XMPP user""" + output, error = actions.superuser_run( + 'xmpp-register', [data['username'], data['password']]) + if error: + raise Exception('Error registering user - %s' % error) + + if 'successfully registered' in output: + messages.append(('success', + _('Registered account for %s' % + data['username']))) + else: + messages.append(('error', + _('Failed to register account for %s: %s') % + (data['username'], output))) diff --git a/modules/installed/sharing/file_explorer.py b/modules/installed/sharing/file_explorer.py index ed23b5053..c56cdb504 100644 --- a/modules/installed/sharing/file_explorer.py +++ b/modules/installed/sharing/file_explorer.py @@ -1,7 +1,10 @@ import cherrypy +from gettext import gettext as _ from modules.auth import require from plugin_mount import PagePlugin import cfg +import util + class FileExplorer(PagePlugin): def __init__(self, *args, **kwargs): @@ -12,24 +15,5 @@ class FileExplorer(PagePlugin): @cherrypy.expose @require() def index(self): - main = """ -File explorer for users that also have shell accounts.
Until -that is written (and it will be a while), we should install mollify or ajaxplorer, but -of which seem to have some support for playing media files in the -browser (as opposed to forcing users to download and play them -locally). The downsides to third-party explorers are: they're don't -fit within our theme system, they require separate login, and they're -written in php, which will make integrating them hard.
- -There are, of course, many other options for php-based file -explorers. These were the ones I saw that might do built-in media -players.
- -For python-friendly options, check out FileManager. -It appears to be mostly javascript with some bindings to make it -python-friendly.
-""" - return self.fill_template(title="File Explorer", main=main, sidebar_right='') + return util.render_template(template='file_explorer', + title=_('File Explorer')) diff --git a/modules/installed/sharing/sharing.py b/modules/installed/sharing/sharing.py index 3a0de623b..81e004c20 100644 --- a/modules/installed/sharing/sharing.py +++ b/modules/installed/sharing/sharing.py @@ -3,6 +3,8 @@ from gettext import gettext as _ from modules.auth import require from plugin_mount import PagePlugin import cfg +import util + class Sharing(PagePlugin): order = 9 # order of running init in PagePlugins @@ -24,13 +26,9 @@ class Sharing(PagePlugin): @cherrypy.expose @require() def files(self): - return self.fill_template(title="File Server", main='', sidebar_right=_(""" -Freedom NASThe %s can make your spare hard drives accessible to your -local network, thus acting as a NAS server. We currently support -sharing files via NFS and SMB. + return util.render_template(template='sharing', + title=_('File Server')) -TODO: this is not true. We currently support no sharing.
-""" % cfg.box_name)) #TODO: move PrinterSharing to another file, as it should be an optional module (most people don't care about printer sharing) class PrinterSharing(PagePlugin): @@ -42,12 +40,5 @@ class PrinterSharing(PagePlugin): @cherrypy.expose @require() def index(self): - main = """ -TODO: Setup and install SAMBA
-TODO: Setup and install CUPS
-""" - return self.fill_template(title="Printer Sharing", main=main, sidebar_right=""" -Share Your PrinterThe %s can share your printer via Samba and CUPS.
-""" % cfg.box_name) - - + return util.render_template(template='sharing_printer', + title=_('Printer Sharing')) diff --git a/modules/installed/sharing/templates/file_explorer.html b/modules/installed/sharing/templates/file_explorer.html new file mode 100644 index 000000000..a7f98b232 --- /dev/null +++ b/modules/installed/sharing/templates/file_explorer.html @@ -0,0 +1,42 @@ +{% extends 'login_nav.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, seeFile explorer for users that also have shell accounts.
Until +that is written (and it will be a while), we should +install mollify +or ajaxplorer, +but of which seem to have some support for playing media files in the +browser (as opposed to forcing users to download and play them +locally). The downsides to third-party explorers are: they're don't +fit within our theme system, they require separate login, and they're +written in php, which will make integrating them hard.
+ +There are, of course, many other options for php-based file +explorers. These were the ones I saw that might do built-in media +players.
+ +For python-friendly options, check out FileManager. +It appears to be mostly javascript with some bindings to make it +python-friendly.
+ +{% endblock %} diff --git a/modules/installed/sharing/templates/sharing.html b/modules/installed/sharing/templates/sharing.html new file mode 100644 index 000000000..020c3edfe --- /dev/null +++ b/modules/installed/sharing/templates/sharing.html @@ -0,0 +1,33 @@ +{% extends "login_nav.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, seeTODO: Setup and install SAMBA
+TODO: Setup and install CUPS
+ +{% endblock %} + +{% block sidebar_right_block %} + + + +{% endblock %} diff --git a/modules/installed/system/config.py b/modules/installed/system/config.py index 6e1f62e2a..808681f2e 100644 --- a/modules/installed/system/config.py +++ b/modules/installed/system/config.py @@ -20,68 +20,136 @@ Plinth module for configuring timezone, hostname etc. """ import cherrypy +from django import forms +from django.core import validators from gettext import gettext as _ -try: - import simplejson as json -except ImportError: - import json -import os +import re import socket import actions import cfg -from forms import Form from modules.auth import require -from plugin_mount import PagePlugin, FormPlugin +from plugin_mount import PagePlugin import util -class Config(PagePlugin): +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 + + +class Configuration(PagePlugin): """System configuration page""" def __init__(self, *args, **kwargs): del args # Unused del kwargs # Unused - self.register_page("sys.config") + self.register_page('sys.config') + + self.menu = cfg.html_root.sys.menu.add_item(_('Configure'), 'icon-cog', + '/sys/config', 10) @cherrypy.expose @require() - def index(self): - """Serve configuration page""" - parts = self.forms('/sys/config') - parts['title'] = _("Configure this {box_name}") \ - .format(box_name=cfg.box_name) + def index(self, **kwargs): + """Serve the configuration form""" + status = self.get_status() - return self.fill_template(**parts) # pylint: disable-msg=W0142 + form = None + messages = [] + if kwargs and cfg.users.expert(): + form = ConfigurationForm(kwargs, prefix='configuration') + # pylint: disable-msg=E1101 + if form.is_valid(): + self._apply_changes(status, form.cleaned_data, messages) + status = self.get_status() + form = ConfigurationForm(initial=status, + prefix='configuration') + else: + form = ConfigurationForm(initial=status, prefix='configuration') -def valid_hostname(name): - """ - Return '' if name is a valid hostname by our standards (not just - by RFC 952 and RFC 1123. We're more conservative than the - standard. If hostname isn't valid, return message explaining why. - """ - message = '' - if len(name) > 63: - message += "Set your timezone to get accurate timestamps. {product} will use -this information to set your {box}'s systemwide timezone.
''').format( - product=cfg.product_name, box=cfg.box_name) - - def main(self, message='', time_zone=None, **kwargs): - """Build and return the main content area which is the form""" - del kwargs # Unused - - if not cfg.users.expert(): - return _(''' -Only members of the expert group are allowed to see and modify the system -setup.
''') - - if not time_zone: - time_zone = get_time_zone() - - # Get the list of supported timezones and the index in that - # list of the current one - module_file = __file__ - if module_file.endswith(".pyc"): - module_file = module_file[:-1] - module_dir = os.path.dirname(os.path.realpath(module_file)) - time_zones_file = os.path.join(module_dir, 'time_zones') - time_zones = json.loads(util.slurp(time_zones_file)) - try: - time_zone_id = time_zones.index(time_zone) - except ValueError: - cfg.log.critical("Unknown Time Zone: %s" % time_zone) - raise cherrypy.HTTPError(500, "Unknown Time Zone: %s" % time_zone) - - # And now, the form. - form = Form(title=_("General Config"), - action=cfg.server_dir + "/sys/config/general/index", - name="config_general_form", - message=message) - form.html(self.help()) - form.dropdown(_("Time Zone"), name="time_zone", vals=time_zones, - select=time_zone_id) - form.html(''' -Your hostname is the local name by which other machines on your LAN -can reach you.
''') - form.text_input('Hostname', name='hostname', value=get_hostname()) - form.submit(_("Submit")) - - return form.render() - - @staticmethod - def process_form(time_zone='', hostname='', *args, **kwargs): - """Handle form submission""" - del args # Unused - del kwargs # Unused - - message = '' - if hostname != get_hostname(): - msg = valid_hostname(hostname) - if msg == '': - set_hostname(hostname) - else: - message += msg - - time_zone = time_zone.strip() - if time_zone != get_time_zone(): - cfg.log.info("Setting timezone to %s" % time_zone) - actions.superuser_run("timezone-change", [time_zone]) - - return message or "Settings updated." diff --git a/modules/installed/system/diagnostics.py b/modules/installed/system/diagnostics.py index b87afb68d..db05738a2 100644 --- a/modules/installed/system/diagnostics.py +++ b/modules/installed/system/diagnostics.py @@ -19,12 +19,14 @@ Plinth module for running diagnostics """ -import os, cherrypy +import cherrypy from gettext import gettext as _ from auth import require from plugin_mount import PagePlugin import actions import cfg +import util + class diagnostics(PagePlugin): order = 30 @@ -36,13 +38,8 @@ class diagnostics(PagePlugin): @cherrypy.expose @require() def index(self): - main = _(""" -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.
- """) - main += '' - return self.fill_template(title=_("System Diagnostics"), main=main) + return util.render_template(template='diagnostics', + title=_('System Diagnostics')) class test(PagePlugin): order = 31 @@ -53,17 +50,8 @@ class test(PagePlugin): @cherrypy.expose @require() def index(self): - main = '' output, error = actions.superuser_run("diagnostic-test") - - if error: - main += _("The diagnostic test encountered an error:") - for line in error.split('\n'): - main += line + "" - - if output: - main += _("Output of diagnostic test:") - for line in output.split('\n'): - main += line + "" - - return self.fill_template(title=_("Diagnostic Test"), main=main) + return util.render_template(template='diagnostics_test', + title=_('Diagnostic Test'), + diagnostics_output=output, + diagnostics_error=error) diff --git a/modules/installed/system/expert_mode.py b/modules/installed/system/expert_mode.py index dd6f11b49..041ce0793 100644 --- a/modules/installed/system/expert_mode.py +++ b/modules/installed/system/expert_mode.py @@ -1,73 +1,79 @@ -import os import cherrypy -try: - import simplejson as json -except ImportError: - import json +from django import forms from gettext import gettext as _ -from filedict import FileDict from modules.auth import require -from plugin_mount import PagePlugin, FormPlugin +from plugin_mount import PagePlugin import cfg -from forms import Form -from model import User -from util import * +import util -class experts(FormPlugin, PagePlugin): - url = ["/sys/config"] - order = 10 - def help(self, *args, **kwargs): - side = _(#"""Expert Mode - """ -The %(box)s 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.
+class ExpertsForm(forms.Form): # pylint: disable-msg=W0232 + """Form to configure expert mode""" -Most users can operate the %(box)s by configuring the - limited number of options visible in Basic mode. For the sake - of simplicity and ease of use, we hid most of %(product)s's - less frequently used options. But if you want more - sophisticated features, you can enable Expert mode, and - %(product)s will present more advanced menu options.
+ expert_mode = forms.BooleanField( + label=_('Expert Mode'), required=False) -You should be aware that it might be possible to render - your %(box)s inaccessible via Expert mode options.
- """ % {'box':cfg.box_name, 'product':cfg.product_name}) + # XXX: Only present due to issue with submitting empty form + dummy = forms.CharField(label='Dummy', initial='dummy', + widget=forms.HiddenInput()) - return side - def main(self, expert=None, message='', **kwargs): - """Note that kwargs contains '':"submit" if this is coming - from a submitted form. If kwargs is empty, it's a fresh form - with no user input, which means it should just reflect the - state of the stored data.""" - if not kwargs and expert == None: - expert = cfg.users.expert() - cfg.log("Expert mode is %s" % expert) - form = Form(title=_("Expert Mode"), - action=cfg.server_dir + "/sys/config/experts", - name="expert_mode_form", - message=message ) - form.html(self.help()) - form.checkbox(_("Expert Mode"), name="expert", checked=expert) - form.submit(_("Submit")) - return form.render() +class Experts(PagePlugin): + """Expert forms page""" + order = 60 - def process_form(self, expert='', *args, **kwargs): - user = cfg.users.get() + def __init__(self, *args, **kwargs): + PagePlugin.__init__(self, *args, **kwargs) + self.register_page('sys.config.expert') - message = 'settings unchanged' + cfg.html_root.sys.config.menu.add_item(_('Expert mode'), 'icon-cog', + '/sys/config/expert', 10) - if expert: + @cherrypy.expose + @require() + def index(self, **kwargs): + """Serve the configuration form""" + status = self.get_status() + + cfg.log.info('Args - %s' % kwargs) + + form = None + messages = [] + + if kwargs: + form = ExpertsForm(kwargs, prefix='experts') + # pylint: disable-msg=E1101 + if form.is_valid(): + self._apply_changes(form.cleaned_data, messages) + status = self.get_status() + form = ExpertsForm(initial=status, prefix='experts') + else: + form = ExpertsForm(initial=status, prefix='experts') + + return util.render_template(template='expert_mode', + title=_('Expert Mode'), form=form, + messages=messages) + + @staticmethod + def get_status(): + """Return the current status""" + return {'expert_mode': cfg.users.expert()} + + @staticmethod + def _apply_changes(new_status, messages): + """Apply expert mode configuration""" + message = ('info', _('Settings unchanged')) + + user = cfg.users.current() + + if new_status['expert_mode']: if not 'expert' in user['groups']: user['groups'].append('expert') - message = "enabled" + message = ('success', _('Expert mode enabled')) else: if 'expert' in user['groups']: user['groups'].remove('expert') - message = "disabled" + message = ('success', _('Expert mode disabled')) - cfg.users.set(user) - return "Expert mode %s." % message + cfg.users.set(user['username'], user) + messages.append(message) diff --git a/modules/installed/system/firewall.py b/modules/installed/system/firewall.py index 069dfb658..e736627f1 100644 --- a/modules/installed/system/firewall.py +++ b/modules/installed/system/firewall.py @@ -27,6 +27,7 @@ import cfg from modules.auth import require from plugin_mount import PagePlugin import service as service_module +import util class Firewall(PagePlugin): @@ -48,89 +49,24 @@ class Firewall(PagePlugin): """Serve introcution page""" del kwargs # Unused - # XXX: Use templates here instead of generating HTML - main = _(''' -Firewall is a network security system that controls the incoming -and outgoing network traffic on your {box_name}. Keeping a firewall -enabled and properly configured reduces risk of security threat from -the Internet.
- -The following the current status:
-''').format(box_name=cfg.box_name) - if not self.get_installed_status(): - status = _(''' -Firewall is not installed. Please install it. Firewall comes -pre-installed with {box_name}. On any Debian based system (such as -{box_name}) you may install it using the command 'aptitude install -firewalld'
''').format(box_name=cfg.box_name) - - return self.fill_template(title=_("Firewall"), main=main + status) + return util.render_template(template='firewall', + title=_("Firewall"), + firewall_status='not_installed') if not self.get_enabled_status(): - status = _(''' -Firewall daemon is not running. Please run it. Firewall comes -enabled by default on {box_name}. On any Debian based system (such as -{box_name}) you may run it using the command 'service firewalld start' -or in case of system with systemd 'systemctl start firewalld'
-''').format(box_name=cfg.box_name) + return util.render_template(template='firewall', + title=_("Firewall"), + firewall_status='not_running') - return self.fill_template(title=_("Firewall"), main=main + status) + internal_enabled_services = self.get_enabled_services(zone='internal') + external_enabled_services = self.get_enabled_services(zone='external') - internal_enabled_sevices = self.get_enabled_services(zone='internal') - external_enabled_sevices = self.get_enabled_services(zone='external') - - services_info = '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.
''' - - return self.fill_template(title=_("Firewall"), main=main + - services_info + footnote) + return util.render_template( + template='firewall', title=_('Firewall'), + services=service_module.SERVICES.values(), + internal_enabled_services=internal_enabled_services, + external_enabled_services=external_enabled_services) def get_installed_status(self): """Return whether firewall is installed""" diff --git a/modules/installed/system/packages.py b/modules/installed/system/packages.py index 276939358..63df8cab0 100644 --- a/modules/installed/system/packages.py +++ b/modules/installed/system/packages.py @@ -1,83 +1,133 @@ import cherrypy +from django import forms from gettext import gettext as _ from auth import require -from plugin_mount import PagePlugin, FormPlugin -from forms import Form +from plugin_mount import PagePlugin import actions import cfg -from util import Message +import util -class Packages(PagePlugin, FormPlugin): + +def get_modules_available(): + """Return list of all modules""" + output, error = actions.run('module-manager', ['list-available']) + if error: + raise Exception('Error getting modules: %s' % error) + + return output.split() + + +def get_modules_enabled(): + """Return list of all modules""" + output, error = actions.run('module-manager', ['list-enabled']) + if error: + raise Exception('Error getting enabled modules - %s' % error) + + return output.split() + + +class PackagesForm(forms.Form): + """Packages form""" + # XXX: Only present due to issue with submitting empty form + dummy = forms.CharField(label='Dummy', initial='dummy', + widget=forms.HiddenInput()) + + 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) + + +class Packages(PagePlugin): + """Package page""" order = 20 def __init__(self, *args, **kwargs): PagePlugin.__init__(self, *args, **kwargs) - self.register_page("sys.packages") - cfg.html_root.sys.menu.add_item("Package Manager", "icon-gift", "/sys/packages", 20) + self.register_page('sys.packages') + + cfg.html_root.sys.menu.add_item('Package Manager', 'icon-gift', + '/sys/packages', 20) @cherrypy.expose @require() def index(self, *args, **kwargs): - output, error = actions.run("module-manager", ["list-available"]) - if error: - raise Exception("something is wrong: " + error) - modules_available = output.split() - - output, error = actions.run("module-manager", \ - ["list-enabled", cfg.python_root]) - if error: - raise Exception("something is wrong: " + error) - modules_enabled = output.split() + """Serve the form""" + del args # Unused - if 'submitted' in kwargs: - del kwargs['submitted'] - modules_selected = map(lambda x: x.split("_")[0], kwargs.keys()) - for module in modules_available: - if module in modules_enabled: - if module not in modules_selected: - output, error = actions.superuser_run(\ - "module-manager",\ - ["disable", cfg.python_root, module]) - # TODO: need a smoother way for plinth - # to unload the module + status = self.get_status() + + form = None + messages = [] + + if kwargs: + form = PackagesForm(kwargs, prefix='packages') + # pylint: disable-msg=E1101 + if form.is_valid(): + self._apply_changes(status, form.cleaned_data, messages) + status = self.get_status() + form = PackagesForm(initial=status, prefix='packages') + else: + form = PackagesForm(initial=status, prefix='packages') + + return util.render_template(template='packages', + title=_('Add/Remove Plugins'), + form=form, messages=messages) + + @staticmethod + 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} + + @staticmethod + def _apply_changes(old_status, new_status, messages): + """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: + output, error = actions.superuser_run( + 'module-manager', ['enable', cfg.python_root, module]) + del output # Unused + + # TODO: need to get plinth to load the module we just + # enabled + if error: + messages.append( + ('error', _('Error enabling module - {module}').format( + module=module))) else: - if module in modules_selected: - output, error = actions.superuser_run(\ - "module-manager",\ - ["enable", cfg.python_root, module]) - # TODO: need to get plinth to load - # the module we just enabled + messages.append( + ('success', _('Module enabled - {module}').format( + module=module))) + else: + output, error = actions.superuser_run( + 'module-manager', ['disable', cfg.python_root, module]) + del output # Unused - main = _(""" -aptitude purge modules
-aptitude install modules
-The modules should depend on the appropriate Debian packages.
""") - main += self.form(self, Message(output), args, kwargs) - sidebar_right = _(""" -Help -On this page, you can add or remove %s plugins to your %s.
-Plugins are just Debian packages, so Debian's usual package management features should make this job fairly easy.
""" % (cfg.product_name, cfg.box_name)) - return self.fill_template(title=_("Add/Remove Plugins"), main=main, sidebar_right=sidebar_right) - - def form(self, message=None, *args, **kwargs): - output, error = actions.run("module-manager", ["list-available"]) - if error: - raise Exception("something is wrong: " + error) - modules_available = output.split() - - output, error = actions.run("module-manager",\ - ["list-enabled", cfg.python_root]) - if error: - raise Exception("something is wrong: " + error) - modules_enabled = output.split() - - form = Form(title="Manage Plugins", - action=cfg.server_dir + "/sys/packages/index", - name="manage_modules", - message=message) - for module in modules_available: - form.checkbox(_("Enable %s" % module), name="%s_enable" % module, id="%s_enable" % module, checked = True if module in modules_enabled else False) - form.hidden(name="submitted", value="True") - form.html(_("""Enabling a plugin will cause a corresponding page to appear in Plinth.
""")) - form.submit(_("Update setup")) - return form.render() + # TODO: need a smoother way for plinth to unload the + # module + if error: + messages.append( + ('error', + _('Error disabling module - {module}').format( + module=module))) + else: + messages.append( + ('success', _('Module disabled - {module}').format( + module=module))) diff --git a/modules/installed/system/system.py b/modules/installed/system/system.py index 906a5b3ca..cfdf92515 100644 --- a/modules/installed/system/system.py +++ b/modules/installed/system/system.py @@ -1,17 +1,8 @@ -import os import cherrypy -try: - import simplejson as json -except ImportError: - import json from gettext import gettext as _ -from filedict import FileDict -from auth import require -from plugin_mount import PagePlugin, FormPlugin +from plugin_mount import PagePlugin import cfg -from forms import Form -from model import User -from util import * +import util sys_dir = "modules/installed/sys" @@ -22,15 +13,9 @@ class Sys(PagePlugin): PagePlugin.__init__(self, *args, **kwargs) self.register_page("sys") self.menu = cfg.main_menu.add_item(_("System"), "icon-cog", "/sys", 100) - self.menu.add_item(_("Configure"), "icon-cog", "/sys/config", 10) self.menu.add_item(_("Users and Groups"), "icon-user", "/sys/users", 15) @cherrypy.expose def index(self): - return self.fill_template(title=_("System Configuration"), main=_(""" -In this section, you can control the %(product)s's - underlying system, as opposed to its various applications and - services. These options affect the %(product)s at its most - general level. This is where you add/remove users, install - applications, reboot, etc.
- """ % {'product':cfg.product_name})) + return util.render_template(template='system', + title=_("System Configuration")) diff --git a/modules/installed/system/templates/config.html b/modules/installed/system/templates/config.html new file mode 100644 index 000000000..5e5310481 --- /dev/null +++ b/modules/installed/system/templates/config.html @@ -0,0 +1,45 @@ +{% extends "login_nav.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, seeOnly members of the expert group are allowed to see and modify + the system setup.
+ +{% endif %} + +{% endblock %} diff --git a/modules/installed/system/templates/diagnostics.html b/modules/installed/system/templates/diagnostics.html new file mode 100644 index 000000000..afb597e34 --- /dev/null +++ b/modules/installed/system/templates/diagnostics.html @@ -0,0 +1,31 @@ +{% extends 'login_nav.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, seeThe 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.
+ + + +{% endblock %} diff --git a/modules/installed/system/templates/diagnostics_test.html b/modules/installed/system/templates/diagnostics_test.html new file mode 100644 index 000000000..93012ab24 --- /dev/null +++ b/modules/installed/system/templates/diagnostics_test.html @@ -0,0 +1,33 @@ +{% extends 'login_nav.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, seeThe diagnostic test encountered an error:
+
{{ diagnostics_error }}
+{% endif %}
+
+{% if diagnostics_output %}
+ Output of diagnostic test:
+{{ diagnostics_output }}
+{% endif %}
+
+{% endblock %}
diff --git a/modules/installed/system/templates/expert_mode.html b/modules/installed/system/templates/expert_mode.html
new file mode 100644
index 000000000..c6df98b36
--- /dev/null
+++ b/modules/installed/system/templates/expert_mode.html
@@ -0,0 +1,51 @@
+{% extends "login_nav.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 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.
+ +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.
+ +You should be aware that it might be possible to render your + {{ cfg.box_name }} inaccessible via Expert mode options.
+ + + +{% endblock %} diff --git a/modules/installed/system/templates/firewall.html b/modules/installed/system/templates/firewall.html new file mode 100644 index 000000000..19c165a46 --- /dev/null +++ b/modules/installed/system/templates/firewall.html @@ -0,0 +1,94 @@ +{% extends "login_nav.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, seeFirewall 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.
+ +The following the current status:
+ +{% if firewall_status = 'not_installed' %} +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'
+ +{% elif firewall_status = 'not_running' %} + +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'
+ +{% else %} + +| Service/Port | +Status | + + + + {% for service in services %} +
|---|---|
| {{ service.name }} | ++ {% if service.is_enabled %} + Enabled + {% else %} + Disabled + {% endif %} + | +
| {{ port }} | ++ {% if port in internal_enabled_services and port in external_enabled_services %} + Permitted + {% elif port in internal_enabled_services %} + Permitted (internal only) + {% elif port in external_enabled_services %} + Permitted (external only) + {% else %} + Blocked + {% endif %} + | +
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.
+ +{% endif %} + +{% endblock %} diff --git a/modules/installed/system/templates/packages.html b/modules/installed/system/templates/packages.html new file mode 100644 index 000000000..d8d7d6164 --- /dev/null +++ b/modules/installed/system/templates/packages.html @@ -0,0 +1,63 @@ +{% extends "login_nav.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, seeaptitude purge modules
+ +aptitude install modules
+ +The modules should depend on the appropriate Debian packages.
+ +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.
+ +{% endblock %} diff --git a/modules/installed/system/templates/users_add.html b/modules/installed/system/templates/users_add.html new file mode 100644 index 000000000..4afbc68c9 --- /dev/null +++ b/modules/installed/system/templates/users_add.html @@ -0,0 +1,52 @@ +{% extends "login_nav.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, seeFor security reasons, neither WAN Administration nor WAN SSH is + available to the `admin` user account.
+ +TODO: in expert mode, tell user they can ssh in to enable admin + from WAN, do their business, then disable it. It would be good to + enable the option and autodisable it when the ssh connection + dies.
+ + + +{% else %} + +This page is available only in expert mode.
+ +{% endif %} + +{% endblock %} diff --git a/modules/installed/system/time_zones b/modules/installed/system/time_zones deleted file mode 100644 index 58c8b7ad3..000000000 --- a/modules/installed/system/time_zones +++ /dev/null @@ -1,572 +0,0 @@ -[ - "Africa/Abidjan", - "Africa/Accra", - "Africa/Addis_Ababa", - "Africa/Algiers", - "Africa/Asmara", - "Africa/Asmera", - "Africa/Bamako", - "Africa/Bangui", - "Africa/Banjul", - "Africa/Bissau", - "Africa/Blantyre", - "Africa/Brazzaville", - "Africa/Bujumbura", - "Africa/Cairo", - "Africa/Casablanca", - "Africa/Ceuta", - "Africa/Conakry", - "Africa/Dakar", - "Africa/Dar_es_Salaam", - "Africa/Djibouti", - "Africa/Douala", - "Africa/El_Aaiun", - "Africa/Freetown", - "Africa/Gaborone", - "Africa/Harare", - "Africa/Johannesburg", - "Africa/Kampala", - "Africa/Khartoum", - "Africa/Kigali", - "Africa/Kinshasa", - "Africa/Lagos", - "Africa/Libreville", - "Africa/Lome", - "Africa/Luanda", - "Africa/Lubumbashi", - "Africa/Lusaka", - "Africa/Malabo", - "Africa/Maputo", - "Africa/Maseru", - "Africa/Mbabane", - "Africa/Mogadishu", - "Africa/Monrovia", - "Africa/Nairobi", - "Africa/Ndjamena", - "Africa/Niamey", - "Africa/Nouakchott", - "Africa/Ouagadougou", - "Africa/Porto-Novo", - "Africa/Sao_Tome", - "Africa/Timbuktu", - "Africa/Tripoli", - "Africa/Tunis", - "Africa/Windhoek", - "America/Adak", - "America/Anchorage", - "America/Anguilla", - "America/Antigua", - "America/Araguaina", - "America/Argentina/Buenos_Aires", - "America/Argentina/Catamarca", - "America/Argentina/ComodRivadavia", - "America/Argentina/Cordoba", - "America/Argentina/Jujuy", - "America/Argentina/La_Rioja", - "America/Argentina/Mendoza", - "America/Argentina/Rio_Gallegos", - "America/Argentina/Salta", - "America/Argentina/San_Juan", - "America/Argentina/San_Luis", - "America/Argentina/Tucuman", - "America/Argentina/Ushuaia", - "America/Aruba", - "America/Asuncion", - "America/Atikokan", - "America/Atka", - "America/Bahia", - "America/Bahia_Banderas", - "America/Barbados", - "America/Belem", - "America/Belize", - "America/Blanc-Sablon", - "America/Boa_Vista", - "America/Bogota", - "America/Boise", - "America/Buenos_Aires", - "America/Cambridge_Bay", - "America/Campo_Grande", - "America/Cancun", - "America/Caracas", - "America/Catamarca", - "America/Cayenne", - "America/Cayman", - "America/Chicago", - "America/Chihuahua", - "America/Coral_Harbour", - "America/Cordoba", - "America/Costa_Rica", - "America/Cuiaba", - "America/Curacao", - "America/Danmarkshavn", - "America/Dawson", - "America/Dawson_Creek", - "America/Denver", - "America/Detroit", - "America/Dominica", - "America/Edmonton", - "America/Eirunepe", - "America/El_Salvador", - "America/Ensenada", - "America/Fort_Wayne", - "America/Fortaleza", - "America/Glace_Bay", - "America/Godthab", - "America/Goose_Bay", - "America/Grand_Turk", - "America/Grenada", - "America/Guadeloupe", - "America/Guatemala", - "America/Guayaquil", - "America/Guyana", - "America/Halifax", - "America/Havana", - "America/Hermosillo", - "America/Indiana/Indianapolis", - "America/Indiana/Knox", - "America/Indiana/Marengo", - "America/Indiana/Petersburg", - "America/Indiana/Tell_City", - "America/Indiana/Vevay", - "America/Indiana/Vincennes", - "America/Indiana/Winamac", - "America/Indianapolis", - "America/Inuvik", - "America/Iqaluit", - "America/Jamaica", - "America/Jujuy", - "America/Juneau", - "America/Kentucky/Louisville", - "America/Kentucky/Monticello", - "America/Knox_IN", - "America/La_Paz", - "America/Lima", - "America/Los_Angeles", - "America/Louisville", - "America/Maceio", - "America/Managua", - "America/Manaus", - "America/Marigot", - "America/Martinique", - "America/Matamoros", - "America/Mazatlan", - "America/Mendoza", - "America/Menominee", - "America/Merida", - "America/Mexico_City", - "America/Miquelon", - "America/Moncton", - "America/Monterrey", - "America/Montevideo", - "America/Montreal", - "America/Montserrat", - "America/Nassau", - "America/New_York", - "America/Nipigon", - "America/Nome", - "America/Noronha", - "America/North_Dakota/Center", - "America/North_Dakota/New_Salem", - "America/Ojinaga", - "America/Panama", - "America/Pangnirtung", - "America/Paramaribo", - "America/Phoenix", - "America/Port-au-Prince", - "America/Port_of_Spain", - "America/Porto_Acre", - "America/Porto_Velho", - "America/Puerto_Rico", - "America/Rainy_River", - "America/Rankin_Inlet", - "America/Recife", - "America/Regina", - "America/Resolute", - "America/Rio_Branco", - "America/Rosario", - "America/Santa_Isabel", - "America/Santarem", - "America/Santiago", - "America/Santo_Domingo", - "America/Sao_Paulo", - "America/Scoresbysund", - "America/Shiprock", - "America/St_Barthelemy", - "America/St_Johns", - "America/St_Kitts", - "America/St_Lucia", - "America/St_Thomas", - "America/St_Vincent", - "America/Swift_Current", - "America/Tegucigalpa", - "America/Thule", - "America/Thunder_Bay", - "America/Tijuana", - "America/Toronto", - "America/Tortola", - "America/Vancouver", - "America/Virgin", - "America/Whitehorse", - "America/Winnipeg", - "America/Yakutat", - "America/Yellowknife", - "Antarctica/Casey", - "Antarctica/Davis", - "Antarctica/DumontDUrville", - "Antarctica/Macquarie", - "Antarctica/Mawson", - "Antarctica/McMurdo", - "Antarctica/Palmer", - "Antarctica/Rothera", - "Antarctica/South_Pole", - "Antarctica/Syowa", - "Antarctica/Vostok", - "Arctic/Longyearbyen", - "Asia/Aden", - "Asia/Almaty", - "Asia/Amman", - "Asia/Anadyr", - "Asia/Aqtau", - "Asia/Aqtobe", - "Asia/Ashgabat", - "Asia/Ashkhabad", - "Asia/Baghdad", - "Asia/Bahrain", - "Asia/Baku", - "Asia/Bangkok", - "Asia/Beirut", - "Asia/Bishkek", - "Asia/Brunei", - "Asia/Calcutta", - "Asia/Choibalsan", - "Asia/Chongqing", - "Asia/Chungking", - "Asia/Colombo", - "Asia/Dacca", - "Asia/Damascus", - "Asia/Dhaka", - "Asia/Dili", - "Asia/Dubai", - "Asia/Dushanbe", - "Asia/Gaza", - "Asia/Harbin", - "Asia/Ho_Chi_Minh", - "Asia/Hong_Kong", - "Asia/Hovd", - "Asia/Irkutsk", - "Asia/Istanbul", - "Asia/Jakarta", - "Asia/Jayapura", - "Asia/Jerusalem", - "Asia/Kabul", - "Asia/Kamchatka", - "Asia/Karachi", - "Asia/Kashgar", - "Asia/Kathmandu", - "Asia/Katmandu", - "Asia/Kolkata", - "Asia/Krasnoyarsk", - "Asia/Kuala_Lumpur", - "Asia/Kuching", - "Asia/Kuwait", - "Asia/Macao", - "Asia/Macau", - "Asia/Magadan", - "Asia/Makassar", - "Asia/Manila", - "Asia/Muscat", - "Asia/Nicosia", - "Asia/Novokuznetsk", - "Asia/Novosibirsk", - "Asia/Omsk", - "Asia/Oral", - "Asia/Phnom_Penh", - "Asia/Pontianak", - "Asia/Pyongyang", - "Asia/Qatar", - "Asia/Qyzylorda", - "Asia/Rangoon", - "Asia/Riyadh", - "Asia/Riyadh87", - "Asia/Riyadh88", - "Asia/Riyadh89", - "Asia/Saigon", - "Asia/Sakhalin", - "Asia/Samarkand", - "Asia/Seoul", - "Asia/Shanghai", - "Asia/Singapore", - "Asia/Taipei", - "Asia/Tashkent", - "Asia/Tbilisi", - "Asia/Tehran", - "Asia/Tel_Aviv", - "Asia/Thimbu", - "Asia/Thimphu", - "Asia/Tokyo", - "Asia/Ujung_Pandang", - "Asia/Ulaanbaatar", - "Asia/Ulan_Bator", - "Asia/Urumqi", - "Asia/Vientiane", - "Asia/Vladivostok", - "Asia/Yakutsk", - "Asia/Yekaterinburg", - "Asia/Yerevan", - "Atlantic/Azores", - "Atlantic/Bermuda", - "Atlantic/Canary", - "Atlantic/Cape_Verde", - "Atlantic/Faeroe", - "Atlantic/Faroe", - "Atlantic/Jan_Mayen", - "Atlantic/Madeira", - "Atlantic/Reykjavik", - "Atlantic/South_Georgia", - "Atlantic/St_Helena", - "Atlantic/Stanley", - "Australia/ACT", - "Australia/Adelaide", - "Australia/Brisbane", - "Australia/Broken_Hill", - "Australia/Canberra", - "Australia/Currie", - "Australia/Darwin", - "Australia/Eucla", - "Australia/Hobart", - "Australia/LHI", - "Australia/Lindeman", - "Australia/Lord_Howe", - "Australia/Melbourne", - "Australia/NSW", - "Australia/North", - "Australia/Perth", - "Australia/Queensland", - "Australia/South", - "Australia/Sydney", - "Australia/Tasmania", - "Australia/Victoria", - "Australia/West", - "Australia/Yancowinna", - "Brazil/Acre", - "Brazil/DeNoronha", - "Brazil/East", - "Brazil/West", - "CET", - "CST6CDT", - "Canada/Atlantic", - "Canada/Central", - "Canada/East-Saskatchewan", - "Canada/Eastern", - "Canada/Mountain", - "Canada/Newfoundland", - "Canada/Pacific", - "Canada/Saskatchewan", - "Canada/Yukon", - "Chile/Continental", - "Chile/EasterIsland", - "Cuba", - "EET", - "EST", - "EST5EDT", - "Egypt", - "Eire", - "Etc/GMT", - "Etc/GMT+0", - "Etc/GMT+1", - "Etc/GMT+10", - "Etc/GMT+11", - "Etc/GMT+12", - "Etc/GMT+2", - "Etc/GMT+3", - "Etc/GMT+4", - "Etc/GMT+5", - "Etc/GMT+6", - "Etc/GMT+7", - "Etc/GMT+8", - "Etc/GMT+9", - "Etc/GMT-0", - "Etc/GMT-1", - "Etc/GMT-10", - "Etc/GMT-11", - "Etc/GMT-12", - "Etc/GMT-13", - "Etc/GMT-14", - "Etc/GMT-2", - "Etc/GMT-3", - "Etc/GMT-4", - "Etc/GMT-5", - "Etc/GMT-6", - "Etc/GMT-7", - "Etc/GMT-8", - "Etc/GMT-9", - "Etc/GMT0", - "Etc/Greenwich", - "Etc/UCT", - "Etc/UTC", - "Etc/Universal", - "Etc/Zulu", - "Europe/Amsterdam", - "Europe/Andorra", - "Europe/Athens", - "Europe/Belfast", - "Europe/Belgrade", - "Europe/Berlin", - "Europe/Bratislava", - "Europe/Brussels", - "Europe/Bucharest", - "Europe/Budapest", - "Europe/Chisinau", - "Europe/Copenhagen", - "Europe/Dublin", - "Europe/Gibraltar", - "Europe/Guernsey", - "Europe/Helsinki", - "Europe/Isle_of_Man", - "Europe/Istanbul", - "Europe/Jersey", - "Europe/Kaliningrad", - "Europe/Kiev", - "Europe/Lisbon", - "Europe/Ljubljana", - "Europe/London", - "Europe/Luxembourg", - "Europe/Madrid", - "Europe/Malta", - "Europe/Mariehamn", - "Europe/Minsk", - "Europe/Monaco", - "Europe/Moscow", - "Europe/Nicosia", - "Europe/Oslo", - "Europe/Paris", - "Europe/Podgorica", - "Europe/Prague", - "Europe/Riga", - "Europe/Rome", - "Europe/Samara", - "Europe/San_Marino", - "Europe/Sarajevo", - "Europe/Simferopol", - "Europe/Skopje", - "Europe/Sofia", - "Europe/Stockholm", - "Europe/Tallinn", - "Europe/Tirane", - "Europe/Tiraspol", - "Europe/Uzhgorod", - "Europe/Vaduz", - "Europe/Vatican", - "Europe/Vienna", - "Europe/Vilnius", - "Europe/Volgograd", - "Europe/Warsaw", - "Europe/Zagreb", - "Europe/Zaporozhye", - "Europe/Zurich", - "GB", - "GB-Eire", - "GMT", - "GMT+0", - "Greenwich", - "HST", - "Hongkong", - "Iceland", - "Indian/Antananarivo", - "Indian/Chagos", - "Indian/Christmas", - "Indian/Cocos", - "Indian/Comoro", - "Indian/Kerguelen", - "Indian/Mahe", - "Indian/Maldives", - "Indian/Mauritius", - "Indian/Mayotte", - "Indian/Reunion", - "Iran", - "Israel", - "Jamaica", - "Japan", - "Kwajalein", - "Libya", - "MET", - "MST", - "MST7MDT", - "Mexico/BajaNorte", - "Mexico/BajaSur", - "Mexico/General", - "Mideast/Riyadh87", - "Mideast/Riyadh88", - "Mideast/Riyadh89", - "NZ", - "NZ-CHAT", - "Navajo", - "PRC", - "PST8PDT", - "Pacific/Apia", - "Pacific/Auckland", - "Pacific/Chatham", - "Pacific/Chuuk", - "Pacific/Easter", - "Pacific/Efate", - "Pacific/Enderbury", - "Pacific/Fakaofo", - "Pacific/Fiji", - "Pacific/Funafuti", - "Pacific/Galapagos", - "Pacific/Gambier", - "Pacific/Guadalcanal", - "Pacific/Guam", - "Pacific/Honolulu", - "Pacific/Johnston", - "Pacific/Kiritimati", - "Pacific/Kosrae", - "Pacific/Kwajalein", - "Pacific/Majuro", - "Pacific/Marquesas", - "Pacific/Midway", - "Pacific/Nauru", - "Pacific/Niue", - "Pacific/Norfolk", - "Pacific/Noumea", - "Pacific/Pago_Pago", - "Pacific/Palau", - "Pacific/Pitcairn", - "Pacific/Pohnpei", - "Pacific/Ponape", - "Pacific/Port_Moresby", - "Pacific/Rarotonga", - "Pacific/Saipan", - "Pacific/Samoa", - "Pacific/Tahiti", - "Pacific/Tarawa", - "Pacific/Tongatapu", - "Pacific/Truk", - "Pacific/Wake", - "Pacific/Wallis", - "Pacific/Yap", - "Poland", - "Portugal", - "ROC", - "ROK", - "Singapore", - "Turkey", - "UCT", - "US/Alaska", - "US/Aleutian", - "US/Arizona", - "US/Central", - "US/East-Indiana", - "US/Eastern", - "US/Hawaii", - "US/Indiana-Starke", - "US/Michigan", - "US/Mountain", - "US/Pacific", - "US/Pacific-New", - "US/Samoa", - "UTC", - "Universal", - "W-SU", - "Zulu" -] \ No newline at end of file diff --git a/modules/installed/system/users.py b/modules/installed/system/users.py index b2a7d2578..1b7550405 100644 --- a/modules/installed/system/users.py +++ b/modules/installed/system/users.py @@ -1,121 +1,172 @@ -import os, cherrypy +import cherrypy +from django import forms +from django.core import validators from gettext import gettext as _ -from auth import require, add_user -from plugin_mount import PagePlugin, FormPlugin +import auth +from auth import require +from plugin_mount import PagePlugin import cfg -from forms import Form -from util import * from model import User +import util -class users(PagePlugin): + +class Users(PagePlugin): order = 20 # order of running init in PagePlugins def __init__(self, *args, **kwargs): PagePlugin.__init__(self, *args, **kwargs) self.register_page("sys.users") - self.register_page("sys.users.add") - self.register_page("sys.users.edit") + + @staticmethod + @cherrypy.expose + @require() + def index(): + """Return a rendered users page""" + menu = {'title': _('Users and Groups'), + 'items': [{'url': '/sys/users/add', + 'text': _('Add User')}, + {'url': '/sys/users/edit', + 'text': _('Edit Users')}]} + sidebar_right = util.render_template(template='menu_block', + menu=menu) + return util.render_template(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) + + +class UserAdd(PagePlugin): + """Add user page""" + order = 30 + + def __init__(self, *args, **kwargs): + PagePlugin.__init__(self, *args, **kwargs) + + self.register_page('sys.users.add') @cherrypy.expose @require() - def index(self): - sidebar_right = 'Add UserAdding a user via this - administrative interface might 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.
""") - - def main(self, username='', name='', email='', message=None, *args, **kwargs): - form = Form(title="Add User", - action=cfg.server_dir + "/sys/users/add/index", - name="add_user_form", - message=message) - form.text_input(_("Username"), name="username", value=username) - form.text_input(_("Full name"), name="name", value=name) - form.text_input(_("Email"), name="email", value=email) - form.text_input(_("Password"), name="password", type="password") - form.submit(label=_("Create User"), name="create") - return form.render() - - def process_form(self, username=None, name=None, email=None, password=None, **kwargs): - msg = Message() - - error = add_user(username, password, name, email, False) - if error: - msg.text = error + if kwargs: + form = UserAddForm(kwargs, prefix='user') + # pylint: disable-msg=E1101 + if form.is_valid(): + self._add_user(form.cleaned_data, messages) + form = UserAddForm(prefix='user') else: - msg.add = _("%s saved." % username) + form = UserAddForm(prefix='user') - cfg.log(msg.text) - main = self.main(username, name, email, msg=msg.text) - return self.fill_template(title="Manage Users and Groups", main=main, sidebar_left=self.sidebar_left, sidebar_right=self.sidebar_right) + return util.render_template(template='users_add', title=_('Add User'), + form=form, messages=messages) -class edit(FormPlugin, PagePlugin): - url = ["/sys/users/edit"] - order = 35 + @staticmethod + def _add_user(data, messages): + """Add a user""" + if cfg.users.exists(data['username']): + messages.append( + ('error', _('User "{username}" already exists').format( + username=data['username']))) + return - sidebar_left = '' - sidebar_right = _("""Edit UsersClick on a user's name to - go to a screen for editing that user's account.
Delete - UsersCheck the box next to a users' names and then click - "Delete User" to remove users from %s and the %s - system.
Deleting users is permanent!
""" % (cfg.product_name, cfg.box_name)) + auth.add_user(data['username'], data['password'], data['full_name'], + data['email'], False) + messages.append( + ('success', _('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) - def main(self, msg=''): users = cfg.users.get_all() - add_form = Form(title=_("Edit or Delete User"), action=cfg.server_dir + "/sys/users/edit", message=msg) - add_form.html('DeleteCould not find a user with username of %s!
" % kwargs['username']) - return self.fill_template(template="err", title=_("Unknown User"), main=main, - sidebar_left=self.sidebar_left, sidebar_right=sidebar_right) - main = _("""Edit User '%s'""" % u['username']) - sidebar_right = '' - return self.fill_template(title="Manage Users and Groups", main=main, sidebar_left=self.sidebar_left, sidebar_right=sidebar_right) +class UserEdit(PagePlugin): + """User edit page""" + order = 35 + + def __init__(self, *args, **kwargs): + PagePlugin.__init__(self, *args, **kwargs) + + self.register_page('sys.users.edit') + + @cherrypy.expose + @require() + def index(self, **kwargs): + """Serve the form""" + form = None + messages = [] + + if kwargs: + form = UserEditForm(kwargs, prefix='user') + # pylint: disable-msg=E1101 + if form.is_valid(): + self._apply_changes(form.cleaned_data, messages) + form = UserEditForm(prefix='user') + else: + form = UserEditForm(prefix='user') + + return util.render_template(template='users_edit', + title=_('Edit or Delete User'), + form=form, messages=messages) + + @staticmethod + def _apply_changes(data, messages): + """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] + + cfg.log.info('%s asked to delete %s' % + (cherrypy.session.get(cfg.session_key), username)) + + if username == cfg.users.current(name=True): + messages.append( + ('error', + _('Can not delete current account - "%s"') % username)) + continue + + if not cfg.users.exists(username): + messages.append(('error', + _('User "%s" does not exist') % username)) + continue + + try: + cfg.users.remove(username) + messages.append(('success', _('User "%s" deleted') % username)) + except IOError as exception: + messages.append(('error', _('Error deleting "%s" - %s') % + (username, exception))) diff --git a/modules/installed/system/wan.py b/modules/installed/system/wan.py index 061ef50d1..962fe806f 100644 --- a/modules/installed/system/wan.py +++ b/modules/installed/system/wan.py @@ -1,78 +1,85 @@ -import os import cherrypy -try: - import simplejson as json -except ImportError: - import json +from django import forms from gettext import gettext as _ from modules.auth import require -from plugin_mount import PagePlugin, FormPlugin +from plugin_mount import PagePlugin import cfg -from forms import Form -from model import User -from util import * +import util -class wan(FormPlugin, PagePlugin): - url = ["/sys/config"] - order = 20 - def help(self, *args, **kwargs): - if not cfg.users.expert(): - return '' - return _(#"""If you check this box, this front - end will be reachable from the WAN. If your %(box)s - connects you to the internet, that means you'll be able to log - in to the front end from the internet. This might be - convenient, but it is also dangerous, since it can - enable attackers to gain access to your %(box)s from the - outside world. All they'll need is your username and - passphrase, which they might guess or they might simply try - every posible combination of letters and numbers until they - get in. If you enable the WAN administration option, you - must use long and complex passphrases.
+class WanForm(forms.Form): # pylint: disable-msg=W0232 + """Form to configure wan settings""" -For security reasons, neither WAN Administration nor WAN - SSH is available to the `admin` user account.
+ wan_admin = forms.BooleanField( + label=_('Allow access to Plinth from WAN'), + required=False, + help_text=_('If you check this box, this front end will be reachable \ +from the WAN. If your {{ box_name }} connects you to the internet, that \ +means you\'ll be able to log in to the front end from the internet. This \ +might be convenient, but it is also dangerous, since it can \ +enable attackers to gain access to your {{ box_name }} from the outside \ +world. All they\'ll need is your username and passphrase, which they might \ +guess or they might simply try every posible combination of letters and \ +numbers until they get in. If you enable the WAN administration option, you \ +must use long and complex passphrases.').format( + box_name=cfg.box_name)) -TODO: in expert mode, tell user they can ssh in to enable - admin from WAN, do their business, then disable it. It would - be good to enable the option and autodisable it when the ssh - connection dies.
- """ % {'product':cfg.product_name, 'box':cfg.box_name}) + lan_ssh = forms.BooleanField( + label=_('Allow SSH access from LAN'), + required=False) - def main(self, message='', **kwargs): - store = filedict_con(cfg.store_file, 'sys') + wan_ssh = forms.BooleanField( + label=_('Allow SSH access from WAN'), + required=False) - defaults = {'wan_admin': '', - 'wan_ssh': '', - 'lan_ssh': '', - } - for key, value in defaults.items(): - if not key in kwargs: - try: - kwargs[key] = store[key] - except KeyError: - store[key] = kwargs[key] = value + # XXX: Only present due to issue with submitting empty form + dummy = forms.CharField(label='Dummy', initial='dummy', + widget=forms.HiddenInput()) - form = Form(title=_("Accessing the %s" % cfg.box_name), - action=cfg.server_dir + "/sys/config/wan/", - name="admin_wan_form", - message=message) - form.html(self.help()) - if cfg.users.expert(): - form.checkbox(_("Allow access to Plinth from WAN"), name="wan_admin", checked=kwargs['wan_admin']) - form.checkbox(_("Allow SSH access from LAN"), name="lan_ssh", checked=kwargs['lan_ssh']) - form.checkbox(_("Allow SSH access from WAN"), name="wan_ssh", checked=kwargs['wan_ssh']) - # Hidden field is needed because checkbox doesn't post if not checked - form.hidden(name="submitted", value="True") +class Wan(PagePlugin): + order = 60 - form.submit(_("Submit")) - return form.render() + def __init__(self, *args, **kwargs): + PagePlugin.__init__(self, *args, **kwargs) + self.register_page('sys.config.wan') - def process_form(self, wan_admin='', wan_ssh='', lan_ssh='', *args, **kwargs): - store = filedict_con(cfg.store_file, 'sys') + cfg.html_root.sys.config.menu.add_item(_('WAN'), 'icon-cog', + '/sys/config/wan', 20) + + @cherrypy.expose + @require() + def index(self, **kwargs): + """Serve the configuration form""" + status = self.get_status() + + form = None + messages = [] + + if kwargs and cfg.users.expert(): + form = WanForm(kwargs, prefix='wan') + # pylint: disable-msg=E1101 + if form.is_valid(): + self._apply_changes(form.cleaned_data, messages) + status = self.get_status() + form = WanForm(initial=status, prefix='wan') + else: + form = WanForm(initial=status, prefix='wan') + + title = _('Accessing the {box_name}').format(box_name=cfg.box_name) + return util.render_template(template='wan', title=title, form=form, + messages=messages) + + @staticmethod + def get_status(): + """Return the current status""" + return util.filedict_con(cfg.store_file, 'sys') + + @staticmethod + def _apply_changes(new_status, messages): + """Apply the changes after form submission""" + store = util.filedict_con(cfg.store_file, 'sys') for field in ['wan_admin', 'wan_ssh', 'lan_ssh']: - store[field] = locals()[field] - return "Settings updated." + store[field] = new_status[field] + + messages.append(('success', _('Setting updated'))) diff --git a/modules/installed/templates/firstboot_sidebar.html b/modules/installed/templates/firstboot_sidebar.html new file mode 100644 index 000000000..5b89b873e --- /dev/null +++ b/modules/installed/templates/firstboot_sidebar.html @@ -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, seeWelcome. It looks like this FreedomBox isn't set up yet. We'll + need to ask you a just few questions to get started.
+ + + +{% endblock %} + +{% block sidebar_right_block %} + + {% include "firstboot_sidebar.html" %} + +{% endblock %} diff --git a/modules/installed/templates/firstboot_state1.html b/modules/installed/templates/firstboot_state1.html new file mode 100644 index 000000000..5ea907ff9 --- /dev/null +++ b/modules/installed/templates/firstboot_state1.html @@ -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, seeWelcome screen not completely implemented yet. Press continue to see the rest of the + web interface.
+ +%s
%s" % (dynamic_msg, stock_msg)) + return u.render_template(template="err", title=status, main="%s
%s" % (dynamic_msg, stock_msg)) def error_page_404(status, message, traceback, version): return error_page(status, message, """If you believe this @@ -88,6 +89,26 @@ def load_modules(): else: cfg.log("skipping %s" % name) + +def get_template_directories(): + """Return the list of template directories""" + directory = os.path.dirname(os.path.abspath(__file__)) + core_directory = os.path.join(directory, 'templates') + + directories = set((core_directory,)) + for name in os.listdir('modules'): + if not name.endswith(".py") or name.startswith('.'): + continue + + real_name = os.path.realpath(os.path.join('modules', name)) + directory = os.path.dirname(real_name) + directories.add(os.path.join(directory, 'templates')) + + cfg.log.info('Template directories - %s' % directories) + + return directories + + def parse_arguments(): parser = argparse.ArgumentParser(description='Plinth web interface for the FreedomBox.') parser.add_argument('--pidfile', @@ -146,7 +167,6 @@ def setup(): cfg.users = plugin_mount.UserStoreModule.get_plugins()[0] cfg.page_plugins = plugin_mount.PagePlugin.get_plugins() cfg.log("Loaded %d page plugins" % len(cfg.page_plugins)) - cfg.forms = plugin_mount.FormPlugin.get_plugins() # Add an extra server server = _cpserver.Server() @@ -178,13 +198,18 @@ def setup(): cherrypy.engine.signal_handler.subscribe() def main(): - # Initialize basic services - service.init() + # Initialize basic services + service.init() - setup() + setup() - cherrypy.engine.start() - cherrypy.engine.block() + # Configure Django + template_directories = get_template_directories() + django.conf.settings.configure(TEMPLATE_DIRS=template_directories, + INSTALLED_APPS=['bootstrapform']) + + cherrypy.engine.start() + cherrypy.engine.block() if __name__ == '__main__': main() diff --git a/plugin_mount.py b/plugin_mount.py index 69ff94552..e3ef5db41 100644 --- a/plugin_mount.py +++ b/plugin_mount.py @@ -1,8 +1,8 @@ import cherrypy from modules.auth import require import cfg -from util import * -import util as u +import util + class PluginMount(type): """See http://martyalchin.com/2008/jan/10/simple-plugin-framework/ for documentation""" @@ -34,27 +34,6 @@ class PluginMountSingular(PluginMount): cls.plugins.append(cls) -def get_parts(obj, parts=None, *args, **kwargs): - if parts == None: - parts={} - - fields = ['sidebar_left', 'sidebar_right', 'main', 'js', 'onload', 'nav', 'css', 'title'] - for v in fields: - if not v in parts: - parts[v] = '' - - try: - method = getattr(obj, v) - if callable(method): - parts[v] = method(*args, **kwargs) - else: - parts[v] = method - except AttributeError: - pass - - return parts - - def _setattr_deep(obj, path, value): """If path is 'x.y.z' or ['x', 'y', 'z'] then perform obj.x.y.z = value""" if isinstance(path, basestring): @@ -87,89 +66,6 @@ class PagePlugin: cfg.log.info("Registering page: %s" % url) _setattr_deep(cfg.html_root, url, self) - def fill_template(self, *args, **kwargs): - return u.page_template(*args, **kwargs) - - def forms(self, url, *args, **kwargs): - for form in cfg.forms: - if url in form.url: - cfg.log('Pulling together form for url %s (which matches %s)' % (url, form.url)) - - parts = get_parts(form, None, *args, **kwargs) - - return parts - return {'sidebar_left':left, 'sidebar_right':right, 'main':main} - -class FormPlugin(): - """ - Mount point for plugins that provide forms at specific URLs. - - Form plugin classes should also inherit from PagePlugin so they - can implement the page that handles the results of the form. The - name of the class will be appended to each url where the form is - displayed to get the urls of the results pages. - - Plugins implementing this reference should provide the following attributes: - - url - list of URL path strings of pages on which to display this - form, not including the url path that *only* displays this form - (that's handled by the index method) - - order - How high up on the page should this content be displayed? - Lower order is higher up. - - The following attributes are optional (though without at least one - of them, this plugin won't do much): - - sidebar_right - text to be displayed in the right column (can be attribute or method) (optional) - - sidebar_left - text to be displayed in the left column (can be attribute or method) (optional) - - main - text to be displayed in the center column (i.e. the form) (can be attribute or method) - - js - attribute containing a string that will be placed in the - template head, just below the javascript loads. Use it to load - more javascript files (optional) - - Although this plugin is intended for forms, it could just display - some html and skip the form. - """ - __metaclass__ = PluginMount - - order = 50 - url = [] - js = '' - - def __init__(self, *args, **kwargs): - for u in self.url: - path = u.split("/")[1:] + [self.__class__.__name__] - _setattr_deep(cfg.html_root, path, self) - cfg.log("Registered page: %s" % '.'.join(path)) - - def main(self, *args, **kwargs): - return "
Override this method and replace it with a form.
" - - @cherrypy.expose - @require() - def index(self, **kwargs): - """If the user has tried to fill in the form, process it, otherwise, just display a default form.""" - if kwargs: - kwargs['message'] = self.process_form(**kwargs) - parts = get_parts(self, **kwargs) - return self.fill_template(**parts) - - def process_form(self, **kwargs): - """Process the form. Return any message as a result of processing.""" - pass - - def fill_template(self, *args, **kwargs): - if not 'js' in kwargs: - try: - kwargs['js'] = self.js - except AttributeError: - pass - cfg.log("%%%%%%%%%%% %s" % kwargs) - return u.page_template(*args, **kwargs) class UserStoreModule: """ diff --git a/templates/Makefile b/templates/Makefile deleted file mode 100644 index df1b31f48..000000000 --- a/templates/Makefile +++ /dev/null @@ -1,15 +0,0 @@ -CHEETAH=cheetah -TEMPLATES=$(wildcard *.tmpl) -TEMPLATE_PYFILES := $(patsubst %.tmpl,%.py,$(TEMPLATES)) - -## Catch-all tagets -default: $(TEMPLATE_PYFILES) - -%.py: %.tmpl - $(CHEETAH) c $< -templates: $(TEMPLATE_PYFILES) -template: templates - -clean: - rm -rf .\#* \#* *.pyc *.bak - @rm -f $(TEMPLATE_PYFILES) diff --git a/templates/__init__.py b/templates/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/templates/base.html b/templates/base.html new file mode 100644 index 000000000..ebaea525c --- /dev/null +++ b/templates/base.html @@ -0,0 +1,136 @@ + + + + + + + + + + + + + + + + + + + + + + + + +