WorkHabit Blogs

WORKHABIT LABS

Checking node_access through the API

by Adam Kalsey Published: November 6th, 2008
Tagged: access control, Deane Barker, drupal, gadgetopia

Deane Barker at Gadgetopia asked about how to access the content access APIs for different CMSs. He emailed me to find out if I might be able provide an example for Drupal.

If I get a list of content IDs, I should be able to “strain” them through some API call on the CMS, and get back a list of IDs the current user is allowed to see.

What if you could say —

Hey, CMS, I have this list of content IDs here… How did I get them? Yeah, well, that’s not that important right now…

Anyway, can you look at this and tell me which ones I can show Nathaniel Snerpis? Here, just take them all, and give me back the ones I can show him.

Here's some sample code to do this. It's untested, but the code is simple enough you should be able to figure out any issues that arise.

  1. <?php
  2.  
  3. // By default, Drupal's node access works on the current user.
  4. // If you want to determine access for an arbitrary user, you
  5. // have to fetch the user object for that user first. Here we
  6. // fetch the user having the email address foo@bar.com.
  7.  
  8. $user = user_load(array('email'=>'foo@bar.com'));
  9.  
  10. $node_ids = array(1,2,5,13,12938345);
  11. foreach ($node_ids as $nid) {
  12.   // Fetch the full node. Drupal has some special cases
  13.   // that can't be determined just from the content id.
  14.   // For instance, a node's author can always view their
  15.   // own node.
  16.   $node = node_load($nid);
  17.   if (node_access('view', $node, $user)) {
  18.     // You have access. Do stuff.
  19.   }
  20.   // You can also check to see if the user has access to
  21.   // create, update, or delete a node instead of simply
  22.   // "view".
  23.   //
  24.   // If you want to check permissions for the current user,
  25.   // you can omit the user_load step above and change the
  26.   // node_access call to node_access('view', $node).
  27. }
  28. ?>

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote> <h3>
  • You can use Markdown syntax to format and style the text.

More information about formatting options

Papernote
Papernote

Upcoming Events

WorkHabit Labs Archives