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.

Chapter 9<br />

The Node Access API allows modules to alter how the default <strong>Drupal</strong> CRUD<br />

workflow behaves. Normally, <strong>Drupal</strong> nodes are created by a single user. That user<br />

"owns" the node and, in most cases, may edit or delete the node at will. Some users,<br />

like the administrative user 1, may edit any node. But by default, <strong>Drupal</strong> has no<br />

concept of group ownership of nodes. Certain roles may be given permission to edit<br />

all nodes of a type (as shown by the core edit any Article content permission,<br />

for instance), but out of the box there is no provision for restricting access to view<br />

that content.<br />

The Node Access API evolved out of the need to define a flexible, extensible set of<br />

access rules. Much has improved in <strong>Drupal</strong> 7, so experienced developers will want<br />

to review this material carefully.<br />

Node Access permissions are checked in two instances:<br />

• When requests to act upon an individual node are made.<br />

• When database queries return lists of nodes that match given conditions.<br />

In order to handle node access securely, module developers need to be mindful of<br />

both cases.<br />

The first case is fairly simple, and is generally handled by a menu callback and the<br />

node_access() function. Unless your module intends to interfere with the normal<br />

handling of node_menu(), you may be able to skip the rest of this chapter.<br />

However, all module developers need to understand the impact of case two. Let's<br />

highlight it here.<br />

Any database query involving the {node} table must be built<br />

dynamically and be marked as a node access query. Failure to<br />

do so can introduce security vulnerabilities on sites running<br />

your code.<br />

To understand this rule, let's look at a simple example from <strong>Drupal</strong> core. The<br />

following query is found in node_page_default(), the function that provides the<br />

basic node listing page:<br />

$select = db_select('node', 'n')<br />

->fields('n', array('nid'))<br />

->condition('promote', 1)<br />

->condition('status', 1)<br />

->orderBy('sticky', 'DESC')<br />

->orderBy('created', 'DESC')<br />

->extend('PagerDefault')<br />

[ 243 ]

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

Saved successfully!

Ooh no, something went wrong!