Our Blog

Controlling Access to Your Node according to User’s Role/ID in Drupal

Need to control which users can access a node/page of a particular content type on your Drupal site?

The Drupal Node API provides us a quick way to do this. It provides the hook_nodeapi function to react to the actions affecting all kinds of nodes. We can easily implement this hook in our module or theme. A prototype of this hook looks like this:

function myCustomModuleName_nodeapi (&$node, $op) {

/*Your code and conditions here*/

}

Here myCustomModuleName is the name of the module in which this hook is defined. The two parameters are $node, which represents the node on which the action is being performed and the other one $op,  is the kind of action which is being performed. The $op can have values like view, alter, delete, print and so on…

As an example, I was looking to design such a condition for my website:

  • If enrolled user creates content type for "recipe", restrict access to recipe except for node author and admin.

So, I needed to develop a mechanism through which for each node of type “recipe”:

  • Everyone can see nodes created by admin including Anonymous user.
  • Only site admin and node author can see nodes created by users other than administrator.


I created a custom module for and used the nodeapi hook to implement the mechanism as follows:

—————————————————– ————————————————–

function custom_hook_implements_nodeapi (&$node, $op)

{

global $user;

if(($node->type == ‘recipe’ and $op == ‘view’))

{

$author=user_load($node->uid);

if(!array_key_exists(3,$author->roles) and $author->uid!=$user->uid and !array_key_exists(3,$user->roles))

{

drupal_access_denied();

}

}

}

—————————————————– ————————————————–

As you can easily observe here that I have only created an if condition that first checks, if the node type is “recipe” and operation performed is “view“. Thereafter, if conditions are found to be true, it further checks for the following:

– if the author of the node is NOT an administrator user (3 being the role ID of administrator user).

– if the author of the node is NOT the user accessing the node himself.

– Finally, the user accessing the node is not an administrator user himself.

 

If these conditions are met, it shows the drupal access denied error message, thus, denying the user access to that node.