本文整理汇总了PHP中Drupal\Core\Session\AccountInterface::isAuthenticated方法的典型用法代码示例。如果您正苦于以下问题:PHP AccountInterface::isAuthenticated方法的具体用法?PHP AccountInterface::isAuthenticated怎么用?PHP AccountInterface::isAuthenticated使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal\Core\Session\AccountInterface
的用法示例。
在下文中一共展示了AccountInterface::isAuthenticated方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: view
/**
* {@inheritdoc}
*/
public function view(EntityInterface $node, $view_mode = 'full', $langcode = NULL)
{
$build = parent::view($node, $view_mode, $langcode);
foreach ($node->uriRelationships() as $rel) {
$url = $node->toUrl($rel);
// Add link relationships if the user is authenticated or if the anonymous
// user has access. Access checking must be done for anonymous users to
// avoid traffic to inaccessible pages from web crawlers. For
// authenticated users, showing the links in HTML head does not impact
// user experience or security, since the routes are access checked when
// visited and only visible via view source. This prevents doing
// potentially expensive and hard to cache access checks on every request.
// This means that the page will vary by user.permissions. We also rely on
// the access checking fallback to ensure the correct cacheability
// metadata if we have to check access.
if ($this->currentUser->isAuthenticated() || $url->access($this->currentUser)) {
// Set the node path as the canonical URL to prevent duplicate content.
$build['#attached']['html_head_link'][] = array(array('rel' => $rel, 'href' => $url->toString()), TRUE);
}
if ($rel == 'canonical') {
// Set the non-aliased canonical path as a default shortlink.
$build['#attached']['html_head_link'][] = array(array('rel' => 'shortlink', 'href' => $url->setOption('alias', TRUE)->toString()), TRUE);
}
}
// Given this varies by $this->currentUser->isAuthenticated(), add a cache
// context based on the anonymous role.
$build['#cache']['contexts'][] = 'user.roles:anonymous';
return $build;
}
示例2: onRespond
/**
* Redirects login attempts on already-logged-in session to the destination.
*/
public function onRespond(FilterResponseEvent $event)
{
// Return early in most cases.
if ($event->getRequest()->getMethod() !== 'POST') {
return;
}
if (!$this->currentUser->isAuthenticated()) {
return;
}
if (!$event->isMasterRequest()) {
return;
}
if (!$event->getRequest()->query->has('destination')) {
return;
}
if ($event->getResponse() instanceof RedirectResponse) {
return;
}
// There has to be a better way to figure out if we landed on the 403/404 page.
$page_403 = $this->configFactory->get('system.site')->get('page.403');
$page_404 = $this->configFactory->get('system.site')->get('page.404');
$path = $this->currentPath->getPath();
$route = $this->currentRouteMatch->getRouteName();
if ($route == 'system.403' || $page_403 && $path == $page_403 || $route == 'system.404' || $page_404 && $path == $page_404) {
// RedirectResponseSubscriber will convert to absolute URL for us.
$event->setResponse(new RedirectResponse($this->redirectDestination->get(), RedirectResponse::HTTP_SEE_OTHER));
}
}
示例3: onKernelRequestMaintenance
/**
* Determine whether the page is configured to be offline.
*
* @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
* The event to process.
*/
public function onKernelRequestMaintenance(GetResponseEvent $event)
{
$request = $event->getRequest();
$route_match = RouteMatch::createFromRequest($request);
$path = $request->attributes->get('_system_path');
if ($this->maintenanceMode->applies($route_match)) {
// If the site is offline, log out unprivileged users.
if ($this->account->isAuthenticated() && !$this->maintenanceMode->exempt($this->account)) {
user_logout();
// Redirect to homepage.
$event->setResponse(new RedirectResponse($this->url('<front>', [], ['absolute' => TRUE])));
return;
}
if ($this->account->isAnonymous() && $path == 'user') {
// Forward anonymous user to login page.
$event->setResponse(new RedirectResponse($this->url('user.login', [], ['absolute' => TRUE])));
return;
}
}
if ($this->account->isAuthenticated()) {
if ($path == 'user/login') {
// If user is logged in, redirect to 'user' instead of giving 403.
$event->setResponse(new RedirectResponse($this->url('user.page', [], ['absolute' => TRUE])));
return;
}
if ($path == 'user/register') {
// Authenticated user should be redirected to user edit page.
$event->setResponse(new RedirectResponse($this->url('entity.user.edit_form', ['user' => $this->account->id()], ['absolute' => TRUE])));
return;
}
}
}
示例4: onKernelRequestMaintenance
/**
* Determine whether the page is configured to be offline.
*
* @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
* The event to process.
*/
public function onKernelRequestMaintenance(GetResponseEvent $event)
{
$request = $event->getRequest();
$route_match = RouteMatch::createFromRequest($request);
$path = $request->attributes->get('_system_path');
if ($this->maintenanceMode->applies($route_match)) {
// If the site is offline, log out unprivileged users.
if ($this->account->isAuthenticated() && !$this->maintenanceMode->exempt($this->account)) {
user_logout();
// Redirect to homepage.
$event->setResponse(new RedirectResponse($this->url('<front>', [], ['absolute' => TRUE])));
return;
}
}
if ($this->account->isAuthenticated()) {
if ($path == 'user/login') {
// If the user is already logged in, redirect to their profile page.
$event->setResponse($this->redirect('entity.user.canonical', ['user' => $this->account->id()]));
return;
}
if ($path == 'user/register') {
// If the user is already registered, redirect to their edit page.
$event->setResponse(new RedirectResponse($this->url('entity.user.edit_form', ['user' => $this->account->id()], ['absolute' => TRUE])));
return;
}
}
}
示例5: getRouteName
/**
* {@inheritdoc}
*/
public function getRouteName()
{
if ($this->currentUser->isAuthenticated()) {
return 'user.logout';
} else {
return 'user.login';
}
}
示例6: onKernelTerminate
/**
* Updates the current user's last access time.
*
* @param \Symfony\Component\HttpKernel\Event\PostResponseEvent $event
* The event to process.
*/
public function onKernelTerminate(PostResponseEvent $event)
{
if ($this->account->isAuthenticated() && REQUEST_TIME - $this->account->getLastAccessedTime() > Settings::get('session_write_interval', 180)) {
// Do that no more than once per 180 seconds.
/** @var \Drupal\user\UserStorageInterface $storage */
$storage = $this->entityManager->getStorage('user');
$storage->updateLastAccessTimestamp($this->account, REQUEST_TIME);
}
}
示例7: onException
/**
* Redirects anonymous users from user.page to user.login.
*
* @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
* The event to process.
*/
public function onException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if ($exception instanceof AccessDeniedHttpException) {
$route_name = RouteMatch::createFromRequest($event->getRequest())->getRouteName();
if ($route_name == 'user.page' && !$this->account->isAuthenticated()) {
$event->setResponse($this->redirect('user.login'));
}
}
}
示例8: onKernelRequestMaintenance
/**
* Logout users if site is in maintenance mode.
*
* @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
* The event to process.
*/
public function onKernelRequestMaintenance(GetResponseEvent $event)
{
$request = $event->getRequest();
$route_match = RouteMatch::createFromRequest($request);
if ($this->maintenanceMode->applies($route_match)) {
// If the site is offline, log out unprivileged users.
if ($this->account->isAuthenticated() && !$this->maintenanceMode->exempt($this->account)) {
user_logout();
// Redirect to homepage.
$event->setResponse($this->redirect($this->url('<front>')));
}
}
}
示例9: onResponse
/**
* Sets the 'is-active' class on links.
*
* @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
* The response event.
*/
public function onResponse(FilterResponseEvent $event)
{
// Only care about HTML responses.
if (stripos($event->getResponse()->headers->get('Content-Type'), 'text/html') === FALSE) {
return;
}
// For authenticated users, the 'is-active' class is set in JavaScript.
// @see system_page_attachments()
if ($this->currentUser->isAuthenticated()) {
return;
}
$response = $event->getResponse();
$response->setContent(static::setLinkActiveClass($response->getContent(), ltrim($this->currentPath->getPath(), '/'), $this->pathMatcher->isFrontPage(), $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_URL)->getId(), $event->getRequest()->query->all()));
}
示例10: handle
/**
* The entry point for our subscriber.
*
* @param GetResponseEvent $event
* The response event from the kernel.
*/
public function handle(GetResponseEvent $event)
{
// Don't do anything if this is a sub request and not a master request.
if ($event->getRequestType() != HttpKernelInterface::MASTER_REQUEST) {
return;
}
// Nothing to do if the user is already logged in.
if ($this->currentUser->isAuthenticated()) {
return;
}
// Some routes we don't want to run on.
if ($this->isIgnoreableRoute()) {
return;
}
// The service controller may have indicated that this current request
// should not be automatically sent to CAS for authentication checking.
// This is to prevent infinite redirect loops.
$session = $this->requestStack->getCurrentRequest()->getSession();
if ($session->has('cas_temp_disable_auto_auth')) {
$session->remove('cas_temp_disable_auto_auth');
$this->casHelper->log("Temp disable flag set, skipping CAS subscriber.");
return;
}
// Check to see if we should require a forced login. It will set a response
// on the event if so.
if ($this->handleForcedPath($event)) {
return;
}
// Check to see if we should initiate a gateway auth check. It will set a
// response on the event if so.
$this->handleGateway($event);
}
示例11: setCache
/**
* {@inheritdoc}
*/
public function setCache($form_build_id, $form, FormStateInterface $form_state)
{
// 6 hours cache life time for forms should be plenty.
$expire = 21600;
// Ensure that the form build_id embedded in the form structure is the same
// as the one passed in as a parameter. This is an additional safety measure
// to prevent legacy code operating directly with
// \Drupal::formBuilder()->getCache() and \Drupal::formBuilder()->setCache()
// from accidentally overwriting immutable form state.
if (isset($form['#build_id']) && $form['#build_id'] != $form_build_id) {
$this->logger->error('Form build-id mismatch detected while attempting to store a form in the cache.');
return;
}
// Cache form structure.
if (isset($form)) {
if ($this->currentUser->isAuthenticated()) {
$form['#cache_token'] = $this->csrfToken->get();
}
unset($form['#build_id_old']);
$this->keyValueExpirableFactory->get('form')->setWithExpire($form_build_id, $form, $expire);
}
// Cache form state.
if ($this->configFactory->get('system.performance')->get('cache.page.use_internal') && $this->isPageCacheable()) {
$form_state->addBuildInfo('immutable', TRUE);
}
// Store the known list of safe strings for form re-use.
// @todo Ensure we are not storing an excessively large string list in:
// https://www.drupal.org/node/2295823
$form_state->addBuildInfo('safe_strings', SafeMarkup::getAll());
if ($data = $form_state->getCacheableArray()) {
$this->keyValueExpirableFactory->get('form_state')->setWithExpire($form_build_id, $data, $expire);
}
}
示例12: setCache
/**
* {@inheritdoc}
*/
public function setCache($form_build_id, $form, FormStateInterface $form_state)
{
// 6 hours cache life time for forms should be plenty.
$expire = 21600;
// Ensure that the form build_id embedded in the form structure is the same
// as the one passed in as a parameter. This is an additional safety measure
// to prevent legacy code operating directly with
// \Drupal::formBuilder()->getCache() and \Drupal::formBuilder()->setCache()
// from accidentally overwriting immutable form state.
if (isset($form['#build_id']) && $form['#build_id'] != $form_build_id) {
$this->logger->error('Form build-id mismatch detected while attempting to store a form in the cache.');
return;
}
// Cache form structure.
if (isset($form)) {
if ($this->currentUser->isAuthenticated()) {
$form['#cache_token'] = $this->csrfToken->get();
}
unset($form['#build_id_old']);
$this->keyValueExpirableFactory->get('form')->setWithExpire($form_build_id, $form, $expire);
}
if ($data = $form_state->getCacheableArray()) {
$this->keyValueExpirableFactory->get('form_state')->setWithExpire($form_build_id, $data, $expire);
}
}
示例13: handle
/**
* The entry point for our subscriber.
*
* @param GetResponseEvent $event
* The response event from the kernel.
*/
public function handle(GetResponseEvent $event)
{
// Don't do anything if this is a sub request and not a master request.
if ($event->getRequestType() != HttpKernelInterface::MASTER_REQUEST) {
return;
}
// Nothing to do if the user is already logged in.
if ($this->currentUser->isAuthenticated()) {
return;
}
// Some routes we don't want to run on.
if ($this->isIgnoreableRoute()) {
return;
}
// Don't do anything if this is a request from cron, drush, crawler, etc.
if ($this->isNotNormalRequest()) {
return;
}
// The service controller may have indicated that this current request
// should not be automatically sent to CAS for authentication checking.
// This is to prevent infinite redirect loops.
if (isset($_SESSION['cas_temp_disable'])) {
unset($_SESSION['cas_temp_disable']);
$this->casHelper->log("Temp disable flag set. Skip processing this request.");
return;
}
// Check to see if we should require a forced login. It will set a response
// on the event if so.
if ($this->handleForcedPath($event)) {
return;
}
// Check to see if we should initiate a gateway auth check. It will set a
// response on the event if so.
$this->handleGateway($event);
}
示例14: getCountNewComments
/**
* {@inheritdoc}
*/
public function getCountNewComments(EntityInterface $entity, $field_name = NULL, $timestamp = 0)
{
// @todo Replace module handler with optional history service injection
// after http://drupal.org/node/2081585
if ($this->currentUser->isAuthenticated() && $this->moduleHandler->moduleExists('history')) {
// Retrieve the timestamp at which the current user last viewed this entity.
if (!$timestamp) {
if ($entity->getEntityTypeId() == 'node') {
$timestamp = history_read($entity->id());
} else {
$function = $entity->getEntityTypeId() . '_last_viewed';
if (function_exists($function)) {
$timestamp = $function($entity->id());
} else {
// Default to 30 days ago.
// @todo Remove once http://drupal.org/node/1029708 lands.
$timestamp = COMMENT_NEW_LIMIT;
}
}
}
$timestamp = $timestamp > HISTORY_READ_LIMIT ? $timestamp : HISTORY_READ_LIMIT;
// Use the timestamp to retrieve the number of new comments.
$query = $this->queryFactory->get('comment')->condition('entity_type', $entity->getEntityTypeId())->condition('entity_id', $entity->id())->condition('created', $timestamp, '>')->condition('status', CommentInterface::PUBLISHED);
if ($field_name) {
// Limit to a particular field.
$query->condition('field_name', $field_name);
}
return $query->count()->execute();
}
return FALSE;
}
示例15: collect
/**
* {@inheritdoc}
*/
public function collect(Request $request, Response $response, \Exception $exception = NULL)
{
$this->data['name'] = $this->currentUser->getDisplayName();
$this->data['authenticated'] = $this->currentUser->isAuthenticated();
$this->data['roles'] = [];
$storage = $this->entityManager->getStorage('user_role');
foreach ($this->currentUser->getRoles() as $role) {
$entity = $storage->load($role);
$this->data['roles'][] = $entity->label();
}
foreach ($this->providerCollector->getSortedProviders() as $provider_id => $provider) {
if ($provider->applies($request)) {
$this->data['provider'] = $provider_id;
}
}
$this->data['anonymous'] = $this->configFactory->get('user.settings')->get('anonymous');
}