你在hook_perm()中定义了权限,但是它们是如何起作用的呢?节点模块可以使用hook_access()来限制对它们定义的节点类型的访问。超级用户(用户ID 1)将绕过所有的访问权限检查,所以对于超级用户则不会调这个钩子函数。如果没有为你的节点类型定义这个钩子函数,那么所有的访问权限检查都会失败,这样就只有超级用户和具有“管理节点”权限的用户,才能够创建、编辑、或删除该类型的内容。
/**
* Implementation of hook_access().
*/
function joke_access($op, $node, $account) {
$is_author = $account->uid == $node->uid;
switch ($op) {
case 'create':
// Allow if user's role has 'create joke' permission.
return user_access('create joke', $account);
case 'update':
// Allow if user's role has 'edit own joke' permission and user is
// the author; or if the user's role has 'edit any joke' permission.
return user_access('edit own joke', $account) && $is_author ||
user_access('edit any joke', $account);
case 'delete':
// Allow if user's role has 'delete own joke' permission and user is
// the author; or if the user's role has 'delete any joke' permission.
return user_access('delete own joke', $account) && $is_author ||
user_access('delete any joke', $account);
}
}
前面的函数允许具有“create joke”权限的用户创建一个笑话节点。如果用户还具有“edit own joke”权限并且他们是节点作者,或者如果他们具有'edit any joke'权限,那么他们还可以更新一个笑话。那些具有'delete own joke'权限的用户,他们可以删除自己创建的笑话;而具有'delete any joke'权限的用户,则可以删除joke类型的所有节点。
在钩子函数hook_access()中, $op另一个可用的值是“view”(查看),它允许你控制谁可以查看该节点。然而我们需要提醒一下:当查看的页面仅有一个节点时,才调用钩子hook_access()。当节点处于摘要视图状态时,比如位于一个多节点列表页面,在这种情况下, hook_access()就无法阻止用户对该节点的访问。你可以创建一些其它的钩子函数,并直接操纵$node->teaser的值来控制对它的访问,但是这有点黑客的味道了。一个比较好的解决方案是,使用我们在后面即将讨论的函数hook_node_grants()和hook_db_rewrite_sql()。
老葛的Drupal培训班 Think in Drupal