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.

<strong>Drupal</strong> Permissions and Security<br />

In this chapter, we will cover the following:<br />

• <strong>Drupal</strong>'s roles and permissions concepts<br />

• Using user_access() to assert permissions<br />

• Using hook_permission()<br />

• Access control with hook_menu()<br />

• Common errors in defining permissions<br />

• Declaring your own access functions<br />

• Securing sensitive actions with permissions<br />

• Responding when access is denied<br />

• Enabling permissions programmatically<br />

• Permissions, security, and <strong>Drupal</strong> forms<br />

• Security considerations for AJAX processing<br />

Using user_access() to assert<br />

permissions<br />

The user_access() function is the primary security element in the <strong>Drupal</strong> API.<br />

Most page requests pass through the function, as do many administrative functions<br />

and the display of certain page elements. Pages, blocks, fields, and form elements<br />

are some of the items that can be shown or hidden by wrapping their display in a<br />

user_access() call.<br />

The function is quite elementary, taking only two arguments:<br />

user_access($string, $account = NULL)<br />

Here, $string is the machine readable name of the permission, and $account is an<br />

optional copy of a $user object, as returned by the function user_load().<br />

The following is a typical access check, taken from the Menu module:<br />

$form['menu'] = array(<br />

'#type' => 'fieldset',<br />

'#title' => t('Menu settings'),<br />

'#access' => user_access('administer menu'),<br />

'#collapsible' => TRUE,<br />

'#collapsed' => !$link['link_title'],<br />

);<br />

[ 212 ]

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

Saved successfully!

Ooh no, something went wrong!