Recibí algunos resultados de pruebas de pluma. Los resultados dicen que cualquiera puede actualizar cualquier registro simplemente cambiando una determinada identificación.
¿Cómo podría asegurarme de que el usuario solo pueda actualizar su propio registro en esta función?
public function actionUpdateProfile() { $postdata = file_get_contents("php://input"); $response = array("status" => "1", "message" => "Profile update successful."); $data = json_decode($postdata); $model = HosDoctors::model()->findByPk($data->doctor_id); foreach ($data->fields1 as $field) { $_POST[$field->name] = $field->value; } $enc = NEW bCrypt(); $model->attributes = $_POST; if ($model->save()) { $response = array("status" => "1", "message" => "Profil erfolgreich aktualisiert"); } else { pr($model->getErrors()); } echo json_encode($response); die; }¿Sería suficiente simplemente verificar
if (cookie == $data->doctor_id) { //ok } else { //we are not logged as the user id that we want to update, so deny updating die; }Supongo que la persona se ha "iniciado sesión" de alguna manera para que sepas "quiénes son". Si bien la seguridad es compleja y definitivamente no es un tema de una sola respuesta; en su nivel más simple, una vez que haya identificado al usuario, use el manejo de sesión de PHP para conservar su identidad en una o varias solicitudes de http/s, luego acceda internamente a cualquier información relacionada usando la identificación de la cookie de sesión durante la sesión.
Hay varios problemas potenciales en esta función (a menos que haya publicado una versión muy editada). Los anotaré como comentarios.
public function actionUpdateProfile() { $postdata = file_get_contents("php://input"); $response = array("status" => "1", "message" => "Profile update successful."); // Never initialize responses until you really *must*. Chances that a partially prepared response might be output are slight, but why run risks? // And actually you **do** reinitialize $response later on! $data = json_decode($postdata); // You are not verifying that $data *exists* (ie the JSON data was, indeed, JSON). You should check that $data is not NULL and that it does have **all** the required fields and that they are valid. // This is the point where you validate $data->doctor_id, by the way. Or you check that patient_data matches with whatever you have in your $_SESSION or Session app object. $model = HosDoctors::model()->findByPk($data->doctor_id); // This is a bad practice. Yes, you have some code that relies on // _POST. If necessary, wrap it in another code that will set up // _POST from an input and then delete it. Otherwise you're leaking // data into a superglobal. You don't want to do that. foreach ($data->fields1 as $field) { $_POST[$field->name] = $field->value; } // Why are you initialising $enc? $enc = NEW bCrypt(); // This is not very good. $_POST could contain *other* information // unless it's been sanitized outside the function. // I would prepare a setter function, $model->setArray($data), that // would verify the validity of the attributes before setting them. $model->attributes = $_POST; if ($model->save()) { $response = array("status" => "1", "message" => "Profil erfolgreich aktualisiert"); } else { pr($model->getErrors()); } // This works in 90% of the browsers and scenarios. But I'd // set up a function that would also send the appropriate // Content-Type headers to satisfy the remaining 10%. echo json_encode($response); die; // eg Utilities::jsonResponse($response); }¿Sería suficiente simplemente verificar
if (cookie == $data->doctor_id) { //ok } else { //no estamos registrados como el id de usuario que queremos actualizar, así que deniegue la actualización die; }
intente verificar por token de usuario en lugar de ID de usuario porque la identificación de usuario se puede encontrar dentro de alguna URL o cuerpo de página, pero el token es difícil de obtener a menos que use técnicas de rastreo de red.
puede generar un token de usuario mediante cualquier método de generación de tokens y luego almacenarlo como una columna en la tabla de usuarios de su base de datos.
método de generación de fichas, por ejemplo
$token = bin2hex(openssl_random_pseudo_bytes(16)); # or in php7 $token = bin2hex(random_bytes(16));