Skip to content

Commit

Permalink
We can make this middleware significantly simpler
Browse files Browse the repository at this point in the history
  • Loading branch information
DaneEveritt committed May 22, 2022
1 parent 0fa33e0 commit 56f15c1
Showing 1 changed file with 5 additions and 36 deletions.
41 changes: 5 additions & 36 deletions app/Http/Middleware/EnsureStatefulRequests.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,10 @@

namespace Pterodactyl\Http\Middleware;

use Illuminate\Http\Request;
use Illuminate\Routing\Pipeline;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;

class EnsureStatefulRequests extends EnsureFrontendRequestsAreStateful
{
/**
* {@inheritDoc}
*/
public function handle($request, $next)
{
$this->configureSecureCookieSessions();

return (new Pipeline(app()))
->send($request)
->through($this->isStateful($request) ? $this->statefulMiddleware() : [])
->then(fn ($request) => $next($request));
}

/**
* Determines if a request is stateful or not. This is determined using the default
* Sanctum "fromFrontend" helper method. However, we also check if the request includes
Expand All @@ -32,26 +15,12 @@ public function handle($request, $next)
* We don't want to support API usage using the cookies, except for requests stemming
* from the front-end we control.
*/
protected function isStateful(Request $request): bool
{
return static::fromFrontend($request) || $request->hasCookie(config('session.cookie'));
}

/**
* Returns the middleware to be applied to a stateful request to the API.
*/
protected function statefulMiddleware(): array
public static function fromFrontend($request)
{
return [
function ($request, $next) {
$request->attributes->set('sanctum', true);
if (parent::fromFrontend($request)) {
return true;
}

return $next($request);
},
config('sanctum.middleware.encrypt_cookies', EncryptCookies::class),
AddQueuedCookiesToResponse::class,
StartSession::class,
config('sanctum.middleware.verify_csrf_token', VerifyCsrfToken::class),
];
return $request->hasCookie(config('session.cookie'));
}
}

0 comments on commit 56f15c1

Please sign in to comment.