Skip to content

Commit

Permalink
auth fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Wirewraith committed Dec 7, 2024
1 parent d814dc3 commit a8c45cd
Show file tree
Hide file tree
Showing 13 changed files with 74 additions and 87 deletions.
14 changes: 1 addition & 13 deletions app/Http/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@

namespace App\Http;

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
use Illuminate\Routing\Router;

class Kernel extends HttpKernel
{
Expand Down Expand Up @@ -43,9 +41,8 @@ class Kernel extends HttpKernel
],

'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\ApiAuthenticate::class,
\App\Http\Middleware\Throttle::class,
],
];
Expand All @@ -58,7 +55,6 @@ class Kernel extends HttpKernel
* @var array<string, class-string|string>
*/
protected $middlewareAliases = [
'apiauth' => \App\Http\Middleware\ApiAuthenticate::class,
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
Expand All @@ -71,12 +67,4 @@ class Kernel extends HttpKernel
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];

public function __construct(Application $app, Router $router)
{
// Our custom throttle middleware relies on user auth being done first
array_push($this->middlewarePriority, \App\Http\Middleware\Throttle::class);

parent::__construct($app, $router);
}
}
51 changes: 0 additions & 51 deletions app/Http/Middleware/ApiAuthenticate.php

This file was deleted.

4 changes: 3 additions & 1 deletion app/Http/Middleware/CanAccessAdminRoutes.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;

