Skip to content

Commit

Permalink
Add `Orchestra\Foundation\Http\Middleware\RequireCsrfToken for explic…
Browse files Browse the repository at this point in the history
…it route middleware.

Signed-off-by: crynobone <crynobone@gmail.com>
  • Loading branch information
crynobone committed Oct 29, 2015
1 parent 93b14a2 commit 3389136
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 2 deletions.
61 changes: 61 additions & 0 deletions src/Http/Middleware/RequireCsrfToken.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php namespace Orchestra\Foundation\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);
}
}
4 changes: 2 additions & 2 deletions src/Providers/RouteServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use Orchestra\Foundation\Http\Middleware\Authenticate;
use Orchestra\Foundation\Http\Middleware\CanBeInstalled;
use Orchestra\Foundation\Http\Middleware\CanRegisterUser;
use Orchestra\Foundation\Http\Middleware\VerifyCsrfToken;
use Orchestra\Foundation\Http\Middleware\RequireCsrfToken;
use Orchestra\Foundation\Http\Middleware\RedirectIfInstalled;
use Orchestra\Support\Providers\Traits\MiddlewareProviderTrait;
use Orchestra\Foundation\Http\Middleware\RedirectIfAuthenticated;
Expand All @@ -32,7 +32,7 @@ class RouteServiceProvider extends ServiceProvider
protected $routeMiddleware = [
'orchestra.auth' => Authenticate::class,
'orchestra.can' => Can::class,
'orchestra.csrf' => VerifyCsrfToken::class,
'orchestra.csrf' => RequireCsrfToken::class,
'orchestra.guest' => RedirectIfAuthenticated::class,
'orchestra.installable' => CanBeInstalled::class,
'orchestra.installed' => RedirectIfInstalled::class,
Expand Down

0 comments on commit 3389136

Please sign in to comment.