View source
<?php
namespace Drupal\ldap_sso\Controller;
use Drupal\Component\Utility\Html;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\Core\Session\AccountInterface;
use Drupal\ldap_authentication\Controller\LoginValidator;
use Drupal\ldap_servers\Logger\LdapDetailLog;
use Drupal\ldap_sso\RedirectResponseWithCookie;
use Drupal\user\UserInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
class LoginController extends ControllerBase {
protected $request;
protected $detailLog;
protected $config;
protected $logger;
protected $validator;
protected $account;
public function __construct(LoggerInterface $logger, ConfigFactory $configFactory, LoginValidator $validator, LdapDetailLog $detailLog, AccountInterface $account) {
$this->logger = $logger;
$this->config = $configFactory
->get('ldap_sso.settings');
$this->validator = $validator;
$this->detailLog = $detailLog;
$this->account = $account;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('logger.channel.ldap_sso'), $container
->get('config.factory'), $container
->get('ldap_authentication.login_validator'), $container
->get('ldap.detail_log'), $container
->get('current_user'));
}
public function login(Request $request) {
$this->detailLog
->log('Beginning SSO login.', [], 'ldap_sso');
$remote_user = FALSE;
$realm = NULL;
if (isset($_SERVER[$this->config
->get('ssoVariable')])) {
$remote_user = $_SERVER[$this->config
->get('ssoVariable')];
}
if ($this->config
->get('ssoSplitUserRealm')) {
list($remote_user, $realm) = $this
->splitUserNameRealm($remote_user);
}
$this->detailLog
->log('SSO raw result is username=@remote_user, (realm=@realm).', [
'@remote_user' => $remote_user,
'@realm' => $realm,
], 'ldap_sso');
if ($remote_user) {
$this->detailLog
->log('User found, logging in.', [], 'ldap_sso');
$this
->loginRemoteUser($remote_user, $realm);
$destination = $request->query
->get('destination', NULL);
if ($destination == NULL) {
$finalDestination = Url::fromRoute('<front>');
}
else {
$finalDestination = Url::fromUserInput($destination);
}
}
else {
$this->detailLog
->log('User missing.', [], 'ldap_sso');
$this
->remoteUserMissing();
$finalDestination = Url::fromRoute('user.login');
}
$cookies[] = new Cookie('sso_login_running', '', REQUEST_TIME - 3600, base_path());
return new RedirectResponseWithCookie($finalDestination
->toString(), 302, $cookies);
}
public function access() {
if ($this->account
->isAnonymous()) {
return AccessResult::allowed();
}
else {
return AccessResult::forbidden();
}
}
private function loginRemoteUser($remote_user, $realm) {
if ($this->config
->get('ssoRemoteUserStripDomainName')) {
$remote_user = $this
->stripDomainName($remote_user);
}
$this->detailLog
->log('Continuing SSO login with username=@remote_user, (realm=@realm).', [
'@remote_user' => $remote_user,
'@realm' => $realm,
], 'ldap_sso');
$user = $this
->validateUser($remote_user);
if ($user && !$user
->isAnonymous()) {
$this
->loginUserSetFinalize($user);
}
else {
$this
->loginUserNotSetFinalize();
}
}
private function validateUser($remote_user) {
$this->detailLog
->log('Starting validation for SSO user.', [], 'ldap_sso');
$authentication_successful = $this->validator
->processSsoLogin(Html::escape($remote_user));
if ($authentication_successful) {
$this->detailLog
->log('Remote user has local uid @uid', [
'@uid' => $this->validator
->getDrupalUser()
->id(),
], 'ldap_sso');
return $this->validator
->getDrupalUser();
}
else {
$this->detailLog
->log('Remote user not valid.', [], 'ldap_sso');
return FALSE;
}
}
private function getCookieLifeTime() {
if ($this->config
->get('cookieExpire')) {
$cookie_lifetime = 0;
}
else {
$cookie_lifetime = REQUEST_TIME - 3600;
}
return $cookie_lifetime;
}
private function loginUserNotSetFinalize() {
$this->detailLog
->log('User not found, SSO aborted.', [], 'ldap_sso');
setcookie('sso_stop', 'true', $this
->getCookieLifeTime(), base_path(), '');
$this
->messenger()
->addError($this
->t('Sorry, your LDAP credentials were not found or the LDAP server is not available. You may log in with other credentials on the %user_login_form.', [
'%user_login_form' => Link::fromTextAndUrl('login form', Url::fromRoute('user.login'))
->toString(),
]));
$this->detailLog
->log('User not found or server error, redirecting to front page', [], 'ldap_sso');
}
private function loginUserSetFinalize(UserInterface $account) {
$this->detailLog
->log('Success with SSO login', [], 'ldap_sso');
user_login_finalize($account);
if ($this->config
->get('enableLoginConfirmationMessage')) {
$this
->messenger()
->addStatus($this
->t('You have been successfully authenticated'));
}
$this->detailLog
->log('Login successful, redirecting to front page.', [], 'ldap_sso');
}
private function remoteUserMissing() {
$this->logger
->debug('$_SERVER[\'@variable\'] not found', [
'@variable' => $this->config
->get('ssoVariable'),
]);
$this->detailLog
->log('Authentication failure, redirecting to login', [], 'ldap_sso');
setcookie('sso_stop', 'true', $this
->getCookieLifeTime(), base_path(), 0);
$this
->messenger()
->addError($this
->t('You were not authenticated by the server. You may log in with your credentials below.'));
}
private function stripDomainName($remote_user) {
$domain = NULL;
$exploded = preg_split('/[\\@\\\\]/', $remote_user);
if (count($exploded) == 2) {
if (strpos($remote_user, '@') !== FALSE) {
$remote_user = $exploded[0];
$domain = $exploded[1];
}
else {
$domain = $exploded[0];
$remote_user = $exploded[1];
}
$this->detailLog
->log('Domain stripped: remote_user=@remote_user, domain=@domain', [
'@remote_user' => $remote_user,
'@domain' => $domain,
], 'ldap_sso');
}
return $remote_user;
}
protected function splitUserNameRealm($remote_user) {
$realm = NULL;
$domainMatch = preg_match('/^([A-Za-z0-9_\\-\\.]+)@([A-Za-z0-9_\\-.]+)$/', $remote_user, $matches);
if ($remote_user && $domainMatch) {
$remote_user = $matches[1];
$realm = $matches[2];
}
return [
$remote_user,
$realm,
];
}
}