Skip to content

Commit

Permalink
Add RequireCsrfToken.
Browse files Browse the repository at this point in the history
Signed-off-by: crynobone <[email protected]>
  • Loading branch information
crynobone committed Dec 8, 2015
1 parent 2151a97 commit 8057b7b
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions Middleware/RequireCsrfToken.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php namespace Orchestra\Http\Middleware;

use Closure;
use Illuminate\Support\Str;
use Illuminate\Contracts\Encryption\Encrypter;
use Illuminate\Session\TokenMismatchException;

class RequireCsrfToken
{
/**
* The encrypter implementation.
*
* @var \Illuminate\Contracts\Encryption\Encrypter
*/
protected $encrypter;

/**
* Create a new filter instance.
*
* @param \Illuminate\Contracts\Encryption\Encrypter $encrypter
*/
public function __construct(Encrypter $encrypter)
{
$this->encrypter = $encrypter;
}

/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
if (! $this->tokensMatch($request)) {
throw new TokenMismatchException();
}

return $next($request);
}

/**
* Determine if the session and input CSRF tokens match.
*
* @param \Illuminate\Http\Request $request
*
* @return bool
*/
protected function tokensMatch($request)
{
$token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN');

if (! $token && $header = $request->header('X-XSRF-TOKEN')) {
$token = $this->encrypter->decrypt($header);
}

return Str::equals($request->session()->token(), $token);
}
}

0 comments on commit 8057b7b

Please sign in to comment.