今天我在我的Web服务中创建了一个函数来从mysql中的表中删除用户。 我使用SLIM框架来构建我的RESTful API。
这是我班级用户的功能:
public function deleteUser($user_id)
{
$stmt = $this->conn->prepare("DELETE
FROM users
WHERE user_id = ?");
if($stmt == FALSE)
{
die($this->conn->error);
}
else
{
$stmt->bind_param("i", $user_id);
$stmt->execute();
$num_affected_rows = $stmt->affected_rows;
$stmt->close();
return $num_affected_rows > 0;
}
}
这是我在index.php中的代码
$app->delete('/users/:user_id', 'authenticate', function() use($app)
{
global $user_id;
$db = new User();
$response = array();
$result = $db->deleteUser($user_id);
if ($result)
{
// user deleted successfully
$response["error"] = false;
$response["message"] = "User deleted succesfully";
}
else
{
// user failed to delete
$response["error"] = true;
$response["message"] = "User failed to delete. Please try again!";
}
echoRespnse(200, $response);
});
问题是我的身份验证功能是从用户表中获取user_id以放置在头部授权中。
function authenticate(\Slim\Route $route)
{
// Getting request headers
$headers = apache_request_headers();
$response = array();
$app = \Slim\Slim::getInstance();
// Verifying Authorization Header
if (isset($headers['Authorization']))
{
$db = new User();
// get the api key
$api_key = $headers['Authorization'];
// validating api key
if (!$db->isValidApiKey($api_key))
{
// api key is not present in users table
$response["error"] = true;
$response["message"] = "Access Denied. Invalid Api key";
echoRespnse(401, $response);
$app->stop();
}
else
{
global $user_id;
// get user primary key id
$user_id = $db->getUserId($api_key);
}
}
else
{
// api key is missing in header
$response["error"] = true;
$response["message"] = "Api key is misssing";
echoRespnse(400, $response);
$app->stop();
}
}
因此,每当我尝试使用'user_id'删除用户时,它总是出错,因为系统将被删除用户取决于在标题授权中提交的API KEY。
我的目标是:删除功能将删除具有用户ID的用户。
有谁知道如何修复它?
谢谢:)
答案 0 :(得分:0)
我在这些代码行中非常狡猾:
else
{
global $user_id;
// get user primary key id
$user_id = $db->getUserId($api_key);
}
对你自己来说最大的问题是,$ user_id作为全局变量的范围是什么?
验证函数将在执行deleteUser($user_id)
之前运行,因此无论您如何努力,您最终都会删除当前经过身份验证的用户,因为$user_id = $db->getUserId($api_key)
会将当前经过身份验证的user_id存储到全局变量中
这对您的实施非常不利,因为临终用户会自行删除。那不是很酷的人。因此,我建议您使用最简单的解决方法,例如:
global $user_id
global $executor_id
旁边声明另一个变量
$user_id = $db->getUserId($api_key);
更改为$executor_id = $db->getUserId($api_key);
它会指定谁将执行删除功能。然后在index.php中创建delete()函数,如下所示:
$app->delete('/users/:user_id', 'authenticate', function() use($app)
{
global $user_id;
global $executor_id;
$db = new User();
$response = array();
$user_id = // please get the user_id that would be deleted here.
$result = false;
if($user_id != $executor_id)
$result = $db->deleteUser($user_id);
if ($result)
{
// user deleted successfully
$response["error"] = false;
$response["message"] = "User deleted succesfully";
}
else
{
// user failed to delete
$response["error"] = true;
$response["message"] = "User failed to delete. Please try again!";
}
echoRespnse(200, $response);
});
抱歉,我不熟悉SLIM Framework,但希望它有所帮助:)