BasicAuth.php in Zircon Profile 8
File
core/modules/basic_auth/src/Authentication/Provider/BasicAuth.php
View source
<?php
namespace Drupal\basic_auth\Authentication\Provider;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Core\Authentication\AuthenticationProviderInterface;
use Drupal\Core\Authentication\AuthenticationProviderChallengeInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Flood\FloodInterface;
use Drupal\user\UserAuthInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
class BasicAuth implements AuthenticationProviderInterface, AuthenticationProviderChallengeInterface {
protected $configFactory;
protected $userAuth;
protected $flood;
protected $entityManager;
public function __construct(ConfigFactoryInterface $config_factory, UserAuthInterface $user_auth, FloodInterface $flood, EntityManagerInterface $entity_manager) {
$this->configFactory = $config_factory;
$this->userAuth = $user_auth;
$this->flood = $flood;
$this->entityManager = $entity_manager;
}
public function applies(Request $request) {
$username = $request->headers
->get('PHP_AUTH_USER');
$password = $request->headers
->get('PHP_AUTH_PW');
return isset($username) && isset($password);
}
public function authenticate(Request $request) {
$flood_config = $this->configFactory
->get('user.flood');
$username = $request->headers
->get('PHP_AUTH_USER');
$password = $request->headers
->get('PHP_AUTH_PW');
if ($this->flood
->isAllowed('basic_auth.failed_login_ip', $flood_config
->get('ip_limit'), $flood_config
->get('ip_window'))) {
$accounts = $this->entityManager
->getStorage('user')
->loadByProperties(array(
'name' => $username,
'status' => 1,
));
$account = reset($accounts);
if ($account) {
if ($flood_config
->get('uid_only')) {
$identifier = $account
->id();
}
else {
$identifier = $account
->id() . '-' . $request
->getClientIP();
}
if ($this->flood
->isAllowed('basic_auth.failed_login_user', $flood_config
->get('user_limit'), $flood_config
->get('user_window'), $identifier)) {
$uid = $this->userAuth
->authenticate($username, $password);
if ($uid) {
$this->flood
->clear('basic_auth.failed_login_user', $identifier);
return $this->entityManager
->getStorage('user')
->load($uid);
}
else {
$this->flood
->register('basic_auth.failed_login_user', $flood_config
->get('user_window'), $identifier);
}
}
}
}
$this->flood
->register('basic_auth.failed_login_ip', $flood_config
->get('ip_window'));
return [];
}
public function challengeException(Request $request, \Exception $previous) {
$site_name = $this->configFactory
->get('system.site')
->get('name');
$challenge = SafeMarkup::format('Basic realm="@realm"', array(
'@realm' => !empty($site_name) ? $site_name : 'Access restricted',
));
return new UnauthorizedHttpException((string) $challenge, 'No authentication credentials provided.', $previous);
}
}