\user_access
function
Determine whether the user has a given privilege.

Determine whether the user has a given privilege.

Comments

EvanDonovan’s picture

1) Define a permission in hook_perm() in your module, here called "coolstuff.module".

function coolstuff_perm() {
  return array('do cool stuff', 'do uncool stuff');
}

2) Grant it to your users at admin/user/permissions.

3) Check it in a function.

function coolstuff_init() {
  if (user_access('do cool stuff')) {
   drupal_set_message(t('You can do cool stuff!'));
  }
  elseif (user_access('do uncool stuff')) {
    drupal_set_message(t('You can do uncool stuff.'));
  }
  elseif (!user_access('do cool stuff') && !user_access('do uncool stuff')) {
   drupal_set_message(t("You can't do stuff at all."));
  }
}

I personally have never used the $account parameter, but presume it could be used as follows:

function check_coolstuff($uid) {
  $account = user_load($uid);
  if (user_access('do cool stuff', $account)) {
    drupal_set_message(t("The user @username with uid @uid has the permission to do cool stuff.", array('@username' => $account->name, '@uid' => $account->uid));
  }
}
mosys’s picture

Use this to forward administrators or editor to the administration page upon login:

  global $user;
  if ($user->uid == 1 || user_access('access administration pages')) {
    // Redirect admin to the administration page
    return 'admin';
  } else {
    return 'node';
  }
PROMES’s picture

Your example can be written even shorter since user_access() does the check for userid 1 for you.

<?php
  if (user_access('access administration pages')) {
    // Redirect admin to the administration page
    return 'admin';
  } else {
    return 'node';
  }
?>
Madbreaks’s picture

return user_access('access administration pages') ? 'admin' : 'node';
fureigh’s picture

If you want to comply with the coding standards:

Always use curly braces even in situations where they are technically optional. Having them increases readability and decreases the likelihood of logic errors being introduced when new lines are added.