Контекст:
Мои вопросы относятся к форуму, который я разрабатываю почти так же, как SO, где есть:
- гости, которые имеют доступ к обсуждениям, но не могут отвечать или голосовать
- участники, которые с достаточным количеством репутации могут редактировать / голосовать за другие темы, и по умолчанию они могут отвечать и иметь те же привилегии, что и гости
- админы, которые могут делать что угодно
Я бы хотел, чтобы этот ACL применялся ко всему сайту и по умолчанию запрещал все ресурсы.
Я прочитал основы использования Zend_Acl - вы в основном создаете роли (гость, участник, администратор) и либо запрещаете, либо разрешаете ресурсы (контроллеры, методы) для этих ролей. В документации нет подробностей о том, как на самом деле следует реализовать код acl в своем приложении, поэтому я поискал SO ..
Наткнулся на довольно полезный stackoverflow ответ от marek, который проливает свет на проблему Однако из-за незнания я до сих пор не могу полностью понять, как правильно реализовать это с учетом передовых практик.
У плаката есть статический файл configAcl.php
в корне приложения, который инициализирует объект acl, добавляет роли, создает ресурс для каждого контроллера, дает admin
доступ ко всему, дает normal
доступ ко всему, кроме администратора, и сохраняет объект acl в реестре. для дальнейшего использования.
$acl = new Zend_Acl();
$roles = array('admin', 'normal');
// Controller script names. You have to add all of them if credential check
// is global to your application.
$controllers = array('auth', 'index', 'news', 'admin');
foreach ($roles as $role) {
$acl->addRole(new Zend_Acl_Role($role));
}
foreach ($controllers as $controller) {
$acl->add(new Zend_Acl_Resource($controller));
}
// Here comes credential definiton for admin user.
$acl->allow('admin'); // Has access to everything.
// Here comes credential definition for normal user.
$acl->allow('normal'); // Has access to everything...
$acl->deny('normal', 'admin'); // ... except the admin controller.
// Finally I store whole ACL definition to registry for use
// in AuthPlugin plugin.
$registry = Zend_Registry::getInstance();
$registry->set('acl', $acl);
Вопрос № 1. Должен ли этот код быть в начальной загрузке или в отдельном файле, таком как этот? Если да, то было бы лучше, если бы он находился внутри, скажем, каталога библиотеки?
Вторая часть - это новый класс, расширяющий класс Zend Controller Plugin Abstract, который позволяет подключать его к auth/login
, логика в основном заключается в том, что если логин не удался, он перенаправляет ... в противном случае он захватывает объект acl из реестра, захватывает identity и определяет, разрешено ли пользователю просматривать этот ресурс.
$identity = $auth->getIdentity();
$frontController->registerPlugin(new AuthPlugin());
Вопрос № 2. Как именно я могу кодировать часть плагина аутентификации, которая фактически возвращает личность пользователя? Я понимаю, что у него был код ниже, который сгенерировал объект таблицы db адаптера Auth, который будет запрашивать столбец таблицы базы данных по идентификатору пользователя и учетным данным (проверка хешированного прохода). Я не понимаю, где это соответствует части getIdentity.
Допустим, моя таблица пользователей состояла из следующих данных:
user_id user_name level
1 superadmin 3
2 john 2
3 example.com 1
Где уровень 3 = администратор, 2 = участник, 1 = гость.
Вопрос № 3 - где именно лучше всего поместить указанный выше код авторизации? Внутри контроллера входа в систему?
Вопрос № 4 - другой автор отвечает своей статьей о том, как логика acl должна выполняться внутри моделей, но конкретный метод, который он использует, изначально не поддерживается и требует обходного пути. Возможно ли это? И действительно ли это так в идеале?