我有一个包含列的表:
- 序列
- 页面名称
- 级别用户
- 级别支持
- 级别帐户
- 级别_admin
最后4列是访问级别(用户、支持、帐户和管理员)
这是我用来检查权限的代码:
$permission_sql="SELECT * from admin_permissions where page_name = '".$_SERVER["REQUEST_URI"]."' ";
$permission_rs=mysql_query($permission_sql,$conn);
if(mysql_num_rows($permission_rs) == 0)
{
echo '<h2 align="center">An Error has occurred!</h2>';
exit();
}
else
{
$permission_result=mysql_fetch_array($permission_rs);
if($usertype_user != $permission_result["level_user"])
{
echo '<h2 align="center">Access Denied</h2>';
echo '<h2 align="center">Please contact your administrator quoting 'Permission Error' and number ''.$permission_result["sequence"].''</h2>';
exit();
}
if($usertype_support != $permission_result["level_support"])
{
echo '<h2 align="center">Access Denied</h2>';
echo '<h2 align="center">Please contact your administrator quoting 'Permission Error' and number ''.$permission_result["sequence"].''</h2>';
exit();
}
if($usertype_admin != $permission_result["level_admin"])
{
echo '<h2 align="center">Access Denied</h2>';
echo '<h2 align="center">Please contact your administrator quoting 'Permission Error' and number ''.$permission_result["sequence"].''</h2>';
exit();
}
if($usertype_accounts != $permission_result["level_accounts"])
{
echo '<h2 align="center">Access Denied</h2>';
echo '<h2 align="center">Please contact your administrator quoting 'Permission Error' and number ''.$permission_result["sequence"].''</h2>';
exit();
}
}
我正在访问:/admin/index.php,所以我的查询显示
从admin_permissions中选择*,其中page_name="/admin/index.php"
然后运行我的if语句,我登录的用户将$usertype_admin
设置为"yes",$permission_result["level_admin"]
等于"yes"但它显示拒绝访问错误,该错误不应为$usertype_admin do=$permission_result["level_admin"]
我做错了什么?
虽然我在下面的第二节中提出了一个建议,但她根据更新的问题/信息解释了代码不起作用的"原因"。
然后运行我的if语句,我登录的用户将$usertype_admin设置为"yes",$permission_result["level_admin"]等于"yes"但它显示拒绝访问错误,该错误不应为$usertype_admin==$permission-result["level_admin"]
这是因为如果if
分支中的任何为真,则将显示错误消息,并调用exit
-请注意,每种情况的条件都是!=
。想象一下这个数据:
(permission) $user database $user != database
------------ ------ -------- -----------------
user yes no TRUE
support yes no TRUE
admin yes yes FALSE
accounts yes no TRUE
可以看出,即使用户是管理员(例如$user(user)
为"是"),并且页面只"请求"管理员权限,授权也会失败,因为$user(user)
是"是",而database(user)
是"否"。哇。
以下是一种只在数据库中将设置为非'no'时才需要匹配权限的方法:
function hasAllPermissions ($permissions) {
// Note the use of a NEGATIVE selector on the database value
if($permission_result["level_admin"] != 'no'
&& $usertype_admin != $permission_result["level_admin"]) {
// Only here if a permission is set OTHER than 'no' and it does
// not equal the currently assigned user permission.
return FALSE;
}
// .. the other checks
// If we haven't rejected yet, the the database either asks for
// no permissions or we pass all permission checks.
return TRUE;
}
// In check:
if (!hasAllPermissions($permission_result)) {
// display warning and exist
}
或者,也许我们想要相反的:
function hasAnyPermission ($permissions) {
// Note the use of a POSITIVE selector on the database value
if($permissions["level_admin"] != 'no'
&& $usertype_admin == $permissions["level_admin"]) {
// We matched, so accept as having permission and return to
// avoid the additional checks.
return TRUE;
}
// .. the others checks
// And if nothing succeeded in matching, then we fail.
return FALSE;
}
// In check:
if (!hasAnyPermission($permission_result)) {
// display warning and exit
}
请注意,除了测试和返回结果的反转之外,这两种形式几乎相同。
除了重做整个模式(我也建议这样做)之外,我还建议进行一些更改:
- 清楚地定义与权限相关的业务规则
- 使用函数-用于条件逻辑和显示警告消息
- 使用
$usertype_xyx
的阵列,使$usertype["xyz"]
镜像$permission_result["xyz"]
,并可传递给适当的函数
(以下是为了解决最初的问题而写的,我觉得它仍然有价值。)
SQL被设计为沿着行而不是列展开-列名不应包含信息。
当使用面向列的方法时,您必须添加对每个列名的支持,并赋予其含义(请参阅"列名不应包含信息")。虽然这可以基于启发式和读取动态列形状(例如从SELECT *
)来完成,但我建议不要使用这种方法。
相反,对于具有基于角色的权限的数据库模式,以下结构可能是更合适的开始。
Users
- Username
Pages
- PageTitle
Roles
- RoleName
Users_Roles -- Granted Roles
- FK Users
- FK Roles
Pages_Roles -- Required (or Denied) Roles
- FK Pages
- FK Roles
然后,给定函数hasAllRequiredPermissions($user, $page)
,可以构造一个查询,该查询将使用上面的表来确定特定用途是否具有查看页面所需的所有权限,并且当添加新角色时,函数将不需要更新。这是因为信息存在于行中,而不是列中。
此外,上述关系允许模型轻松扩展,以允许诸如"如果用户具有角色,则允许访问"one_answers"如果用户拥有角色,则拒绝访问"之类的操作。
此外,不使用占位符是一个问题,使用$_SERVER["REQUEST_URI"]
发布的查询可能会被利用。在编写新的身份验证代码时,请确保使用占位符。
您可以有一个名为permission_table的表,它将存储每个用户可以访问的页面,不允许访问的页面将不会出现在这里
+---------------+--------------+----------+
| permission_id | page | user_id |
+---------------+--------------+----------+
| 1 | home.php | 33 |
| 2 | accounts.php | 2 |
| 3 | support.php | 67 |
+---------------+--------------+----------+
然后每个页面的查询将是
SELECT * from permissions_table where user_id = :user_id AND page = :page
您可以从类似$_session['user_ID']的存储会话中获取当前登录用户的ID。您甚至可以将允许他们访问的页面存储在会话阵列中,以保存数据库查询
您应该使用PDO,而不是去掉前缀的"mysql_"。完整的代码是…
session_start(); //This is needed when working with PHP sessions
//The mysql database details
$dbhost = 'your db host';
$dbuser = 'your db username';
$dbpass = 'your db password';
$dbname = 'your db name';
//PDO connection
try {
$con = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
//Permissions query
$stmt = $con->prepare('SELECT * from permissions_table WHERE user_id = :user_id AND page = :page');
$stmt->bindParam(':staff_id', $_SESSION['user_id']);
$stmt->bindParam(':page', basename($_SERVER['PHP_SELF']));
//If PDO query executes and returns 1 row!
if($stmt->execute() && $stmt->rowCount() === 1){
echo 'Permission granted'!
} else { die('Permission denied!');
}
最好的部分是,所有这些脚本都可以放在一个单独的php文件中,然后根据需要将其包含在每个页面的顶部。。。require('permissions.php');
因此,如果代码要更改,您只需在permissions.php 中更改一次即可
或者,如果您只想要4种不同的权限类型,而不是按每个页面执行权限。您可以将页面列更改为"type"。并存储"管理"、"支持"等内容。然后在每个页面的顶部放上这样的内容。。。
$permissiontype = 'Support';
require ('permissions.php');
然后更改查询和PDO绑定以获取变量,而不是当前页面
$stmt->bindParam(':type', $permissiontype);
"mysql_fetch_array"为该行返回一个零索引数组。如果希望列名成为行中的索引,则应使用"mysql_fetch_assoc"。有关使用该函数的更多信息,请参阅本页:http://us1.php.net/manual/en/function.mysql-fetch-assoc.php
基本上,你回来了:
$permission_result[0] = whatever "sequence" is
$permission_result[1] = the page name that you asked for
$permission_result[2] = value of level_user
$permission_result[3] = value of level_support
$permission_result[4] = value of level_accounts
$permission_result[5] = value of level_admin
所以,当你要求时
$permission_result["level_user"]
事实证明,"$permissionresult"没有名为"level_user"的元素,因此它会给您"null"作为结果。我很确定你的用户权限变量是布尔值(true/false)或字符(如"y"one_answers"n"),它们与你通过检查获得的null值不匹配
$permission_result["level_user"]
将"mysql_fetch_array"切换为"mysql_feach_assoc",您可能会没事的。