Add Phase 1 Identity & Access module (roles, tokens, panel auth, policies)

Implements T1.1-T1.4: Spatie role/permission seeding, Sanctum token
issuance for customer channels and the FastAPI agent (with an
ability-exact-match middleware to tell them apart), Filament admin
panel access restricted to admin-tier roles with the navigation group
order, and skeleton BookingPolicy/RoutePolicy gated on the seeded
permissions ahead of their models landing in later phases.
This commit is contained in:
Nyan Lin Paing
2026-08-05 00:27:41 +07:00
parent cfa5aed15c
commit 17dd5acd23
22 changed files with 569 additions and 12 deletions
@@ -0,0 +1,72 @@
<?php
namespace Modules\Identity\Database\Seeders;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;
class RolePermissionSeeder extends Seeder
{
/**
* @var list<string>
*/
protected array $permissions = [
'manage_catalog',
'manage_routes',
'manage_pricing',
'view_bookings',
'manage_bookings',
'view_payments',
'process_refunds',
'view_audit_log',
];
/**
* @var array<string, list<string>>
*/
protected array $roles = [
'super_admin' => [
'manage_catalog',
'manage_routes',
'manage_pricing',
'view_bookings',
'manage_bookings',
'view_payments',
'process_refunds',
'view_audit_log',
],
'admin' => [
'manage_catalog',
'manage_routes',
'manage_pricing',
'view_bookings',
'manage_bookings',
'view_payments',
'process_refunds',
'view_audit_log',
],
'support' => [
'view_bookings',
'view_payments',
'view_audit_log',
],
];
public function run(): void
{
foreach ($this->permissions as $permission) {
Permission::findOrCreate($permission, 'web');
}
// WithoutModelEvents (used by DatabaseSeeder) suppresses the model
// events Spatie's permission cache relies on to invalidate itself,
// so the freshly created permissions above must be flushed manually.
app(PermissionRegistrar::class)->forgetCachedPermissions();
foreach ($this->roles as $role => $permissions) {
Role::findOrCreate($role, 'web')->syncPermissions($permissions);
}
}
}
@@ -1 +1,8 @@
<?php
use Illuminate\Support\Facades\Route;
use Modules\Identity\Http\Controllers\TokenController;
Route::prefix('api/v1')->middleware('api')->group(function () {
Route::post('/auth/token', [TokenController::class, 'store'])->name('identity.auth.token');
});
@@ -0,0 +1,40 @@
<?php
namespace Modules\Identity\Console\Commands;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Modules\Identity\Enums\TokenAbility;
class IssueFastApiAgentTokenCommand extends Command
{
protected $signature = 'identity:issue-agent-token
{--email=fastapi-agent@system.internal : Email identifying the FastAPI agent service account}
{--name=fastapi-agent : Sanctum token name}';
protected $description = 'Provision a Sanctum token for the FastAPI AI agent, scoped to its restricted ability set';
public function handle(): int
{
$email = $this->option('email');
$tokenName = $this->option('name');
$agent = User::firstOrCreate(
['email' => $email],
[
'name' => 'FastAPI Agent',
'password' => Str::password(40),
],
);
$agent->tokens()->where('name', $tokenName)->delete();
$token = $agent->createToken($tokenName, TokenAbility::fastApiAgentAbilities());
$this->components->info('FastAPI agent token issued.');
$this->line($token->plainTextToken);
return self::SUCCESS;
}
}
@@ -0,0 +1,44 @@
<?php
namespace Modules\Identity\Enums;
enum TokenAbility: string
{
case RouteRead = 'route:read';
case BookingCreate = 'booking:create';
case BookingRead = 'booking:read';
case BookingCancel = 'booking:cancel';
case PaymentInitiate = 'payment:initiate';
/**
* Full ability set granted to customer channel tokens (mini app / mobile app).
*
* @return list<string>
*/
public static function customerAbilities(): array
{
return [
self::RouteRead->value,
self::BookingCreate->value,
self::BookingRead->value,
self::BookingCancel->value,
self::PaymentInitiate->value,
];
}
/**
* Restricted ability set granted to the FastAPI AI agent token it must
* never be able to refund, cancel someone else's booking, or write
* catalog/pricing data.
*
* @return list<string>
*/
public static function fastApiAgentAbilities(): array
{
return [
self::RouteRead->value,
self::BookingCreate->value,
self::BookingRead->value,
];
}
}
@@ -0,0 +1,37 @@
<?php
namespace Modules\Identity\Http\Controllers;
use App\Models\User;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
use Modules\Identity\Enums\TokenAbility;
use Modules\Identity\Http\Requests\IssueTokenRequest;
class TokenController extends Controller
{
/**
* Exchange customer credentials (mini app / mobile app) for a Sanctum
* token carrying the full customer ability set.
*/
public function store(IssueTokenRequest $request): array
{
$user = User::where('email', $request->string('email'))->first();
if (! $user || ! Hash::check($request->string('password'), $user->password)) {
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
$token = $user->createToken(
$request->string('device_name')->toString(),
TokenAbility::customerAbilities(),
);
return [
'token' => $token->plainTextToken,
];
}
}
@@ -0,0 +1,38 @@
<?php
namespace Modules\Identity\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Modules\Identity\Enums\TokenAbility;
use Symfony\Component\HttpFoundation\Response;
class EnsureFastApiAgent
{
/**
* Identify the FastAPI AI agent by its token's ability scope rather than
* a role the agent has no admin-panel role, only a Sanctum token
* restricted to exactly route:read, booking:create, booking:read.
*
* A customer token also carries those three abilities (plus more), so
* membership alone can't tell agent and customer tokens apart the
* ability set must match exactly.
*/
public function handle(Request $request, Closure $next): Response
{
$token = $request->user()?->currentAccessToken();
if (! $token) {
abort(403, 'This action requires a FastAPI agent token.');
}
$actual = collect($token->abilities)->sort()->values()->all();
$expected = collect(TokenAbility::fastApiAgentAbilities())->sort()->values()->all();
if ($actual !== $expected) {
abort(403, 'This action requires a FastAPI agent token.');
}
return $next($request);
}
}
@@ -0,0 +1,25 @@
<?php
namespace Modules\Identity\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class IssueTokenRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/**
* @return array<string, array<int, string>>
*/
public function rules(): array
{
return [
'email' => ['required', 'email'],
'password' => ['required', 'string'],
'device_name' => ['required', 'string', 'max:255'],
];
}
}
@@ -0,0 +1,41 @@
<?php
use App\Models\User;
use Illuminate\Support\Facades\Route;
use Modules\Identity\Enums\TokenAbility;
beforeEach(function () {
Route::middleware(['auth:sanctum', 'fastapi.agent'])
->get('/__test/fastapi-agent-only', fn () => response()->json(['ok' => true]));
});
test('a token scoped to exactly the agent abilities is allowed through', function () {
$agent = User::factory()->create();
$token = $agent->createToken('fastapi-agent', TokenAbility::fastApiAgentAbilities())->plainTextToken;
$this->withHeader('Authorization', "Bearer {$token}")
->getJson('/__test/fastapi-agent-only')
->assertSuccessful();
});
test('a customer token carrying broader abilities is rejected', function () {
$customer = User::factory()->create();
$token = $customer->createToken('iphone', TokenAbility::customerAbilities())->plainTextToken;
$this->withHeader('Authorization', "Bearer {$token}")
->getJson('/__test/fastapi-agent-only')
->assertForbidden();
});
test('a token missing one of the agent abilities is rejected', function () {
$user = User::factory()->create();
$token = $user->createToken('partial', [TokenAbility::RouteRead->value, TokenAbility::BookingCreate->value])->plainTextToken;
$this->withHeader('Authorization', "Bearer {$token}")
->getJson('/__test/fastapi-agent-only')
->assertForbidden();
});
test('an unauthenticated request is rejected', function () {
$this->getJson('/__test/fastapi-agent-only')->assertUnauthorized();
});
@@ -0,0 +1,46 @@
<?php
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Modules\Identity\Enums\TokenAbility;
test('customer token endpoint issues a token with the full customer ability set', function () {
$user = User::factory()->create([
'password' => Hash::make('secret-password'),
]);
$response = $this->postJson('/api/v1/auth/token', [
'email' => $user->email,
'password' => 'secret-password',
'device_name' => 'iphone',
]);
$response->assertSuccessful()->assertJsonStructure(['token']);
$accessToken = $user->tokens()->sole();
expect($accessToken->abilities)->toEqualCanonicalizing(TokenAbility::customerAbilities());
});
test('customer token endpoint rejects invalid credentials', function () {
$user = User::factory()->create([
'password' => Hash::make('secret-password'),
]);
$response = $this->postJson('/api/v1/auth/token', [
'email' => $user->email,
'password' => 'wrong-password',
'device_name' => 'iphone',
]);
$response->assertUnprocessable();
expect($user->tokens()->count())->toBe(0);
});
test('identity:issue-agent-token command provisions a token scoped to the agent ability set', function () {
$this->artisan('identity:issue-agent-token')->assertSuccessful();
$agent = User::where('email', 'fastapi-agent@system.internal')->sole();
$token = $agent->tokens()->sole();
expect($token->abilities)->toEqualCanonicalizing(TokenAbility::fastApiAgentAbilities());
});