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 code will grant anonymous users with the proper permission access to View<br />

content as if they were authenticated.<br />

Security warning!<br />

Be very careful with any code that provides this type of privilege<br />

escalation. For instance, if we failed to check that $op == 'view' we<br />

would be giving anonymous users permission to View, Update and<br />

Delete all content on the site!<br />

The above example is great, but what if we want to restrict custom roles to only view<br />

content created by people in those roles? That is, we might need to remove the ability<br />

to View content as an authenticated user. With a slight modification to the code, we<br />

can do so:<br />

/**<br />

* Implement hook_node_grants_alter().<br />

*/<br />

function role_access_extend_node_grants_alter(&$grants, $account, $op)<br />

{<br />

// We only act on the 'view' operation.<br />

// If our grants is not present, do nothing.<br />

if ($op != 'view' || !isset($grants['role_access'])) {<br />

return;<br />

}<br />

// Check the permission.<br />

$access = user_access('view role access as authenticated user');<br />

// Get the defined role id for 'authenticated user'.<br />

$rid = DRUPAL_AUTHENTICATED_RID;<br />

// Check authenticated users.<br />

if ($account->uid > 0) {<br />

// Users with more than one role should have 'authenticated users'<br />

// removed.<br />

if (count($account->roles) > 1 && in_array($rid, $grants['role_<br />

access']) && !$access) {<br />

// The grants array is in the order $grants[$realm][$key] =><br />

// $value, so flip it, unset, and flip back.<br />

$grants['role_access'] = array_flip($grants['role_access']);<br />

unset($grants['role_access'][$rid]);<br />

$grants['role_access'] = array_flip($grants['role_access']);<br />

}<br />

}<br />

[ 278 ]

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

Saved successfully!

Ooh no, something went wrong!