1

I have a list of lesson plans, sorted by category. Underneath each category, I have a link called "Add new lesson/category/root term".

enter image description here

I would like it so that when the user clicks on "Add new category" or "Add new root term", they are prompted with a message box to get the name of the new term to add. Then, that message box will make an ajax call to mysite.com/add-new-term, with the name of the new term as a POST argument.

I know how to make an HTTP POST request using jQuery.post(). I know how to implement hook_menu() to enable requests to mysite.com/add-new-term. And I know how to use PHP's superglobal array $_POST to get the data from the request.

BUT, I don't know how to add user authentication to the request.

How can I ensure that only logged-in admins can make these requests? I don't want just any random person on the web to be able to create new terms.

0

Turns out this is actually really easy.

You can get the current user's roles with:

global $user;
$roles = $user->roles;

That returns an associative array with the roles as values. Getting the values is trivial with in_array():

if (in_array("Teacher", $user->roles)) {
  // allow the post request to have effect
}
else {
  // don't go through with the request; return an error
}

Because the module is called during the lifecycle of the Drupal structure, you have access to the whole environment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.