A.3. Users and Permissions

The next functions help Drupal safely deal with user permissions. These functions are covered in more detail in Chapter 4.

  • session_save_session(TRUE | FALSE)

    • Description Used when code has to modify the global $user object to protect the global value from being accidentally replaced.

    • Use Code that has to take actions on a site as another user.

    • Example The unvulnerable.module, which executes an action like the creation of a node type for a user when you don't want the user to have the ability to create that node in general.

    function unvulnerable_session_switcher() {
      global $user;
      $current_user = $user;
      session_save_session(FALSE);
      $user = user_load(array('uid' => 1));
      action_as_another_user();
    
      $user = $current_user;
    
     session_save_session(TRUE);
    
    }
  • user_access('permission name')

    • Description Takes a string for the name of a specific permission and returns either TRUE or FALSE depending on whether the user has that specific permission.

    • Use Verifying whether or not a user can perform a task.

    • Example Limiting access to view the comment on a comment reply form in comment_reply in comment.pages.inc.

    if (user_access('access comments')) {
    
    . . .
    }
    else {
      drupal_set_message(t('You are not authorized to view comments.'),
          'error');
      drupal_goto("node/$node->nid");
    
    }
  • drupal_access_denied()

    • Description Shows the user an Access Denied page. This function does not stop processing. Be sure that you either return this value or guard any processing that follows so that you don't accidentally ...

Get Cracking Drupal®: A Drop in the Bucket now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.