AuthenticationLinkProvider.php in JSON:API Hypermedia 8
File
examples/Plugin/jsonapi_hypermedia/LinkProvider/AuthenticationLinkProvider.php
View source
<?php
namespace Drupal\jsonapi_hypermedia\Plugin\jsonapi_hypermedia\LinkProvider;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\jsonapi\JsonApiResource\JsonApiDocumentTopLevel;
use Drupal\jsonapi_hypermedia\AccessRestrictedLink;
use Drupal\jsonapi_hypermedia\Plugin\LinkProviderBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
final class AuthenticationLinkProvider extends LinkProviderBase implements ContainerFactoryPluginInterface {
protected $currentUser;
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$provider = new static($configuration, $plugin_id, $plugin_definition);
$provider
->setCurrentUser($container
->get('current_user'));
return $provider;
}
public function setCurrentUser(AccountInterface $current_user) {
$this->currentUser = $current_user;
}
public function getLinkRelationType() {
return $this->currentUser
->isAuthenticated() ? 'logout' : 'authenticate';
}
public function getLink($context) {
assert($context instanceof JsonApiDocumentTopLevel);
$is_authenticated = $this->currentUser
->isAuthenticated();
$route_name = !$is_authenticated ? 'user.login.http' : 'user.logout.http';
$login_url = Url::fromUri($route_name, [
'query' => [
'_format' => 'json',
],
]);
$link_cacheability = new CacheableMetadata();
$link_cacheability
->addCacheContexts([
'session.exists',
'user.roles:anonymous',
]);
return AccessRestrictedLink::createLink(AccessResult::allowed(), $link_cacheability, $login_url, $this
->getLinkRelationType(), [
'type' => 'application/json',
]);
}
}