0

I'm working on a node access module. I've set up my logic. I can't seem to get my code to return AccessResult::forbidden(). I can't even get \dpm to run in access method. What am I doing wrong? Below are my routing.yml and controller.

/* nodeaccess.routing.yml */
nodeaccess.people:
  path: '/user/{uid}/edit'
  defaults:
    _controller: '\Drupal\nodeaccess\Controller\NodeaccessController::content'
    _title: 'Dashboard'
  requirements:
    _custom_access: '\Drupal\nodeaccess\Controller\NodeaccessController::access'

/* src/Controller/NodeAccessController.php */

<?php

namespace Drupal\nodeaccess\Controller;

use Drupal\Core\Access\AccessResult; 
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountInterface;

/**
 * Defines the Dashboard controller.
 */
class NodeaccessController extends ControllerBase {

 /**
  * Returns content for this controller.
  */
 public function content() {
   $today = date("l");
   if ($today == "Thursday") {
     // Return 403 Access Denied page.  
     \dpm("You are not allowed.");
   }
 }

 /**
  * Checks access for this controller.
  */
 public function access(AccountInterface $account) {
  $current_user = User::load(Drupal::currentUser()->id());
  $user = User::load(explode("/", $_SERVER["REQUEST_URI"])[1]);
  if ($current_user->field_department->target_id != $user->field_department->target_id) {
    return AccessResult::forbidden();
  }
  return AccessResult::allowed();
  }
}
3
  • You have the user available in the method if you pass it as a parameter, AccountInterface $account
    – user72672
    Commented Jun 15, 2019 at 7:02
  • I'm not sure if it is actually an issue, but in the nodeacess.routing.yml file, the _custom_access is incorrectly indented. Also, check this drupal.org/docs/8/api/routing-system/access-checking-on-routes/… Commented Jun 15, 2019 at 7:42
  • I've made the suggested changes, no dice.
    – Kartagis
    Commented Jun 15, 2019 at 8:20

1 Answer 1

0

There is a syntax error here Drupal::currentUser()->id() should be \Drupal::currentUser()->id() and also explode("/", $_SERVER["REQUEST_URI"])[2] gives you only people not the user id, to use User::load.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.