Как добавить автоматическую подстановку доменов при входе в Roundcube
Тип статьи:
Авторская
Для реализации подобного алгоритма нужно создать отдельный каталог для плагина. В данном примере roundcube лежит по пути /var/www/html/webmail, если у вас другой — отредактируйте под себя.
sudo mkdir /var/www/html/webmail/plugins/login_autocomplete/
Создаем файл конфигурации
sudo nano /var/www/html/webmail/plugins/login_autocomplete/login_autocomplete.php
Со следующим содержимым
<?php class login_autocomplete extends rcube_plugin { public $task = 'login'; // ========================================================================= // НАСТРОЙКИ ПЛАГИНА // ========================================================================= //Запрещать домены, которых нет в списке private $restrict_domains = true; //Включить логи. Используется путь записи логов из переменной $config['log_dir'] private $enable_logging = true; //Название лога private $log_filename = 'autocomplete_auth.log'; //Список доменов private $allowed_domains = ['domain1.tld', 'domain2.tld']; // ========================================================================= public function init() { $this->add_hook('authenticate', [$this, 'validate_login_domain']); $this->add_hook('template_object_loginform', [$this, 'login_form_modify']); } public function validate_login_domain($args) { $user_email = trim($args['user']); if (!$this->restrict_domains) { $this->log_action($user_email, 'ALLOWED (Control disabled)'); return $args; } if (strpos($user_email, '@') !== false) { $parts = explode('@', $user_email); $user_domain = strtolower(end($parts)); if (!in_array($user_domain, $this->allowed_domains)) { $this->log_action($user_email, 'BLOCKED (Unauthorized domain)'); $rcmail = rcube::get_instance(); unset($_SESSION['login_error']); $rcmail->output->show_message('Вход с этого почтового домена запрещен администратором', 'error'); $args['abort'] = false; $args['pass'] = ''; if ($rcmail->output->ajax_request) { $rcmail->output->send(); exit; } $rcmail->output->send('login'); exit; } } $this->log_action($user_email, 'ALLOWED (Domain check passed)'); return $args; } private function log_action($user, $status) { if (!$this->enable_logging) return; $rcmail = rcube::get_instance(); $log_dir = rtrim($rcmail->config->get('log_dir', RCUBE_INSTALL_PATH . 'logs'), '/\\'); $log_file = $log_dir . DIRECTORY_SEPARATOR . $this->log_filename; $ip = rcube_utils::remote_addr(); $date = date('Y-m-d H:i:s'); $log_line = sprintf("[%s]: %s -> %s (IP: %s)\n", $date, $user, $status, $ip); if ($fp = @fopen($log_file, 'a')) { @fwrite($fp, $log_line); @fflush($fp); @fclose($fp); } } public function login_form_modify($args) { $domains_json = json_encode($this->allowed_domains); $styles = " <style> .rc-autocomplete-container { position: relative; width: 100%; } .rc-autocomplete-list { position: absolute; top: 100%; left: 0; z-index: 9999; width: 100%; background: #ffffff; border: 1px solid #cbd5e1; border-radius: 4px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); max-height: 200px; overflow-y: auto; margin-top: 2px; padding: 0; list-style: none; display: none; } .rc-autocomplete-item { padding: 10px 14px; cursor: pointer; color: #334155; font-size: 14px; text-align: left; } .rc-autocomplete-item:hover { background: #f1f5f9; color: #0284c7; } </style>"; $script = " <script> (function() { var baseDomains = {$domains_json}; var checkInput = setInterval(function() { var userInput = document.getElementById('rcmloginuser'); if (userInput) { clearInterval(checkInput); userInput.setAttribute('autocomplete', 'new-password'); var wrapper = document.createElement('div'); wrapper.className = 'rc-autocomplete-container'; userInput.parentNode.insertBefore(wrapper, userInput); wrapper.appendChild(userInput); var listContainer = document.createElement('ul'); listContainer.className = 'rc-autocomplete-list'; wrapper.appendChild(listContainer); function renderSuggestions() { var val = userInput.value.trim(); if (val.length === 0 || val.includes('@')) { listContainer.style.display = 'none'; return; } listContainer.innerHTML = ''; baseDomains.forEach(function(domain) { var li = document.createElement('li'); li.className = 'rc-autocomplete-item'; li.textContent = val + '@' + domain; li.addEventListener('click', function() { userInput.value = val + '@' + domain; listContainer.style.display = 'none'; userInput.focus(); }); listContainer.appendChild(li); }); listContainer.style.display = 'block'; } userInput.addEventListener('input', renderSuggestions); document.addEventListener('click', function(e) { if (e.target !== userInput) listContainer.style.display = 'none'; }); } }, 50); })(); </script>"; $args['content'] .= $styles . $script; return $args; } }
Для корректной работы скрипта необходимо убедиться, что у web-сервера (Nginx, Apache и т.п.) есть права на папку с плагином и файл конфигурации. Для Debian/Ubuntu права можно задать следующим образом:
sudo chown -R www-data:www-data /var/www/html/webmail/plugins/login_autocomplete/
где
- /var/www/html/webmail/plugins/login_autocomplete/ — путь к папке плагина.
- www-data — имя пользователя веб-сервера.
Редактируем
sudo nano /var/www/html/webmail/config/config.inc.php
Дописывая в список плагинов login_autocomplete
$config['plugins'] = [ //Прочие плагины //... 'login_autocomplete', ];
Работа данного плагина тестировалась в версиях roundcube 1.7.x.