此代码片段响应用户#1,但不响应其他登录或匿名用户:
function module_menu_alter(&$items) {
$items["node/add/page"]['access callback'] = 'module_access_callback';
}
function module_access_callback(){
die('responding here - test');
}
我究竟做错了什么?
此代码片段响应用户#1,但不响应其他登录或匿名用户:
function module_menu_alter(&$items) {
$items["node/add/page"]['access callback'] = 'module_access_callback';
}
function module_access_callback(){
die('responding here - test');
}
我究竟做错了什么?
OK It turns out the answer is actually very simple...
You're calling menu_get_object()
to retrieve the node, but no node exists on node/add/page
. In fact quite the opposite; it wouldn't make sense to have a node available on the page to add a node, as it hasn't been created yet! The 403 is a side effect of this.
You'll need to make your access decision based on some other value (normally the logged in user along with a permission as @kiamlaluno has done a very good job of explaining in his answer).
Also do make sure you return TRUE
or FALSE
from your access callback as @kiamlaluno has also stated :)
EDIT
Just to say that this is partially an answer to https://stackoverflow.com/questions/8342169/drupal-hook-menu-alter-menu-get-object-error, which explains why there are functions mentioned in this answer that aren't mentioned in the question.
如果那是您真正使用的代码,那么访问回调函数是错误的,因为它应该TRUE
在当前登录的用户可以访问菜单时返回,并且FALSE
当用户无权访问菜单时。它不使用die()
.
这是hook_menu()文档中报告的内容:
“访问回调”:
TRUE
如果用户有权访问此菜单项,则返回一个函数,否则返回FALSE
。它也可以是布尔常量而不是函数,您还可以使用数值(将被强制转换为布尔值)。默认为user_access()除非值是从父菜单项继承的;只有MENU_DEFAULT_LOCAL_TASK项目可以继承访问回调。要使用user_access()
默认回调,您必须将要检查的权限指定为“访问参数”。
如果您没有显示您正在使用的代码,那么下面的内容可以解释您所看到的行为。
第一个用户或用户 #1 是特定用户,因为user_access()始终TRUE
为该用户返回。这在该函数的代码中很明显,它明确检查用户 ID 是否等于 1。
// User #1 has all privileges:
if ($account->uid == 1) {
return TRUE;
}
如果认证用户的访问回调返回FALSE
,并且它正在使用user_access()
,那是因为认证用户没有权限传递给函数。
也可能是您正在检查多个权限,并且您正在使用user_access('first permission') && user_access('second permission')
, 而不是user_access('first permission') || user_access('second permission')
(反之亦然)。对于没有任何区别的用户 #1,作为 and 的结果,user_access('first permission') && user_access('second permission')
总是user_access('first permission') || user_access('second permission')
,TRUE
即使您将字符串传递给函数,以获得未从任何模块定义的权限。