Patrick
Patrick

Reputation: 3440

How to target specific content types in Drupal 6 with hook_menu_alter()

I am trying to target a specific content type so that any time an anonymous user tries to access the content type's page it will give them a not authorized message. To do this I think I need to use hook_menu_alter() and add an access callback to it. (This is a Drupal 6 site).

The problem I am having is that I don't really know how to identify to the menu system the nodes of that content type. I know that the generated URL looks something like this "name-and-biography/name-and-biography-%username". So I tried that and a few other combinations and cannot seem to get it to work.

I tried this essentially:

function mysite_profile_menu_alter(&$items) {
  //Restrict access to profile pages
  $items['name-and-biography/%title']['access callback'] = 'mysite_profile_content_access';
}


function mysite_profile_content_access() {
  //Check to make sure they are an authenticated user
  GLOBAL $user;

  foreach ($user->roles as $role) {
    if ($role == 'authenticated user') {
      return TRUE;
    }
  }

  return FALSE;
}

I have also tried the item path like this "name-and-biography/%" and "name-and-biography/*". It doesn't seem to be working. The URL aliases default for this are set to "[type-name]/[title-raw]". And the title generation is set to "[type-name] - ([author-name])".

I also tried using hook_access(), but that doesn't seem to be running. Even after flushing all cache multiple times. Neither option seems to be.

Does anyone have any ideas as to how I need to target this in my hook_menu_alter()? Or get the hook_access() to work? Or any other ideas? I did try the content access module, but it creates problems on our site. So another option would be preferred.

Thanks!

Upvotes: 0

Views: 421

Answers (2)

scronide
scronide

Reputation: 12238

Implement hook_nodeapi() to check for access on view:

/**
 * Implementation of hook_nodeapi().
 */
function MODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  global $user;

  switch ($op) {
    case 'view':
      if ($node->type == 'CONTENT_TYPE' && $user->uid < 1) {
        drupal_access_denied();
        exit;
      }
      break;
  }
}

Upvotes: 1

AKS
AKS

Reputation: 4658

hook_menu_alter is all about altering existing items (paths such as /admin, /node/%, admin/reports/status, etc). If you want to add a new menu item, use hook_menu() instead. Also, you don't have an page callback defined so this is not a valid hook_menu() either.

Usually to introduce a new permission level, we use hook_perm() to add new permission item. So you don't have to hardcode which roles are allowed to access content. You can also try Content Access module.

See http://drupalcode.org/project/examples.git/blob/refs/heads/6.x-1.x:/node_access_example/node_access_example.module which is a great example for node access.

Upvotes: 0

Related Questions