WorkHabit Blogs
WORKHABIT LABSChecking node_access through the API
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.
-
<?php
-
-
// By default, Drupal's node access works on the current user.
-
// If you want to determine access for an arbitrary user, you
-
// have to fetch the user object for that user first. Here we
-
// fetch the user having the email address foo@bar.com.
-
-
-
foreach ($node_ids as $nid) {
-
// Fetch the full node. Drupal has some special cases
-
// that can't be determined just from the content id.
-
// For instance, a node's author can always view their
-
// own node.
-
$node = node_load($nid);
-
if (node_access('view', $node, $user)) {
-
// You have access. Do stuff.
-
}
-
// You can also check to see if the user has access to
-
// create, update, or delete a node instead of simply
-
// "view".
-
//
-
// If you want to check permissions for the current user,
-
// you can omit the user_load step above and change the
-
// node_access call to node_access('view', $node).
-
}
-
?>


Post new comment