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:
40
app/Http/Resources/ApiTokenResource.php
Normal file
40
app/Http/Resources/ApiTokenResource.php
Normal file
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Models\ApiToken;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/**
|
||||
* Never the token itself, which only exists in the answer that made it.
|
||||
*
|
||||
* @mixin ApiToken
|
||||
*/
|
||||
class ApiTokenResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
'prefix' => $this->prefix,
|
||||
'abilities' => $this->abilities ?? [],
|
||||
'owner' => ['id' => $this->user_id, 'name' => $this->user?->name],
|
||||
'status' => match (true) {
|
||||
$this->revoked_at !== null => 'revoked',
|
||||
$this->expires_at->isPast() => 'expired',
|
||||
default => 'active',
|
||||
},
|
||||
'expires_at' => $this->expires_at->toIso8601String(),
|
||||
'last_used_at' => $this->last_used_at?->toIso8601String(),
|
||||
'revoked_at' => $this->revoked_at?->toIso8601String(),
|
||||
'created_at' => $this->created_at?->toIso8601String(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Support\Permissions;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
@@ -35,7 +36,10 @@ class UserResource extends JsonResource
|
||||
'roles' => $this->whenLoaded('roles', fn () => $this->roles->pluck('name')->values()),
|
||||
'permissions' => $this->when(
|
||||
$request->routeIs('api.v1.me'),
|
||||
fn () => $this->getAllPermissions()->pluck('name')->values(),
|
||||
// Through a machine token, only what the token may do.
|
||||
fn () => $this->resource->currentAccessToken()
|
||||
? collect(Permissions::all())->filter(fn (string $permission) => $this->resource->can($permission))->values()
|
||||
: $this->getAllPermissions()->pluck('name')->values(),
|
||||
),
|
||||
|
||||
// Roles reported by the identity server. Informational only: they
|
||||
|
||||
Reference in New Issue
Block a user