18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Node Access<br />

This clause is primarily a query builder function, designed to create the proper join<br />

from the {node} table to the {node_access} table and then return the result of that<br />

query. Understanding how that query is constructed – and how the {node_access}<br />

table is populated – is the key to understanding Node Access.<br />

Dealing with unpublished content<br />

For experienced module authors, one major difference between <strong>Drupal</strong><br />

7 and previous versions is that hook_node_grants() is now invoked<br />

for unpublished content. Great care must be taken to prevent exposing<br />

unpublished content to users.<br />

If the Node Access API does not assert rules, this clause will default to allowing<br />

access to content. But notice that the function does not end here.<br />

elseif (is_object($node) && $op == 'view' && $node->status) {<br />

// If no modules implement hook_node_grants(), the default<br />

// behavior is to allow all users to view published nodes,<br />

// so reflect that here.<br />

$rights[$account->uid][$cid][$op] = TRUE;<br />

return TRUE;<br />

}<br />

}<br />

}<br />

return FALSE;<br />

At the very end of the function, notice the final return FALSE; statement. From a<br />

security standpoint, this catch-all ensures that we never grant access by accident.<br />

Whenever writing an access check, FALSE should be your default return.<br />

hook_node_access() compared to<br />

{node_access}<br />

For module developers, the two key points to the node_access() function<br />

are the behaviors of the two hook invocations: hook_node_access() and<br />

hook_node_grants(). Because of the fundamental difference between how<br />

the two hooks are implemented, for the rest of the chapter, we will refer to a node<br />

access module as one that implements hook_node_grants() and writes to the<br />

{node_access} table. A module that implements hook_node_access() will be<br />

referred to as an access control module.<br />

[ 250 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!