You are here

7.5 权限与访问控制

admin 的头像
Submitted by admin on 星期一, 2015-08-31 10:18

作者:老葛,北京亚艾元软件有限责任公司,http://www.yaiyuan.com

在我们的菜单项里面,用到了权限'administer breadcrumbs',现在就让我们定义这个权限,向module文件中添加以下代码:

/**

 * Implements hook_permission().

 */

function breadcrumb2_permission() {

  $permissions = array(

    'administer breadcrumbs' => array(

      'title' => t('Administer breadcrumbs'),

      'description' => t('Edit and view all entity breadcrumbs.'),

    ),  

  );

  return $permissions;  

}

面包屑也有增删查改,但是这些工作都是由管理员来做的,所以我们这里比较省事,就定义了一个'administer breadcrumbs'权限,其它的都省去了。

hook_entity_info里面,有这样的定义'access callback' => 'breadcrumb2_access',这里的breadcrumb2_access,就是一个访问控制回调函数,来看一下我们的实现:

 

/**

 * Determines whether the given user has access to a breadcrumb.

 *

 * @param $op

 *   The operation being performed. One of 'view', 'update', 'create', 'delete'

 *   or just 'edit' (being the same as 'create' or 'update').

 * @param $breadcrumb

 *   Optionally a breadcrumb to check access for. If nothing is

 *   given, access for all breadcrumbs is determined.

 * @param $account

 *   The user to check for. Leave it to NULL to check for the global user.

 * @return boolean

 *   Whether access is allowed or not.

 */

function breadcrumb2_access($op, $breadcrumb = NULL, $account = NULL) {

  if (user_access('administer breadcrumbs', $account)) {

    return TRUE;

  }

  return FALSE;

}

对于比较复杂的实体,比如profile2,这个访问回调里面还会定义一个新的钩子hook_profile2_access

 

function profile2_access($op, $profile = NULL, $account = NULL) {

  if (user_access('administer profiles', $account)) {

    return TRUE;

  }

  if ($op == 'create' || $op == 'update') {

    $op = 'edit';

  }

  // Allow modules to grant / deny access.

  $access = module_invoke_all('profile2_access', $op, $profile, $account);

 

  // Only grant access if at least one module granted access and no one denied

  // access.

  if (in_array(FALSE, $access, TRUE)) {

    return FALSE;

  }

  elseif (in_array(TRUE, $access, TRUE)) {

    return TRUE;

  }

  return FALSE;

}

node_access里面,也定义了类似的钩子:

$access = module_invoke_all('node_access', $node, $op, $account);

 

当然,我们这里不需要定义一个hook_breadcrumb2_access,所以我们的就比较简单。


Drupal版本: