Drupal access control to custom user profile page

99 views Asked by At

I am trying to add a new tab to a Drupal 7 user profile. Unfortunately, I can't find the right access argument to let the user view the page, but restrict him to view other users' pages by changing the userid in the url.

Currently the admin can access it but not the registered users.

This is the current code :

$items['user/%user/apples'] = array(
    'title' => t('My apples'),
    'type' => MENU_LOCAL_TASK,
    'description' => t('Configure your apples'),
    'access arguments' => array(
      'administer site configuration'
    ),
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'mysite_apples_config_page'
    ),
    'file' => 'mysite.apples.inc'
);

Where can I find an example ?

1

There are 1 answers

1
Muhammad Reda On BEST ANSWER

The only way I see this achievable is by writing a custom access callback logic.

In this callback, you will check if the user has the same uid as the page he is trying to view. If so, grant him access; otherwise, block him.

function my_custom_access_callback($account) {

    global $user;

    // allow admin users
    if(user_access("administer site configuration")) {
        return TRUE;
    }

    // allow the user to view his own page
    if($user->uid == $account->uid) {
        return TRUE;
    }

    // disallow the rest
    return FALSE;
}

In your hook_menu use the new access callback:

$items['user/%user/apples'] = array(
    'title' => t('My apples'),
    'type' => MENU_LOCAL_TASK,
    'description' => t('Configure your apples'),
    'access callback' => 'my_custom_access_callback', // use the new callback.
    'access arguments' => array(1), // use %user as the callback argument.
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'mysite_apples_config_page'
    ),
    'file' => 'mysite.apples.inc'
);