2

I want to restrict my page access. Only an administrator should be able to see the page.

I followed this tutorial

function example_menu() {
  $items['example'] = array(
    'title' => 'My Page',
    'page callback' => 'example_custom_page',
    'access callback' => 'example_user_has_role',
    'access arguments' => array(1, array('adminstrator')), // Argument 1 loads the user, argument 2 is the role name.
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}


function check_user_has_role($user, $roles = array()) {
    foreach ($roles as $role) {
        if (in_array($role, $user->roles)) {
            return TRUE;
        }
    }
    return FALSE;
}

But I was able to access the URL even after I logged out. What is my mistake or is there a better way to achieve this?

2 Answers 2

3

I think the name of your access callback is wrong. (example_user_has_role => check_user_has_role). Also, you made a mistake on the role name (adminstrator => administrator).

Anyway, you can achieve this in a more simple way like this (avoiding the argument in the URL)

function example_menu() {
  $items['example'] = array(
    'title' => 'My Page',
    'page callback' => 'example_custom_page',
    'access callback' => 'check_user_has_role',
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}


function check_user_has_role() {
  global $user;
  if (in_array('administrator', $user->roles)) {
    return TRUE;
  }
  return FALSE;
}
4
  • :-) lets find the other 50%
    – pbonnefoi
    Feb 12, 2015 at 14:12
  • My answer is the other 50%. o_Ô Feb 12, 2015 at 14:14
  • I'm thinking now that without any arguments, passing 1 in the access arguments will not lead to any substitution, so uid will always be 1. The access test will always then run for admin account, and not for logged in user. Feb 12, 2015 at 14:20
  • Actually, I simplified the code above and it works just fine. No need of arguments.
    – pbonnefoi
    Feb 12, 2015 at 14:21
2

You did not follow the example as is.

The example uses auto loading, as in:

$items['example/%user']

Your path does not, hence your issue.

Just drop the $user as parameter to the access callback and arguments, and get the pseudo user object by using:

global $user
2
  • still learning drupal , I was wondering about that too but I dont know about auto loading ..can u explain little bit more !!! thanks!!!! I am thankful for both the answers , both gave me something new to learn :)
    – Hitesh
    Feb 13, 2015 at 4:40
  • hook_menu Feb 13, 2015 at 4:59

Your Answer

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

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