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

This allows us to pass a <strong>Drupal</strong> authentication token to our access callback. To make<br />

this work, we modify our link creation code to include a token:<br />

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

$output = l(t('Add to my list'), 'example-ajax/'. $item->id .<br />

'/add/'. $user->uid) .'/'. drupal_get_token($user->uid);<br />

return $output;<br />

}<br />

This will generate a link similar to:<br />

Add to my list<br />

Then, in our access callback, we check the token string in addition to the user:<br />

function example_access_ajax_add($account, $token = NULL) {<br />

global $user;<br />

// Check the validity of the user account.<br />

if ($account->uid == 0 || $account->uid != $user->uid) {<br />

return FALSE;<br />

}<br />

// Check the validity of the callback token.<br />

if (empty($token) || !drupal_valid_token($token, $account->uid)) {<br />

return FALSE;<br />

}<br />

return TRUE;<br />

}<br />

<strong>Drupal</strong>'s token handling API performs the validation for us, and we are ensured the<br />

same protection that is given to regular <strong>Drupal</strong> forms.<br />

Note that this approach will only work correctly for logged-in users<br />

who are being served non-cached pages. The link we output to access<br />

this callback cannot be cached, since caching returns the same HTML<br />

output to all users.<br />

As a general rule, you only need to worry about token handling for AJAX callbacks<br />

that perform creative or destructive actions, such as editing a list of user favorites.<br />

That is because such actions generally write to the database, and can change certain<br />

settings for your <strong>Drupal</strong> users. Simple AJAX callbacks that only read and return data<br />

do not necessarily need to be secured in this manner unless the data is user-specific.<br />

[ 239 ]

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

Saved successfully!

Ooh no, something went wrong!