colymba / silverstripe-restfulapi

SilverStripe RESTful API with a default JSON serializer.
BSD 3-Clause "New" or "Revised" License
64 stars 34 forks source link

How to prevent POST requests specifying ID #91

Closed thepearson closed 6 years ago

thepearson commented 6 years ago

I'm looking for some ideas on how to best prevent users POST requests specifying the ID parameter.

Scenario: POST { Id: 99999999999, OtherFields: "FooBar" }

This sets the MySQL AUTO INCREMENT value to the max signed/unsigned integer value, essentially breaking any new inserts.

Can I get the HTTP method within onAfterDeserialize to prevent transactions using the Id field when creating record? Or should I be doing this in onBeforeWrite. Again how do I know if this is a new record or an update to the record?

Am I just doing it wrong. Is there another way to prevent fields being updated/created.

thepearson commented 6 years ago

I ended up using the following on my base DataObject class

    public function onAfterDeserialize(&$data)
    {
        $request = Controller::curr()->getRequest();
        if (($request->isPOST() || $request->isPUT()) && $data['ID']) {
            unset($data['ID']);
        }
    }