18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8<br />

}<br />

$permissions = array(<br />

'access user profiles',<br />

'administer users',<br />

);<br />

$role = user_role_load_by_name('acount moderator');<br />

user_role_grant_permissions($role->rid, $permissions);<br />

When our module is uninstalled, we should delete the role as well.<br />

function account_moderator_uninstall() {<br />

user_role_delete('account moderator');<br />

}<br />

Securing forms in <strong>Drupal</strong><br />

Form handling is one of the most crucial areas of website security. Inappropriate<br />

handling of form data can lead to multiple security weaknesses including SQL<br />

injection and cross-site request forgeries (CSRF). While we cannot cover all aspects<br />

of security in a brief chapter, it is important to state some clear guidelines for <strong>Drupal</strong><br />

module developers.<br />

See http://en.wikipedia.org/wiki/CSRF for information on<br />

CSFR, and for cross-site scripting (XSS) see http://en.wikipedia.<br />

org/wiki/XSS.<br />

The Forms API<br />

First and foremost, you should always use the <strong>Drupal</strong> Forms API when creating and<br />

processing forms in <strong>Drupal</strong>. For one, doing so makes your life easier because the<br />

Forms API contains standards for form definition, AJAX handling, required elements,<br />

validation handling, and submit handling. (See more about forms in Chapter 5.)<br />

From a security standpoint, the Forms API is critical because it contains built-in<br />

mechanisms for preventing CSRF requests.<br />

Whenever <strong>Drupal</strong> creates a form through the API, the form is tagged with a<br />

unique token called the form_build_id. The form_build_id is a random<br />

md5 hash used to identify the form during processing. This token is added<br />

by the drupal_build_form() routine:<br />

$form_build_id = 'form-' . drupal_hash_base64(uniqid(mt_rand(), TRUE)<br />

. mt_rand());<br />

$form['#build_id'] = $form_build_id;<br />

[ 229 ]

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

Saved successfully!

Ooh no, something went wrong!