Issue machine tokens with limited permissions and an expiry
A token acts as the person who made it, within the permissions it was given and those they still hold, checked on every request. Permission checks now go through one gate rule, since spatie's answered first and never asked the token. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -37,6 +37,7 @@ use App\Policies\TalkPolicy;
|
||||
use App\Policies\TechnologyPolicy;
|
||||
use App\Policies\TestimonialPolicy;
|
||||
use App\Policies\UserPolicy;
|
||||
use App\Support\Permissions;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Spatie\Permission\Models\Role;
|
||||
@@ -63,12 +64,35 @@ class AuthServiceProvider extends ServiceProvider
|
||||
Gate::policy(User::class, UserPolicy::class);
|
||||
Gate::policy(Role::class, RolePolicy::class);
|
||||
|
||||
// Super admins bypass every permission check. Granting the role this
|
||||
// way rather than by attaching every permission means the role can
|
||||
// never fall behind as the catalogue grows.
|
||||
// The one place a permission is granted — spatie's own gate check is
|
||||
// switched off (config/permission.php) so nothing answers before this.
|
||||
//
|
||||
// Returning null (not false) when the role is absent is important: it
|
||||
// lets the normal policy chain run instead of short-circuiting it.
|
||||
Gate::before(fn (User $user, string $ability) => $user->hasRole('super_admin') ? true : null);
|
||||
// Super admins bypass every check. Granting the role this way rather
|
||||
// than by attaching every permission means the role can never fall
|
||||
// behind as the catalogue grows. Returning null (not false) when
|
||||
// nothing applies lets the normal policy chain run.
|
||||
//
|
||||
// A machine token narrows all of that: a permission must be one the
|
||||
// token was given *and* one its owner holds. A policy is not a
|
||||
// permission, so it runs as usual and asks for permissions, which come
|
||||
// back here.
|
||||
Gate::before(function (User $user, string $ability): ?bool {
|
||||
$token = $user->currentAccessToken();
|
||||
|
||||
if ($token !== null) {
|
||||
if (! in_array($ability, Permissions::all(), true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $token->allows($ability)
|
||||
&& ($user->hasRole('super_admin') || $user->checkPermissionTo($ability));
|
||||
}
|
||||
|
||||
if ($user->hasRole('super_admin')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $user->checkPermissionTo($ability) ?: null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user