mirror of
https://github.com/freedombox/FreedomBox.git
synced 2026-11-29 08:25:10 +00:00
wordpress: Use privileged decorator for actions
Tests: - Functional tests work (when libpam-tmpdir is removed) - Backup and restore of database works - Initial setup work - Configuration file is created - Database is created - Website is accessible - Enabling/disabling public access works - Configuration file created/deleted - App page show proper status Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org> Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
This commit is contained in:
1 parent
0c936512c4
commit
d68a84d245
3 files changed
+29
-65
No files matched your search
@@ -1,11 +1,8 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
"""
|
||||
FreedomBox app to configure WordPress.
|
||||
"""
|
||||
"""FreedomBox app to configure WordPress."""
|
||||
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from plinth import actions
|
||||
from plinth import app as app_module
|
||||
from plinth import cfg, frontpage, menu
|
||||
from plinth.daemon import Daemon
|
||||
@@ -15,9 +12,7 @@ from plinth.modules.firewall.components import Firewall
|
||||
from plinth.package import Packages
|
||||
from plinth.utils import format_lazy
|
||||
|
||||
from . import manifest
|
||||
|
||||
PUBLIC_ACCESS_FILE = '/etc/wordpress/is_public'
|
||||
from . import manifest, privileged
|
||||
|
||||
_description = [
|
||||
_('WordPress is a popular way to create and manage websites and blogs. '
|
||||
@@ -106,7 +101,7 @@ class WordPressApp(app_module.App):
|
||||
def setup(self, old_version):
|
||||
"""Install and configure the app."""
|
||||
super().setup(old_version)
|
||||
actions.superuser_run('wordpress', ['setup'])
|
||||
privileged.setup()
|
||||
if not old_version:
|
||||
self.enable()
|
||||
elif old_version < 3:
|
||||
@@ -120,9 +115,9 @@ class WordPressBackupRestore(BackupRestore):
|
||||
def backup_pre(self, packet):
|
||||
"""Save database contents."""
|
||||
super().backup_pre(packet)
|
||||
actions.superuser_run('wordpress', ['dump-database'])
|
||||
privileged.dump_database()
|
||||
|
||||
def restore_post(self, packet):
|
||||
"""Restore database contents."""
|
||||
super().restore_post(packet)
|
||||
actions.superuser_run('wordpress', ['restore-database'])
|
||||
privileged.restore_database()
|
||||
@@ -0,0 +1,179 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
"""Configuration helper for WordPress."""
|
||||
|
||||
import os
|
||||
import pathlib
|
||||
import random
|
||||
import shutil
|
||||
import string
|
||||
import subprocess
|
||||
|
||||
import augeas
|
||||
|
||||
from plinth import action_utils
|
||||
from plinth.actions import privileged
|
||||
|
||||
PUBLIC_ACCESS_FILE = '/etc/wordpress/is_public'
|
||||
|
||||
_config_file_path = pathlib.Path('/etc/wordpress/config-default.php')
|
||||
_static_config_file_path = pathlib.Path('/etc/wordpress/freedombox-static.php')
|
||||
_db_file_path = pathlib.Path('/etc/wordpress/database.php')
|
||||
_db_backup_file = pathlib.Path(
|
||||
'/var/lib/plinth/backups-data/wordpress-database.sql')
|
||||
DB_HOST = 'localhost'
|
||||
DB_NAME = 'wordpress_fbx'
|
||||
DB_USER = 'wordpress_fbx'
|
||||
|
||||
|
||||
@privileged
|
||||
def setup():
|
||||
"""Create initial configuration and database for WordPress."""
|
||||
if _db_file_path.exists() or _config_file_path.exists():
|
||||
if _config_file_path.exists():
|
||||
_upgrade_config_file()
|
||||
|
||||
return
|
||||
|
||||
db_password = _generate_secret_key(16)
|
||||
|
||||
_create_config_file(DB_HOST, DB_NAME, DB_USER, db_password)
|
||||
_create_database(DB_NAME)
|
||||
_set_privileges(DB_HOST, DB_NAME, DB_USER, db_password)
|
||||
|
||||
|
||||
def _create_config_file(db_host, db_name, db_user, db_password):
|
||||
"""Create a PHP configuration file included by WordPress."""
|
||||
secret_keys = [_generate_secret_key() for _ in range(8)]
|
||||
|
||||
config_contents = f'''<?php
|
||||
# Created by FreedomBox
|
||||
include_once('{_static_config_file_path}');
|
||||
include_once('{_db_file_path}');
|
||||
define('DB_NAME', $dbname);
|
||||
define('DB_USER', $dbuser);
|
||||
define('DB_PASSWORD', $dbpass);
|
||||
define('DB_HOST', $dbserver);
|
||||
|
||||
define('AUTH_KEY', '{secret_keys[0]}');
|
||||
define('SECURE_AUTH_KEY', '{secret_keys[1]}');
|
||||
define('LOGGED_IN_KEY', '{secret_keys[2]}');
|
||||
define('NONCE_KEY', '{secret_keys[3]}');
|
||||
define('AUTH_SALT', '{secret_keys[4]}');
|
||||
define('SECURE_AUTH_SALT', '{secret_keys[5]}');
|
||||
define('LOGGED_IN_SALT', '{secret_keys[6]}');
|
||||
define('NONCE_SALT', '{secret_keys[7]}');
|
||||
|
||||
define('WP_CONTENT_DIR', '/var/lib/wordpress/wp-content');
|
||||
|
||||
define('DISABLE_WP_CRON', true);
|
||||
'''
|
||||
_config_file_path.write_text(config_contents, encoding='utf-8')
|
||||
|
||||
db_contents = f'''<?php
|
||||
# Created by FreedomBox
|
||||
$dbuser='{db_user}';
|
||||
$dbpass='{db_password}';
|
||||
$dbname='{db_name}';
|
||||
$dbserver='{db_host}';
|
||||
'''
|
||||
old_umask = os.umask(0o037)
|
||||
try:
|
||||
_db_file_path.write_text(db_contents, encoding='utf-8')
|
||||
finally:
|
||||
os.umask(old_umask)
|
||||
|
||||
shutil.chown(_db_file_path, group='www-data')
|
||||
|
||||
|
||||
def _create_database(db_name):
|
||||
"""Create an empty MySQL database for WordPress."""
|
||||
# Wordpress' install.php creates the tables.
|
||||
# SQL injection is avoided due to known input.
|
||||
query = f'''CREATE DATABASE {db_name};'''
|
||||
subprocess.run(['mysql', '--user', 'root'], input=query.encode(),
|
||||
check=True)
|
||||
|
||||
|
||||
def _set_privileges(db_host, db_name, db_user, db_password):
|
||||
"""Create user, set password and provide permissions on the database."""
|
||||
# SQL injection is avoided due to known input.
|
||||
query = f'''GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,ALTER
|
||||
ON {db_name}.*
|
||||
TO {db_user}@{db_host}
|
||||
IDENTIFIED BY '{db_password}';
|
||||
FLUSH PRIVILEGES;
|
||||
'''
|
||||
subprocess.run(['mysql', '--user', 'root'], input=query.encode(),
|
||||
check=True)
|
||||
|
||||
|
||||
def _generate_secret_key(length=64, chars=None):
|
||||
"""Generate a new random secret key for use with WordPress."""
|
||||
chars = chars or (string.ascii_letters + string.digits +
|
||||
'!@#$%^&*()-_ []{}<>~`+=,.:/?|')
|
||||
rand = random.SystemRandom()
|
||||
return ''.join(rand.choice(chars) for _ in range(length))
|
||||
|
||||
|
||||
def _upgrade_config_file():
|
||||
"""Upgrade existing config file to add changes."""
|
||||
include_line = f"include_once('{_static_config_file_path}');"
|
||||
lines = _config_file_path.read_text(encoding='utf-8').splitlines()
|
||||
if include_line not in lines:
|
||||
lines.insert(2, include_line) # Insert on 3rd line
|
||||
_config_file_path.write_text('\n'.join(lines), encoding='utf-8')
|
||||
|
||||
|
||||
@privileged
|
||||
def set_public(enable: bool):
|
||||
"""Allow/disallow public access."""
|
||||
public_access_file = pathlib.Path(PUBLIC_ACCESS_FILE)
|
||||
if enable:
|
||||
public_access_file.touch()
|
||||
else:
|
||||
public_access_file.unlink(missing_ok=True)
|
||||
|
||||
action_utils.service_reload('apache2')
|
||||
|
||||
|
||||
def is_public() -> bool:
|
||||
"""Return whether public access is enabled."""
|
||||
return pathlib.Path(PUBLIC_ACCESS_FILE).exists()
|
||||
|
||||
|
||||
@privileged
|
||||
def dump_database():
|
||||
"""Dump database to file."""
|
||||
_db_backup_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
with _db_backup_file.open('w', encoding='utf-8') as file_handle:
|
||||
subprocess.run([
|
||||
'mysqldump', '--add-drop-database', '--add-drop-table',
|
||||
'--add-drop-trigger', '--user', 'root', '--databases', DB_NAME
|
||||
], stdout=file_handle, check=True)
|
||||
|
||||
|
||||
@privileged
|
||||
def restore_database():
|
||||
"""Restore database from file."""
|
||||
with _db_backup_file.open('r', encoding='utf-8') as file_handle:
|
||||
subprocess.run(['mysql', '--user', 'root'], stdin=file_handle,
|
||||
check=True)
|
||||
|
||||
_set_privileges(DB_HOST, DB_NAME, DB_USER, _read_db_password())
|
||||
|
||||
|
||||
def _read_db_password():
|
||||
"""Return the password stored in the DB configuration file."""
|
||||
aug = _load_augeas()
|
||||
return aug.get('./$dbpass').strip('\'"')
|
||||
|
||||
|
||||
def _load_augeas():
|
||||
"""Initialize augeas."""
|
||||
aug = augeas.Augeas(flags=augeas.Augeas.NO_LOAD +
|
||||
augeas.Augeas.NO_MODL_AUTOLOAD)
|
||||
aug.transform('Phpvars', str(_db_file_path))
|
||||
aug.set('/augeas/context', '/files' + str(_db_file_path))
|
||||
aug.load()
|
||||
|
||||
return aug
|
||||
@@ -1,28 +1,25 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
"""
|
||||
FreedomBox app for configuring WordPress.
|
||||
"""
|
||||
|
||||
import pathlib
|
||||
"""FreedomBox app for configuring WordPress."""
|
||||
|
||||
from django.contrib import messages
|
||||
from django.utils.translation import gettext as _
|
||||
|
||||
from plinth import actions, views
|
||||
from plinth import views
|
||||
|
||||
from . import PUBLIC_ACCESS_FILE
|
||||
from . import privileged
|
||||
from .forms import WordPressForm
|
||||
|
||||
|
||||
class WordPressAppView(views.AppView):
|
||||
"""Serve configuration page."""
|
||||
|
||||
form_class = WordPressForm
|
||||
app_id = 'wordpress'
|
||||
|
||||
def get_initial(self):
|
||||
"""Get the current WordPress settings."""
|
||||
status = super().get_initial()
|
||||
status['is_public'] = pathlib.Path(PUBLIC_ACCESS_FILE).exists()
|
||||
status['is_public'] = privileged.is_public()
|
||||
return status
|
||||
|
||||
def form_valid(self, form):
|
||||
@@ -30,10 +27,7 @@ class WordPressAppView(views.AppView):
|
||||
old_status = form.initial
|
||||
new_status = form.cleaned_data
|
||||
if old_status['is_public'] != new_status['is_public']:
|
||||
actions.superuser_run(
|
||||
'wordpress',
|
||||
['set-public', '--enable',
|
||||
str(new_status['is_public'])])
|
||||
privileged.set_public(new_status['is_public'])
|
||||
messages.success(self.request, _('Configuration updated'))
|
||||
|
||||
return super().form_valid(form)
|
||||
Reference in new issue
Block a user