3 months ago

Preventing multiple form submissions with session and slow requests. Session does not seem to write fast enough?

Posted 3 months ago by booni3

I have a create order request, that is currently a little slow (about 3 - 4 seconds). I am attempting to prevent a duplicate form submission using the CSRF token, or a custom token.

For this instance, I am using valet with a file driver... so this may well be the issue but I am yet to push this code into a production server as it is not working as intended.

It works like this:

  • The token is added to the session and to the submit form in a hidden "custom_token" field.

  • The form is submitted and either within the middleware or the controller itself we do a quick comparison.

if(! hash_equals($request->session()->get('custom_token'), $request->custom_token)){
    flash()->error('Order placed twice');
    return redirect('/checkout/thank-you');

$request->session()->put('custom_token', Str::random(40));
  • If they do not match we do a quick redirect (Flash message only there for debugging currently).

The above works if I remove the main create orde call from the controller (i.e. the slow bit) but with this included the hash_equals always returns true.

So my questions are:

  1. Is this likely to be caused by the slow updating of a session file driver?
  2. Surely if this is the case, even in a production environment there is still some risk of this happening.
  3. Is there a better way I can prevent duplicate form submission on the backend?

Please sign in or create an account to participate in this conversation.