3 namespace Drupal\user\Authentication\Provider;
5 use Drupal\Core\Authentication\AuthenticationProviderInterface;
6 use Drupal\Core\Database\Connection;
7 use Drupal\Core\Session\AccountInterface;
8 use Drupal\Core\Session\UserSession;
9 use Drupal\Core\Session\SessionConfigurationInterface;
10 use Symfony\Component\HttpFoundation\Request;
11 use Symfony\Component\HttpFoundation\Session\SessionInterface;
14 * Cookie based authentication provider.
16 class Cookie implements AuthenticationProviderInterface {
19 * The session configuration.
21 * @var \Drupal\Core\Session\SessionConfigurationInterface
23 protected $sessionConfiguration;
26 * The database connection.
28 * @var \Drupal\Core\Database\Connection
30 protected $connection;
33 * Constructs a new cookie authentication provider.
35 * @param \Drupal\Core\Session\SessionConfigurationInterface $session_configuration
36 * The session configuration.
37 * @param \Drupal\Core\Database\Connection $connection
38 * The database connection.
40 public function __construct(SessionConfigurationInterface $session_configuration, Connection $connection) {
41 $this->sessionConfiguration = $session_configuration;
42 $this->connection = $connection;
48 public function applies(Request $request) {
49 return $request->hasSession() && $this->sessionConfiguration->hasSession($request);
55 public function authenticate(Request $request) {
56 return $this->getUserFromSession($request->getSession());
60 * Returns the UserSession object for the given session.
62 * @param \Symfony\Component\HttpFoundation\Session\SessionInterface $session
65 * @return \Drupal\Core\Session\AccountInterface|null
66 * The UserSession object for the current user, or NULL if this is an
69 protected function getUserFromSession(SessionInterface $session) {
70 if ($uid = $session->get('uid')) {
71 // @todo Load the User entity in SessionHandler so we don't need queries.
72 // @see https://www.drupal.org/node/2345611
73 $values = $this->connection
74 ->query('SELECT * FROM {users_field_data} u WHERE u.uid = :uid AND u.default_langcode = 1', [':uid' => $uid])
77 // Check if the user data was found and the user is active.
78 if (!empty($values) && $values['status'] == 1) {
79 // Add the user's roles.
80 $rids = $this->connection
81 ->query('SELECT roles_target_id FROM {user__roles} WHERE entity_id = :uid', [':uid' => $values['uid']])
83 $values['roles'] = array_merge([AccountInterface::AUTHENTICATED_ROLE], $rids);
85 return new UserSession($values);
89 // This is an anonymous session.