View source
<?php
namespace Drupal\login_history\Plugin\Block;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\AccountProxy;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class LastLoginBlock extends BlockBase implements ContainerFactoryPluginInterface {
protected $currentUser;
protected $requestStack;
public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxy $currentUser, RequestStack $requestStack) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->currentUser = $currentUser;
$this->requestStack = $requestStack;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('current_user'), $container
->get('request_stack'));
}
public function blockAccess(AccountInterface $account) {
return AccessResult::allowedIf($account
->isAuthenticated());
}
public function build() {
$build = [];
$last_login = FALSE;
if (!$this->currentUser
->isAnonymous()) {
$last_login = \Drupal::database()
->select('login_history', 'lh')
->fields('lh', [
'login',
'hostname',
'one_time',
'user_agent',
])
->condition('uid', $this->currentUser
->id())
->orderBy('login', 'DESC')
->range(1, 1)
->execute()
->fetch();
}
if ($last_login) {
$request = $this->requestStack
->getCurrentRequest();
$hostname = $last_login->hostname == $request
->getClientIP() ? $this
->t('this IP address') : $last_login->hostname;
$user_agent = $last_login->user_agent == $request->server
->get('HTTP_USER_AGENT') ? $this
->t('this browser') : $last_login->user_agent;
$build['last_login']['#markup'] = '<p>' . $this
->t('You last logged in from @hostname using @user_agent.', [
'@hostname' => $hostname,
'@user_agent' => $user_agent,
]) . '</p>';
if ($this->currentUser
->hasPermission('view own login history')) {
$build['view_report'] = [
'#type' => 'more_link',
'#title' => $this
->t('View your login history'),
'#url' => Url::fromRoute('login_history.user_report', [
'user' => $this->currentUser
->id(),
]),
];
}
}
$build['#cache'] = [
'contexts' => [
'session',
],
];
return $build;
}
}