You are here

useraccount_permissions.module in User Account Permissions 7

Adds more granular permissions related to user accounts.

File

useraccount_permissions.module
View source
<?php

/**
 * @file
 * Adds more granular permissions related to user accounts.
 */

/**
 * Implements hook_permission().
 */
function useraccount_permissions_permission() {
  return array(
    'edit own user account' => array(
      'title' => t('Edit own user account'),
      'description' => t('User can edit their own account profile.'),
    ),
    'edit own email address' => array(
      'title' => t('Edit own email address'),
      'description' => t('User can edit their own email address.'),
    ),
    "edit other user's email address" => array(
      'title' => t("Edit other users' email address"),
      'description' => t("User can change another user's email address"),
      'restrict access' => TRUE,
    ),
    'change own password' => array(
      'title' => t('Change own password'),
      'description' => t('User can change their own password.'),
    ),
    "change other user's password" => array(
      'title' => t("Change other user's password"),
      'description' => t("User can change another user's password."),
      'restrict access' => TRUE,
    ),
  );
}

/**
 * Implements hook_menu_alter().
 */
function useraccount_permissions_menu_alter(&$items) {
  $items['user/%user/edit']['access callback'] = 'useraccount_permissions_access_own_account';
  $items['user/%user/edit']['access arguments'] = array(
    1,
  );
}

/**
 * Access callback for the user edit menu item.
 *
 * @param object $account
 *   User account object that access is being determined for
 *
 * @return bool
 *   Whether or not the user has access to the menu item.
 */
function useraccount_permissions_access_own_account($account) {
  global $user;
  if (user_access('edit own user account') && $user->uid == $account->uid || user_access('administer users')) {
    return TRUE;
  }
  return FALSE;
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function useraccount_permissions_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  if (!user_access('administer users')) {
    global $user;
    $account = $form['#user'];
    $is_own_account = $user->uid == $account->uid;
    if ($is_own_account && !user_access('edit own email address')) {
      $form['account']['mail']['#access'] = FALSE;
    }
    if (!$is_own_account && !user_access("edit other user's email address")) {
      $form['account']['mail']['#access'] = FALSE;
    }
    if ($is_own_account && !user_access('change own password')) {
      $form['account']['pass']['#access'] = FALSE;
      $form['account']['current_pass']['#access'] = FALSE;
    }
    if (!$is_own_account && !user_access("change other user's password")) {
      $form['account']['pass']['#access'] = FALSE;
      $form['account']['current_pass']['#access'] = FALSE;
    }
  }
}