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 />

Security considerations<br />

The above code works just fine. But there is a potentially dangerous flaw in its logic:<br />

we do not account for variations of the different operations. As written, the module<br />

gives View, Update, and Delete access to all nodes based on user role. This could be<br />

a huge problem if we don't want some roles to delete content.<br />

One way to correct this issue is to leverage the core permission system to establish<br />

additional rules that our module implements. We can assign specific permissions<br />

to allow each role access to the various operations.<br />

If you recall Chapter 8, <strong>Drupal</strong> Permissions and Security, implementing<br />

hook_permission() gives us an easy way to do this.<br />

/**<br />

* Implement hook_permission().<br />

*<br />

* Define our modules permissions as follows:<br />

* -- view role access content<br />

* -- update role access content<br />

* -- delete role access content<br />

*<br />

* Naming these properly helps avoid conflicts with other modules.<br />

* Note that we name these based on the $op value passed by<br />

* hook_node_grants(). This allows us to use string concatenation<br />

* when doing our access check.<br />

*/<br />

function role_access_permission() {<br />

return array(<br />

'view role access content' => array(<br />

'title' => t('View role-restricted content'),<br />

'description' => t('Allow users to view content assigned by<br />

role.'),<br />

),<br />

'update role access content' => array(<br />

'title' => t('Edit role-restricted content'),<br />

'description' => t('Allow users to edit content assigned by<br />

role.'),<br />

),<br />

'delete role access content' => array(<br />

'title' => t('Delete role-restricted content'),<br />

'description' => t('Allow users to delete content assigned by<br />

role.'),<br />

),<br />

);<br />

}<br />

[ 271 ]

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

Saved successfully!

Ooh no, something went wrong!