SilverStripe 4 - пустая страница при выходе
Как я уже говорил здесь, я бы позволил предварительно сгенерированным пользователям выходить из веб-сайта SilverStripe 4, используя значение по умолчанию from. Выход из системы, потому что вход в систему работает.
Проблема в том, что если зарегистрированный универсальный пользователь пытается выйти, нажав на ссылку, как Security/logout
(так же как Security/logout?BackURL=home/
), он перенаправляется на пустую страницу (только с видимым верхним / нижним колонтитулом, по умолчанию Page.ss
реализовано). Видимо контроллер не работает или похожий, потому что URL указывает мне просто Security/logout
без следующих перенаправлений. Кроме того, сеанс не очищается, и если я вернусь на страницу панели пользователя, она все равно будет авторизована.
Итак, я попытался реализовать собственный аутентификатор, как это обычно делают в SS 3, но заметил некоторые небольшие различия. Затем я последовал как официальному документу, так и предложенному примеру помощи.
Это ситуация:
Пользовательский класс MemberAuthenticator(в MySite/ код)
<?php
// Definizione Namespace
namespace Greylab\Corporate\Authenticator\UtenteAuthenticator;
use SilverStripe\Security\MemberAuthenticator\MemberAuthenticator;
/**
* Classe Autenticazione Utente
*/
class UtenteAuthenticator extends MemberAuthenticator
{
/**
* Login Paziente - Getter
* @param string $link URL di autenteicazione utente
* @return object Form di autenticazione utente
*/
public function getLoginHandler($link)
{
return UtenteLoginHandler::create($link, $this);
}
/**
* Logout Paziente - Getter
* @param string $link URL di deautenteicazione utente
* @return object Form di deautenteicazione utente
*/
public function getLogoutHandler($link)
{
return UtenteLogoutHandler::create($link, $this);
}
}
Пользовательский класс MemberAuthenticator\LoginHandler(в MySite/ код)
<?php
// Definizione Namespace
use SilverStripe\Security\MemberAuthenticator\LoginHandler;
use SilverStripe\Core\Injector\Injector;
/**
* Clesse Login Utente
*/
class UtenteLoginHandler extends LoginHandler
{
/**
* Metodo gestione Login Utente
* Setter
* @param array $dati Dati form login
* @param object $form Form login
* @return void
*/
public function doLogin($dati, $form)
{
$utente = $this->checkLogin($dati);
// Controllo Utente
if ($utente) {
$request = Injector::inst()->get(HTTPRequest::class);
$session = $request->getSession();
$cliente = $session->set('UtenteLoginHandler.MemberID', $utente->ID);
$profiloPaziente = Member::get()->byID($session->get('UtenteLoginHandler.MemberID'));
$datiPaziente = $session->set('UtenteLoginHandler.Data', $dati);
// Controllo Utente
if ($profiloCliente) {
$this->performLogin($profiloCliente, $datiCliente);
return $this->redirectAfterSuccessfulLogin();
} else {
// Se utente invalido torna al form
return $this->redirectBack();
}
} else {
// Se utente invalido torna al form
return $this->redirectBack();
}
}
}
Пользовательский класс MemberAuthenticator\LogoutHandler(в MySite/ код)
// Definizione Namespace
use SilverStripe\Security\MemberAuthenticator\LogoutHandler;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Security\Security;
use SilverStripe\Security\IdentityStore;
use SilverStripe\Security\Member;
use SilverStripe\Control\HTTPResponse;
/**
* Clesse Login Utente
*/
class UtenteLogoutHandler extends LogoutHandler
{
/**
* Metodo gestione Logout Utente
* Setter
* @param array $dati Dati form login
* @param object $form Form login
* @return HTTPResponse
*/
public function doLogOut($utente)
{
// Controllo Utente
if ($utente) {
$request = Injector::inst()->get(HTTPRequest::class);
$session = $request->getSession();
$paziente = $session->get('UtenteLoginHandler.MemberID');
$datiPaziente = $session->get('UtenteLoginHandler.Data');
// Controllo Sessione Utente
if ($paziente && $datiPaziente) {
$session->clear('UtenteLoginHandler.MemberID');
$session->clear('UtenteLoginHandler.Data');
Security::setCurrentUser(null);
return $this->redirectAfterLogout();
// Tried with this approach too without success...
/* if ($utente instanceof Member) {
Injector::inst()->get(IdentityStore::class)->logOut($this->getRequest());
return $this->redirectAfterLogout();
} */
} else {
// Se sessione utente invalida torna al form
return $this->redirectBack();
}
}
}
Инъекция MemberAuthenticator(в _MySite/config / mysite.yml)
SilverStripe\Core\Injector\Injector:
SilverStripe\Security\Security:
properties:
Authenticators:
UtenteAuthenticator: %$Greylab\Corporate\Authenticator\UtenteAuthenticator
С этой реализацией ничего не изменилось.
Кто-нибудь может подсказать мне правильный путь?
Спасибо всем заранее.
1 ответ
После глубокого исследования решение пришло от храброго официального члена Slack Community: особая благодарность @ kinglozzer за это.
Просто SS 4 предлагает совершенно новый $LogoutURL
параметр по умолчанию для получения правильного выхода из системы. Включает вошедшего в систему участника SecurityID
в качестве параметра. Старый СС 3 Security/logout
не достаточно больше, чтобы запустить процесс. Итак, используя:
{$LogoutURL}&BackURL=<url>
Пользователь будет выведен из системы и перенаправлен правильно.
Спасибо всем за помощь.