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.

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

In our callback, the menu system transforms 10 into a standard $user object, which<br />

we check for validity in two ways:<br />

function example_access_ajax_add($account) {<br />

global $user;<br />

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

return FALSE;<br />

}<br />

return TRUE;<br />

}<br />

First, if user_load() returns FALSE, then the page argument is invalid. Second,<br />

if the returned $account does not match the user making the request, the request<br />

is invalid.<br />

This is pretty good. It allows our code to check that the user making the AJAX<br />

request is the currently logged in user. However, how do we know that this<br />

request came from our server and is not a CSRF attack?<br />

Well honestly, we don't know and we can't know. However, we can be a little<br />

paranoid and add another layer of security.<br />

Knaddson gives us the key in Cracking <strong>Drupal</strong>, when he says:<br />

The security team is working on an API to make [securing AJAX callback] much<br />

easier, but that API is not yet available…The system is based on the same token<br />

system used to protect <strong>Drupal</strong> forms.<br />

Cracking <strong>Drupal</strong>, page 18<br />

To implement this structure, we have to add an additional argument to our<br />

page callback:<br />

function example_menu() {<br />

$items = array();<br />

$items['example-ajax/%item/add/%user/%'] = array(<br />

'title' => 'Example AJAX add to list',<br />

'page callback' => 'example_ajax_add',<br />

'page arguments' => array(1, 3),<br />

'access callback' => 'example_access_ajax_add',<br />

'access arguments' => array(3, 4),<br />

'type' => MENU_CALLBACK,<br />

);<br />

return $items;<br />

}<br />

[ 238 ]

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

Saved successfully!

Ooh no, something went wrong!