tinyauth-web/src/actions.php

234 lines
7.8 KiB
PHP

<?php
declare(strict_types=1);
function handle_setup(array $groups): void
{
$group = (string) ($_POST['group'] ?? '');
if (!in_array($group, $groups, true)) {
flash('error', 'Pick one of your own groups.');
return;
}
save_settings(['allowed_group' => $group]);
flash('ok', "Access group set to \"$group\".");
}
function handle_reset_group(): void
{
save_settings([]);
flash('info', 'Access group cleared. Pick a new one below.');
}
function handle_service(string $action): void
{
$service = config()['service'];
if (!service_allowed($action)) {
flash('error', "sudo does not allow 'systemctl $action $service' for this user. See the permission checks.");
return;
}
$result = service_run($action);
$ok = $result['code'] === 0 || ($action === 'status' && $result['code'] === 3);
flash($ok ? 'ok' : 'error', ucfirst($action) . ' ' . ($ok ? 'done' : 'failed') . " (exit {$result['code']}).");
if ($result['output'] !== '') {
$_SESSION['last_output'] = $result['output'];
}
}
/**
* Writes changes to the env file after making a backup.
* Returns the backup file name on success, or null with a flash error.
*/
function apply_env_changes(array $changes, array $deletes): ?string
{
$envFile = config()['env_file'];
if (!is_file($envFile) || !is_readable($envFile) || !is_writable($envFile)) {
flash('error', "Env file $envFile is missing or not readable/writable by this user.");
return null;
}
$content = (string) file_get_contents($envFile);
$backupDir = data_dir() . '/backups';
if (!is_dir($backupDir)) {
mkdir($backupDir, 0750, true);
}
$backup = $backupDir . '/tinyauth.env.' . date('Ymd-His');
if (!copy($envFile, $backup)) {
flash('error', "Could not write backup to $backup. Nothing was changed.");
return null;
}
if (file_put_contents($envFile, env_apply($content, $changes, $deletes), LOCK_EX) === false) {
flash('error', "Could not write $envFile.");
return null;
}
return basename($backup);
}
/** Blank values are allowed, so the page only warns about them. Returns null when none are blank. */
function blank_warning(): ?string
{
$blank = blank_keys(env_parse(current_env()));
if ($blank === []) {
return null;
}
return count($blank) . ' blank variable(s): ' . implode(', ', $blank)
. '. tinyauth may not work with these empty. Fill them in or delete them.';
}
function valid_value(string $value): bool
{
return !preg_match('/[\r\n]/', $value);
}
function handle_save_config(): void
{
$original = env_parse(current_env());
$deletes = array_values(array_intersect(array_map('strval', (array) ($_POST['delete'] ?? [])), array_keys($original)));
$posted = (array) ($_POST['value'] ?? []);
$changes = [];
foreach ($original as $key => $current) {
if (in_array($key, $deletes, true) || !array_key_exists($key, $posted)) {
continue;
}
$new = (string) $posted[$key];
if (!valid_value($new)) {
flash('error', "Value for $key contains a line break.");
return;
}
if (preg_match(SECRET_PATTERN, $key) && $new === '') {
continue;
}
if ($new !== $current) {
$changes[$key] = $new;
}
}
$newKey = trim((string) ($_POST['new_key'] ?? ''));
$newValue = (string) ($_POST['new_value'] ?? '');
if ($newKey !== '') {
if (!preg_match(KEY_PATTERN, $newKey)) {
flash('error', "\"$newKey\" is not a valid variable name (letters, digits and underscores).");
return;
}
if (isset($original[$newKey]) && !in_array($newKey, $deletes, true)) {
flash('error', "$newKey already exists. Edit it in the table instead.");
return;
}
if (!valid_value($newValue)) {
flash('error', "Value for $newKey contains a line break.");
return;
}
$changes[$newKey] = $newValue;
}
if ($changes === [] && $deletes === []) {
flash('info', 'No changes to save.');
return;
}
$backup = apply_env_changes($changes, $deletes);
if ($backup === null) {
return;
}
flash('ok', 'Saved ' . (count($changes) + count($deletes)) . ' change(s). Backup: ' . $backup . '. Restart tinyauth to apply.');
}
function handle_create_oidc_client(): void
{
$name = strtoupper(trim((string) ($_POST['client_name'] ?? '')));
if (!preg_match('/^[A-Z0-9]+$/', $name)) {
flash('error', 'Client name: letters and digits only, no spaces or underscores.');
return;
}
$prefix = "TINYAUTH_OIDC_CLIENTS_{$name}_";
foreach (array_keys(env_parse(current_env())) as $key) {
if (str_starts_with($key, $prefix)) {
flash('error', "A client named $name already exists. Edit it in the table instead.");
return;
}
}
$clientId = trim((string) ($_POST['client_id'] ?? '')) ?: strtolower($name);
$secret = trim((string) ($_POST['client_secret'] ?? ''));
$generated = $secret === '';
if ($generated) {
$secret = bin2hex(random_bytes(24));
}
$display = trim((string) ($_POST['display_name'] ?? '')) ?: $name;
$redirects = trim((string) ($_POST['redirect_uris'] ?? ''));
$changes = [
$prefix . 'CLIENTID' => $clientId,
$prefix . 'CLIENTSECRET' => $secret,
$prefix . 'NAME' => $display,
];
if ($redirects !== '') {
$changes[$prefix . 'TRUSTEDREDIRECTURIS'] = $redirects;
}
foreach ($changes as $value) {
if (!valid_value($value)) {
flash('error', 'Values cannot contain line breaks.');
return;
}
}
$backup = apply_env_changes($changes, []);
if ($backup === null) {
return;
}
$message = "OIDC client $name created. Restart tinyauth to apply. Backup: $backup.";
if ($generated) {
$message .= ' Generated client secret (shown once, copy it now): ' . $secret;
}
flash('ok', $message);
if ($redirects === '') {
flash('warn', "No redirect URIs for $name. Login will fail until you add TINYAUTH_OIDC_CLIENTS_{$name}_TRUSTEDREDIRECTURIS.");
}
}
function handle_create_app_acl(): void
{
$name = strtoupper(trim((string) ($_POST['app_name'] ?? '')));
if (!preg_match('/^[A-Z0-9]+$/', $name)) {
flash('error', 'App name: letters and digits only, no spaces or underscores.');
return;
}
$prefix = "TINYAUTH_APPS_{$name}_";
foreach (array_keys(env_parse(current_env())) as $key) {
if (str_starts_with($key, $prefix)) {
flash('error', "An app named $name already exists. Edit it in the table instead.");
return;
}
}
$fields = [
'CONFIG_DOMAIN' => trim((string) ($_POST['domain'] ?? '')),
'USERS_ALLOW' => trim((string) ($_POST['users_allow'] ?? '')),
'LDAP_GROUPS' => trim((string) ($_POST['ldap_groups'] ?? '')),
'OAUTH_GROUPS' => trim((string) ($_POST['oauth_groups'] ?? '')),
];
$changes = [];
foreach ($fields as $suffix => $value) {
if ($value === '') {
continue;
}
if (!valid_value($value)) {
flash('error', 'Values cannot contain line breaks.');
return;
}
$changes[$prefix . $suffix] = $value;
}
if ($changes === []) {
flash('error', 'Fill in at least one field for the app.');
return;
}
$backup = apply_env_changes($changes, []);
if ($backup === null) {
return;
}
flash('ok', "App $name added. Restart tinyauth to apply. Backup: $backup.");
if ($fields['CONFIG_DOMAIN'] === '') {
flash('warn', "No domain set for $name. Add TINYAUTH_APPS_{$name}_CONFIG_DOMAIN or the app will not match.");
}
}