Expand All @@ -17,7 +18,8 @@ class CanAccessAdminRoutes
*/
public function handle(Request $request, Closure $next)
{
if (! $request->user()->isAdmin() && ! $request->user()->isGameAdmin()) {
$user = Auth::user();
if (! $user->isAdmin() && ! $user->isGameAdmin()) {
return $request->expectsJson()
? abort(403, 'You don\'t have permission to access this route.')
: Redirect::guest(URL::route('dashboard'));
Expand Down
3 changes: 2 additions & 1 deletion app/Http/Middleware/EnsureUserIsAdmin.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;

Expand All @@ -17,7 +18,7 @@ class EnsureUserIsAdmin
*/
public function handle(Request $request, Closure $next)
{
if (! $request->user()?->isAdmin()) {
if (! Auth::user()?->isAdmin()) {
return $request->expectsJson()
? abort(403, 'You don\'t have permission to access this route.')
: Redirect::guest(URL::route('dashboard'));
Expand Down
3 changes: 2 additions & 1 deletion app/Http/Middleware/EnsureUserIsGameAdmin.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;

Expand All @@ -17,7 +18,7 @@ class EnsureUserIsGameAdmin
*/
public function handle(Request $request, Closure $next)
{
if (! $request->user()->isGameAdmin()) {
if (! Auth::user()->isGameAdmin()) {
return $request->expectsJson()
? abort(403, 'You don\'t have permission to access this route.')
: Redirect::guest(URL::route('dashboard'));
Expand Down
3 changes: 2 additions & 1 deletion app/Http/Middleware/Throttle.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@

use Closure;
use Illuminate\Routing\Middleware\ThrottleRequests;
use Illuminate\Support\Facades\Auth;

class Throttle extends ThrottleRequests
{
public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1, $prefix = '')
{
if ($request->user()?->isAdmin()) {
if (Auth::user()?->isAdmin()) {
return $next($request);
}

Expand Down
5 changes: 1 addition & 4 deletions app/Policies/TestPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@ class TestPolicy
/**
* Create a new policy instance.
*/
public function __construct()
{
//
}
public function __construct() {}

public function view(User $user): bool
{
Expand Down
30 changes: 18 additions & 12 deletions app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
namespace App\Providers;

use App\Models\PersonalAccessToken;
use App\Services\Auth\ApiSanctumGuard;
use Dedoc\Scramble\Scramble;
use Dedoc\Scramble\Support\Generator\OpenApi;
use Dedoc\Scramble\Support\Generator\SecurityScheme;
use Illuminate\Auth\Access\Gate as AccessGate;
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Application;
use Illuminate\Auth\RequestGuard;
use Illuminate\Routing\Route;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
Expand All @@ -24,8 +24,6 @@ class AppServiceProvider extends ServiceProvider
*/
public function register()
{
$this->registerAccessGate();

if ($this->app->environment(['local', 'staging'])) {
$this->app->register(\Laravel\Telescope\TelescopeServiceProvider::class);
$this->app->register(TelescopeServiceProvider::class);
Expand All @@ -43,14 +41,22 @@ public function boot()

Sanctum::usePersonalAccessTokenModel(PersonalAccessToken::class);

Auth::resolved(function ($auth) {
$auth->extend('api', function ($app, $name, array $config) use ($auth) {
return tap($this->createApiGuard($auth, $config), function ($guard) {
app()->refresh('request', $guard, 'setRequest');
});
});
});

Scramble::extendOpenApi(function (OpenApi $openApi) {
$openApi->secure(
SecurityScheme::http('bearer', 'JWT')
);
});

Scramble::routes(function (Route $route) {
return $route->getDomain() === config('app.api_url');
return $route->getDomain() === preg_replace('(^https?://)', '', config('app.api_url'));
});

Event::listen(function (\SocialiteProviders\Manager\SocialiteWasCalled $event) {
Expand All @@ -69,12 +75,12 @@ protected function loadHelpers()
}
}

protected function registerAccessGate()
protected function createApiGuard($auth, $config)
{
$this->app->scoped(GateContract::class, function (Application $app) {
return new AccessGate($app, function () {
return request()->user();
});
});
return new RequestGuard(
new ApiSanctumGuard($auth, config('sanctum.expiration'), $config['provider']),
request(),
$auth->createUserProvider($config['provider'] ?? null)
);
}
}
2 changes: 1 addition & 1 deletion app/Providers/AuthServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class AuthServiceProvider extends ServiceProvider
*/
public function boot(): void
{
Gate::before(function (User $user, string $ability) {
Gate::before(function (User $user) {
if ($user->isAdmin()) {
// Admins can do anything
return true;
Expand Down
2 changes: 1 addition & 1 deletion app/Providers/RouteServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public function boot()
}

$this->routes(function () {
Route::middleware('api')
Route::middleware(['auth:api', 'api'])
->domain(config('app.api_url'))
->group(base_path('routes/api.php'));

Expand Down
38 changes: 38 additions & 0 deletions app/Services/Auth/ApiSanctumGuard.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace App\Services\Auth;

use Illuminate\Http\Request;
use Laravel\Sanctum\Events\TokenAuthenticated;
use Laravel\Sanctum\Guard as SanctumGuard;
use Laravel\Sanctum\Sanctum;

class ApiSanctumGuard extends SanctumGuard
{
/**
* Override to avoid:
* - Checking 'web' guard first (or whatever other guards are in sanctum.php)
* - Setting modified fields of PAT
*/
public function __invoke(Request $request)
{
if ($token = $this->getTokenFromRequest($request)) {
$model = Sanctum::$personalAccessTokenModel;

$accessToken = $model::findToken($token);

if (! $this->isValidAccessToken($accessToken) ||
! $this->supportsTokens($accessToken->tokenable)) {
return;
}

$tokenable = $accessToken->tokenable->withAccessToken(
$accessToken
);

event(new TokenAuthenticated($accessToken));

return $tokenable;
}
}
}
4 changes: 4 additions & 0 deletions config/auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'api',
'provider' => 'users',
]
],

/*
Expand Down
2 changes: 1 addition & 1 deletion config/scramble.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
* Your API domain. By default, app domain is used. This is also a part of the default API routes
* matcher, so when implementing your own, make sure you use this config if needed.
*/
'api_domain' => config('app.api_url'),
'api_domain' => preg_replace('(^https?://)', '', config('app.api_url')),

'info' => [
/*
Expand Down

0 comments on commit a8c45cd

Please sign in to comment.