简体   繁体   中英

Displaying a flash message and redirecting to another page after Token mismatch exception

I have a simple voting application where I try to prevent double submission using the back button by using csrf tokens. My route looks like this

Route::group(array('before' => 'csrf'), function(){
   Route::post('votesuccess', array('as' => 'votesuccess', 'uses'=>'VoteController@votesuccess'));
});

I have filters that looks like this

Route::filter('csrf', function()
 {

  if (Session::token() != Input::get('_token'))
    {

     return Response::to('voteresults');

      Session::flash('message', 'You are trying to vote twice!');

    }
});

Route::filter('no-cache',function($route, $request, $response){

  header("Cache-Control: no-cache,no-store, must-revalidate"); //HTTP 1.1
  header("Pragma: no-cache"); //HTTP 1.0
  header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

});

Part of my controller looks like this

Session::put('_token', md5(microtime())); 

        // redirect
Session::flash('message', 'Successfully Cast your vote!');
return Redirect::route('voteresults');

It works fine and sure enough if someone clicks the back button and tries to re submit it brings Illuminate \\ Session \\ TokenMismatchException which is all well and good except I want it to redirect to the voteresults view and display a flash message informing the user that they are trying to cheat. Any ideas about how I can achieve this?

You need to create a handler for the TokenMismatchException a good place to put this would be in start/global.php and would look something like

App::error(function(TokenMismatchException $exception)
{
    Session::flash('message', 'You are trying to vote twice!');
    return Redirect::to('voteresults');
});

For more information on handling exceptions in Laravel have a look here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM