Skip to content

Commit

Permalink
feat: add hability to disable login (#378)
Browse files Browse the repository at this point in the history
  • Loading branch information
ellite authored Jun 7, 2024
1 parent f79a3f9 commit 092be22
Show file tree
Hide file tree
Showing 28 changed files with 205 additions and 12 deletions.
23 changes: 21 additions & 2 deletions admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
$result = $stmt->execute();
$settings = $result->fetchArray(SQLITE3_ASSOC);

// get user accounts where id is not 1
// get user accounts
$stmt = $db->prepare('SELECT id, username, email FROM user ORDER BY id ASC');
$result = $stmt->execute();

Expand All @@ -20,7 +20,8 @@
$users[] = $row;
}
$userCount = is_array($users) ? count($users) : 0;


$loginDisabledAllowed = $userCount == 1 && $settings['registrations_open'] == 0;
?>

<section class="contain settings">
Expand All @@ -42,6 +43,9 @@
<p>
<i class="fa-solid fa-circle-info"></i>
<?= translate('max_users_info', $i18n) ?>
</p><p>
<i class="fa-solid fa-circle-info"></i>
By enabling user registrations, the setting to disable login will be unavailable.
</p>
</div>
<div class="form-group-inline">
Expand Down Expand Up @@ -76,6 +80,21 @@
<?= translate('server_url_password_reset', $i18n) ?>
</p>
</div>
<hr>
<div class="form-group-inline">
<input type="checkbox" id="disableLogin" <?= $settings['login_disabled'] ? 'checked' : '' ?> <?= $loginDisabledAllowed ? '' : 'disabled' ?> />
<label for="disableLogin"><?= translate('disable_login', $i18n) ?></label>
</div>
<div class="settings-notes">
<p>
<i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
<?= translate('disable_login_info', $i18n) ?>
</p>
<p>
<i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
<?= translate('disable_login_info2', $i18n) ?>
</p>
</div>
<div class="buttons">
<input type="submit" class="thin" value="<?= translate('save', $i18n) ?>" id="saveAccountRegistrations" onClick="saveAccountRegistrationsButton()"/>
</div>
Expand Down
28 changes: 27 additions & 1 deletion endpoints/admin/saveopenregistrations.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,31 @@
$maxUsers = $data['max_users'];
$requireEmailVerification = $data['require_email_validation'];
$serverUrl = $data['server_url'];
$disableLogin = $data['disable_login'];

if ($disableLogin == 1) {
if ($openRegistrations == 1) {
echo json_encode([
"success" => false,
"message" => translate('error', $i18n)
]);
die();
}

$sql = "SELECT COUNT(*) as userCount FROM user";
$stmt = $db->prepare($sql);
$result = $stmt->execute();
$row = $result->fetchArray(SQLITE3_ASSOC);
$userCount = $row['userCount'];

if ($userCount > 1) {
echo json_encode([
"success" => false,
"message" => translate('error', $i18n)
]);
die();
}
}

