3 namespace Drupal\contact\Access;
5 use Drupal\Core\Access\AccessResult;
6 use Drupal\Core\Config\ConfigFactoryInterface;
7 use Drupal\Core\Routing\Access\AccessInterface;
8 use Drupal\Core\Session\AccountInterface;
9 use Drupal\user\UserDataInterface;
10 use Drupal\user\UserInterface;
13 * Access check for contact_personal_page route.
15 class ContactPageAccess implements AccessInterface {
18 * The contact settings config object.
20 * @var \Drupal\Core\Config\ConfigFactoryInterface
22 protected $configFactory;
25 * The user data service.
27 * @var \Drupal\user\UserDataInterface
32 * Constructs a ContactPageAccess instance.
34 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
36 * @param \Drupal\user\UserDataInterface $user_data
37 * The user data service.
39 public function __construct(ConfigFactoryInterface $config_factory, UserDataInterface $user_data) {
40 $this->configFactory = $config_factory;
41 $this->userData = $user_data;
45 * Checks access to the given user's contact page.
47 * @param \Drupal\user\UserInterface $user
48 * The user being contacted.
49 * @param \Drupal\Core\Session\AccountInterface $account
50 * The currently logged in account.
52 * @return \Drupal\Core\Access\AccessResultInterface
55 public function access(UserInterface $user, AccountInterface $account) {
56 $contact_account = $user;
58 // Anonymous users cannot have contact forms.
59 if ($contact_account->isAnonymous()) {
60 return AccessResult::forbidden();
63 // Users may not contact themselves by default, hence this requires user
64 // granularity for caching.
65 $access = AccessResult::neutral()->cachePerUser();
66 if ($account->id() == $contact_account->id()) {
70 // User administrators should always have access to personal contact forms.
71 $permission_access = AccessResult::allowedIfHasPermission($account, 'administer users');
72 if ($permission_access->isAllowed()) {
73 return $access->orIf($permission_access);
76 // If requested user has been blocked, do not allow users to contact them.
77 $access->addCacheableDependency($contact_account);
78 if ($contact_account->isBlocked()) {
82 // Forbid access if the requested user has disabled their contact form.
83 $account_data = $this->userData->get('contact', $contact_account->id(), 'enabled');
84 if (isset($account_data) && !$account_data) {
88 // If the requested user did not save a preference yet, deny access if the
89 // configured default is disabled.
90 $contact_settings = $this->configFactory->get('contact.settings');
91 $access->cacheUntilConfigurationChanges($contact_settings);
92 if (!isset($account_data) && !$contact_settings->get('user_default_enabled')) {
96 return $access->orIf(AccessResult::allowedIfHasPermission($account, 'access user contact forms'));