if ($requireEmailVerification == 1 && $serverUrl == "") {
echo json_encode([
Expand All @@ -35,12 +60,13 @@
die();
}

$sql = "UPDATE admin SET registrations_open = :openRegistrations, max_users = :maxUsers, require_email_verification = :requireEmailVerification, server_url = :serverUrl";
$sql = "UPDATE admin SET registrations_open = :openRegistrations, max_users = :maxUsers, require_email_verification = :requireEmailVerification, server_url = :serverUrl, login_disabled = :disableLogin WHERE id = 1";
$stmt = $db->prepare($sql);
$stmt->bindParam(':openRegistrations', $openRegistrations, SQLITE3_INTEGER);
$stmt->bindParam(':maxUsers', $maxUsers, SQLITE3_INTEGER);
$stmt->bindParam(':requireEmailVerification', $requireEmailVerification, SQLITE3_INTEGER);
$stmt->bindParam(':serverUrl', $serverUrl, SQLITE3_TEXT);
$stmt->bindParam(':disableLogin', $disableLogin, SQLITE3_INTEGER);
$result = $stmt->execute();

if ($result) {
Expand Down
18 changes: 14 additions & 4 deletions includes/checksession.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,20 @@
}
$userId = $userData['id'];
$main_currency = $userData['main_currency'];
$sql = "SELECT * FROM login_tokens WHERE user_id = :userId AND token = :token";
$stmt = $db->prepare($sql);
$stmt->bindParam(':userId', $userId, SQLITE3_TEXT);
$stmt->bindParam(':token', $token, SQLITE3_TEXT);

$adminQuery = "SELECT login_disabled FROM admin";
$adminResult = $db->query($adminQuery);
$adminRow = $adminResult->fetchArray(SQLITE3_ASSOC);
if ($adminRow['login_disabled'] == 1) {
$sql = "SELECT * FROM login_tokens WHERE user_id = :userId";
$stmt = $db->prepare($sql);
$stmt->bindParam(':userId', $userId, SQLITE3_TEXT);
} else {
$sql = "SELECT * FROM login_tokens WHERE user_id = :userId AND token = :token";
$stmt = $db->prepare($sql);
$stmt->bindParam(':userId', $userId, SQLITE3_TEXT);
$stmt->bindParam(':token', $token, SQLITE3_TEXT);
}
$result = $stmt->execute();
$row = $result->fetchArray(SQLITE3_ASSOC);

Expand Down
8 changes: 8 additions & 0 deletions includes/getsettings.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,12 @@
$settings['customColors'] = $customColors;
}

$query = "SELECT * FROM admin";
$result = $db->query($query);
$adminSettings = $result->fetchArray(SQLITE3_ASSOC);

if ($adminSettings) {
$settings['disableLogin'] = $adminSettings['login_disabled'];
}

?>
8 changes: 7 additions & 1 deletion includes/header.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,13 @@
<a href="admin.php"><i class="fa-solid fa-user-tie"></i><?= translate('admin', $i18n) ?></a>
<?php endif; ?>
<a href="about.php"><i class="fa-solid fa-info-circle"></i><?= translate('about', $i18n) ?></a>
<a href="logout.php"><i class="fa-solid fa-arrow-right-from-bracket"></i><?= translate('logout', $i18n) ?></a>
<?php
if ($settings['disableLogin'] == 0) {
?>
<a href="logout.php"><i class="fa-solid fa-arrow-right-from-bracket"></i><?= translate('logout', $i18n) ?></a>
<?php
}
?>
</div>
</div>
</nav>
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/de.php
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,9 @@
"server_url" => "Server URL",
"server_url_info" => "Wird für die E-Mail-Überprüfung und die Passwortwiederherstellung verwendet. Muss eine gültige öffentliche URL sein.",
"server_url_password_reset" => "Wenn diese Option gesetzt ist, wird auch die Funktion zum Zurücksetzen des Passworts aktiviert.",
"disable_login" => "Login deaktivieren",
"disable_login_info" => "Anmeldung umgehen. Wenn Sie Ihren Server nur in einem lokalen Netzwerk betreiben, ohne Zugriff von außen, können Sie die Anmeldung deaktivieren. Dadurch wird automatisch der Admin-Benutzer angemeldet.",
"disable_login_info2" => "Sie können diese Einstellung nur aktivieren, wenn die Benutzerregistrierung ausgeschaltet ist und es nicht mehr als ein Admin-Benutzerkonto gibt.",
"max_users_info" => "0 für unbegrenzte Anzahl an Benutzern",
"user_management" => "Benutzerverwaltung",
"delete_user" => "Benutzer löschen",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/el.php
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,9 @@
"server_url" => "Διεύθυνση URL διακομιστή",
"server_url_info" => "Χρησιμοποιείται για επαλήθευση email και ανάκτηση κωδικού πρόσβασης. Πρέπει να είναι ένα έγκυρο δημόσιο URL.",
"server_url_password_reset" => "Εάν οριστεί, θα ενεργοποιήσει επίσης τη λειτουργία επαναφοράς κωδικού πρόσβασης.",
"disable_login" => "Απενεργοποίηση σύνδεσης",
"disable_login_info" => "Παράκαμψη σύνδεσης. Εάν εκτελείτε το διακομιστή σας μόνο σε τοπικό δίκτυο, χωρίς εξωτερική πρόσβαση, μπορείτε να απενεργοποιήσετε τη σύνδεση. Αυτό θα πραγματοποιήσει αυτόματα την είσοδο του χρήστη διαχειριστή.",
"disable_login_info2" => "Μπορείτε να ενεργοποιήσετε αυτή τη ρύθμιση μόνο εάν η εγγραφή χρηστών είναι απενεργοποιημένη και δεν υπάρχουν περισσότεροι από το λογαριασμό χρήστη διαχειριστή.",
"max_users_info" => "Ο μέγιστος αριθμός χρηστών που μπορούν να εγγραφούν. Αν η τιμή είναι 0, δεν υπάρχει όριο.",
"user_management" => "Διαχείριση χρηστών",
"delete_user" => "Διαγραφή χρήστη",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/en.php
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,9 @@
"server_url" => "Server URL",
"server_url_info" => "Used for email verification and password recovery. Must be a valid public URL.",
"server_url_password_reset" => "If set will also enable password reset functionality.",
"disable_login" => "Disable login",
"disable_login_info" => "Bypass login. If you run your server on a local network only, without external access you can disable the login. This will automatically login the admin user.",
"disable_login_info2" => "You can only enable this setting if user registration is disabled and there are no more than the admin user account.",
"max_users_info" => "0 means unlimited",
"user_management" => "User Management",
"delete_user" => "Delete User",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/es.php
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,9 @@
"server_url" => "URL del Servidor",
"server_url_info" => "Se utiliza para verificar el correo electrónico y recuperar la contraseña. Debe ser una URL pública válida.",
"server_url_password_reset" => "Si se configura, también se habilitará la función de restablecimiento de contraseña.",
"disable_login" => "Deshabilitar Inicio de Sesión",
"disable_login_info" => "Omitir el inicio de sesión. Si ejecuta su servidor sólo en una red local, sin acceso externo, puede desactivar el inicio de sesión. Esto iniciará automáticamente la sesión del usuario administrador.",
"disable_login_info2" => "Sólo puede activar esta configuración si el registro de usuarios está desactivado y no hay más que la cuenta de usuario admin.",
"max_users_info" => "0 para ilimitado",
"user_management" => "Gestión de Usuarios",
"delete_user" => "Eliminar Usuario",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/fr.php
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,9 @@
"server_url" => "URL du serveur",
"server_url_info" => "Utilisé pour la vérification du courrier électronique et la récupération du mot de passe. Il doit s'agir d'une URL publique valide.",
"server_url_password_reset" => "Si cette option est activée, la fonction de réinitialisation du mot de passe sera également activée.",
"disable_login" => "Désactiver la connexion",
"disable_login_info" => "Contourner le login. Si vous utilisez votre serveur sur un réseau local uniquement, sans accès externe, vous pouvez désactiver le login. L'utilisateur admin se connectera automatiquement.",
"disable_login_info2" => "Vous ne pouvez activer ce paramètre que si l'enregistrement des utilisateurs est désactivé et qu'il n'y a pas d'autre compte utilisateur que celui de l'administrateur.",
"max_users_info" => "0 signifie un nombre illimité d'utilisateurs",
"user_management" => "Gestion des utilisateurs",
"delete_user" => "Supprimer l'utilisateur",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/it.php
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,9 @@
"server_url" => "URL del server",
"server_url_info" => "Utilizzato per la verifica dell'e-mail e il recupero della password. Deve essere un URL pubblico valido.",
"server_url_password_reset" => "Se impostato, abilita anche la funzionalità di reimpostazione della password.",
"disable_login" => "Disabilita il login",
"disable_login_info" => "Bypassare il login. Se si gestisce il server solo su una rete locale, senza accesso esterno, è possibile disabilitare il login. In questo modo, l'utente amministratore effettuerà automaticamente il login.",
"disable_login_info2" => "Questa impostazione può essere attivata solo se la registrazione degli utenti è disattivata e non ci sono più account utente oltre a quello dell'amministratore.",
"max_users_info" => "Impostare a 0 per un numero illimitato di utenti",
"user_management" => "Gestione utenti",
"delete_user" => "Elimina utente",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/jp.php
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,9 @@
"server_url" => "サーバーURL",
"server_url_info" => "電子メール認証とパスワード回復に使用される。有効な公開URLでなければなりません。",
"server_url_password_reset" => "設定すると、パスワードリセット機能も有効になる。",
"disable_login" => "ログインを無効にする",
"disable_login_info" => "ログインをバイパスします。サーバーをローカルネットワークのみで運用し、外部からのアクセスがない場合、ログインを無効にすることができます。これにより、管理者ユーザが自動的にログインします。",
"disable_login_info2" => "この設定を有効にできるのは、ユーザー登録がオフで、管理者以上のユーザーアカウントが存在しない場合のみです。",
"max_users_info" => "0に設定すると無制限になります",
"user_management" => "ユーザー管理",
"delete_user" => "ユーザーを削除",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/ko.php
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,9 @@
"server_url" => "서버 URL",
"server_url_info" => "이메일 인증 및 비밀번호 복구에 사용됩니다. 유효한 공개 URL이어야 합니다.",
"server_url_password_reset" => "설정하면 비밀번호 재설정 기능도 활성화됩니다.",
"disable_login" => "로그인 비활성화",
"disable_login_info" => "로그인 우회. 외부 액세스 없이 로컬 네트워크에서만 서버를 실행하는 경우 로그인을 비활성화할 수 있습니다. 그러면 관리자 사용자가 자동으로 로그인됩니다.",
"disable_login_info2" => "이 설정은 사용자 등록이 해제되어 있고 관리자 사용자 계정이 없는 경우에만 활성화할 수 있습니다.",
"max_users_info" => "0으로 설정하면 무제한으로 설정됩니다.",
"user_management" => "유저 관리",
"delete_user" => "유저 삭제",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/pl.php
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,9 @@
"server_url" => "Adres URL serwera",
"server_url_info" => "Służy do weryfikacji adresu e-mail i odzyskiwania hasła. Musi to być prawidłowy publiczny adres URL.",
"server_url_password_reset" => "Jeśli zostanie ustawiona, włączy również funkcję resetowania hasła.",
"disable_login" => "Wyłącz logowanie",
"disable_login_info" => "Obejście logowania. Jeśli serwer działa tylko w sieci lokalnej, bez dostępu z zewnątrz, można wyłączyć logowanie. Spowoduje to automatyczne zalogowanie użytkownika admin.",
"disable_login_info2" => "To ustawienie można włączyć tylko wtedy, gdy rejestracja użytkowników jest wyłączona i nie ma więcej niż konto administratora.",
"max_users_info" => "Jeśli ustawisz 0, nie będzie limitu użytkowników.",
"user_management" => "Zarządzanie użytkownikami",
"delete_user" => "Usuń użytkownika",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/pt.php
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,9 @@
"server_url" => "URL do Servidor",
"server_url_info" => "Usado para gerar links de verificação de email. Deve ser um URL público e válido.",
"server_url_password_reset" => "Se definido, também activará a funcionalidade de reposição da palavra-passe.",
"disable_login" => "Desactivar Inicio de Sessão",
"disable_login_info" => "Ultrapassar o início de sessão. Se o seu servidor funciona apenas numa rede local, sem acesso externo, pode desativar o início de sessão. Isto irá iniciar automaticamente a sessão do utilizador administrador.",
"disable_login_info2" => "Só pode ativar esta definição se o registo de utilizadores estiver desativado e se não houver mais do que a conta de utilizador administrador.",
"max_users_info" => "0 para ilimitado",
"user_management" => "Gestão de Utilizadores",
"delete_user" => "Apagar Utilizador",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/pt_br.php
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,9 @@
"server_url" => "URL do servidor",
"server_url_info" => "Será usado para gerar links de verificação de email, deve ser um endereço público e válido.",
"server_url_password_reset" => "Se definido, também ativará a funcionalidade de redefinição de senha.",
"disable_login" => "Desativar login",
"disable_login_info" => "Ignorar login. Se você executar o servidor somente em uma rede local, sem acesso externo, poderá desativar o login. Isso fará o login automático do usuário administrador.",
"disable_login_info2" => "Só é possível ativar essa configuração se o registro de usuário estiver desativado e não houver mais do que a conta de usuário administrador.",
"max_users_info" => "0 para ilimitado",
"user_management" => "Gerenciamento de usuários",
"delete_user" => "Excluir usuário",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/ru.php
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,9 @@
"server_url" => "URL-адрес сервера",
"server_url_info" => "Используется для проверки электронной почты и восстановления пароля. Должен быть действительным публичным URL.",
"server_url_password_reset" => "Если этот параметр установлен, он также включает функцию сброса пароля.",
"disable_login" => "Отключить вход",
"disable_login_info" => "Обход входа в систему. Если вы используете свой сервер только в локальной сети, без доступа извне, вы можете отключить вход в систему. При этом будет автоматически входить пользователь admin.",
"disable_login_info2" => "Этот параметр можно включить только в том случае, если регистрация пользователей отключена и их количество не превышает учетную запись администратора.",
"max_users_info" => "Установите 0 для неограниченного количества пользователей.",
"user_management" => "Управление пользователями",
"delete_user" => "Удалить пользователя",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/sl.php
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,9 @@
"server_url" => "URL strežnika",
"server_url_info" => "Uporablja se za preverjanje e-pošte in obnovitev gesla. Biti mora veljaven javni URL.",
"server_url_password_reset" => "Če je nastavljeno, bo omogočena tudi funkcija ponastavitve gesla.",
"disable_login" => "Onemogoči prijavo",
"disable_login_info" => "Obidite prijavo. Če strežnik uporabljate samo v lokalnem omrežju brez zunanjega dostopa, lahko onemogočite prijavo. Tako se bo samodejno prijavil uporabnik administrator.",
"disable_login_info2" => "To nastavitev lahko omogočite le, če je registracija uporabnikov izklopljena in če ni več uporabniških računov, razen uporabniškega računa upravitelja.",
"max_users_info" => "0 pomeni neomejeno",
"user_management" => "Upravljanje uporabnikov",
"delete_user" => "Izbriši uporabnika",
Expand Down
Loading

0 comments on commit 092be22

Please sign in to comment.