feat: phase 1 — InsForge session auth, role gates, refresh middleware, auth test suites

This commit is contained in:
sean
2026-08-25 18:01:11 +07:00
parent 046cefc56c
commit aad2b5e256
15 changed files with 613 additions and 36 deletions
+109
View File
@@ -0,0 +1,109 @@
<?php
namespace Tests\Feature\Auth;
use App\Models\User;
use App\Services\InsForge\InsForgeAuthService;
use Filament\Auth\Pages\Login;
use Illuminate\Support\Facades\Session;
use Livewire\Livewire;
use Tests\Support\InsForgeFake;
use Tests\TestCase;
class AuthenticationTest extends TestCase
{
private function adminProfile(array $overrides = []): array
{
return array_merge([
'id' => '11111111-1111-1111-1111-111111111111',
'name' => 'Admin BerasPro',
'email' => 'admin@beraspro.test',
'password' => '$2y$04$hash',
'role' => 'admin',
'is_active' => true,
], $overrides);
}
public function test_login_page_renders_for_guest(): void
{
$this->get('/admin/login')->assertOk();
}
public function test_unauthenticated_user_is_redirected_to_login(): void
{
$this->get('/admin')->assertRedirect('/admin/login');
}
public function test_user_can_login_with_valid_credentials(): void
{
InsForgeFake::fakeLoginSuccess($this->adminProfile());
Livewire::test(Login::class)
->fillForm(['email' => 'admin@beraspro.test', 'password' => 'secret'])
->call('authenticate')
->assertHasNoErrors();
$this->assertAuthenticated();
$this->assertSame(
InsForgeFake::$accessToken,
Session::get(InsForgeAuthService::SESSION_ACCESS_TOKEN),
);
$user = auth()->user();
$this->assertInstanceOf(User::class, $user);
$this->assertTrue($user->isAdmin());
}
public function test_mirror_profile_is_created_when_missing(): void
{
InsForgeFake::fakeLoginSuccess($this->adminProfile());
unset(InsForgeFake::$profiles['admin@beraspro.test']);
Livewire::test(Login::class)
->fillForm(['email' => 'admin@beraspro.test', 'password' => 'secret'])
->call('authenticate');
$this->assertArrayHasKey('admin@beraspro.test', InsForgeFake::$profiles);
$this->assertSame('operator', InsForgeFake::$profiles['admin@beraspro.test']['role']);
}
public function test_invalid_credentials_do_not_authenticate(): void
{
InsForgeFake::fakeLoginFailure();
Livewire::test(Login::class)
->fillForm(['email' => 'admin@beraspro.test', 'password' => 'wrong'])
->call('authenticate')
->assertHasErrors();
$this->assertGuest();
}
public function test_inactive_user_cannot_access_panel(): void
{
InsForgeFake::fakeLoginSuccess($this->adminProfile(['is_active' => false]));
Livewire::test(Login::class)
->fillForm(['email' => 'admin@beraspro.test', 'password' => 'secret'])
->call('authenticate');
$this->get('/admin')->assertRedirect('/admin/login');
$this->assertGuest();
}
public function test_logout_clears_insforge_tokens(): void
{
InsForgeFake::fakeLoginSuccess($this->adminProfile());
Livewire::test(Login::class)
->fillForm(['email' => 'admin@beraspro.test', 'password' => 'secret'])
->call('authenticate');
$this->post('/admin/logout');
$this->assertGuest();
$this->assertNull(Session::get(InsForgeAuthService::SESSION_ACCESS_TOKEN));
}
}
+66
View File
@@ -0,0 +1,66 @@
<?php
namespace Tests\Feature\Auth;
use App\Models\User;
use Illuminate\Support\Facades\Gate;
use Tests\Support\InsForgeFake;
use Tests\TestCase;
class AuthorizationTest extends TestCase
{
private const ADMIN_ONLY_ABILITIES = [
'manage-products',
'manage-stock',
'manage-drivers',
'manage-users',
'view-reports',
'view-activity-logs',
];
private function loginUser(array $profile): User
{
InsForgeFake::fakeLoginSuccess($profile);
$user = new User;
$user->forceFill([
'id' => $profile['id'],
'name' => $profile['name'],
'email' => $profile['email'],
'role' => $profile['role'],
'is_active' => true,
]);
$this->actingAs($user);
return $user;
}
public function test_admin_is_granted_every_ability(): void
{
$this->loginUser([
'id' => '22222222-2222-2222-2222-222222222222',
'name' => 'Admin',
'email' => 'admin@beraspro.test',
'role' => 'admin',
]);
foreach (self::ADMIN_ONLY_ABILITIES as $ability) {
$this->assertTrue(Gate::allows($ability), "admin should be allowed {$ability}");
}
}
public function test_operator_is_denied_admin_only_abilities(): void
{
$this->loginUser([
'id' => '33333333-3333-3333-3333-333333333333',
'name' => 'Operator',
'email' => 'operator@beraspro.test',
'role' => 'operator',
]);
foreach (self::ADMIN_ONLY_ABILITIES as $ability) {
$this->assertTrue(Gate::denies($ability), "operator should be denied {$ability}");
}
}
}
+115
View File
@@ -0,0 +1,115 @@
<?php
namespace Tests\Support;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
class InsForgeFake
{
public static array $profiles = [];
public static string $accessToken = 'fake.header.';
public static function reset(): void
{
self::$profiles = [];
}
public static function fakeLoginSuccess(array $profile): void
{
self::reset();
self::$accessToken = 'eyJhbGciOiJIUzI1NiJ9.'.base64_encode(json_encode([
'sub' => $profile['id'],
'exp' => now()->addHour()->getTimestamp(),
])).'.sig';
self::$profiles[$profile['email']] = $profile;
Http::fake([
'*/api/auth/sessions' => Http::response([
'accessToken' => self::$accessToken,
'refreshToken' => 'fake-refresh-token',
'user' => [
'id' => $profile['id'],
'email' => $profile['email'],
'name' => $profile['name'],
],
], 200, [
'Set-Cookie' => 'insforge_refresh_token=fake-refresh-cookie; Path=/; HttpOnly',
]),
'*/api/auth/refresh' => Http::response([
'accessToken' => self::$accessToken,
], 200),
'*/api/database/records/users*' => function (Request $request) {
return self::handleUsersRequest($request);
},
]);
}
public static function fakeLoginFailure(): void
{
self::reset();
Http::fake([
'*/api/auth/sessions' => Http::response([
'error' => 'AUTH_UNAUTHORIZED',
'message' => 'Invalid credentials',
'statusCode' => 401,
], 401),
]);
}
public static function fakeProfile(array $profile): void
{
self::$profiles[$profile['email']] = $profile;
}
private static function handleUsersRequest(Request $request)
{
parse_str((string) parse_url($request->url(), PHP_URL_QUERY) ?? '', $query);
$method = strtoupper($request->method());
if ($method === 'GET') {
foreach (self::$profiles as $profile) {
if (($query['email'] ?? null) === 'eq.'.$profile['email']
|| ($query['id'] ?? null) === 'eq.'.$profile['id']) {
return Http::response([$profile], 200);
}
}
return Http::response([], 200);
}
if ($method === 'POST') {
$payload = $request->data()[0] ?? [];
if (! is_array($payload)) {
return Http::response([], 201);
}
self::$profiles[$payload['email']] = array_merge([
'role' => 'operator',
'is_active' => true,
], $payload);
return Http::response([], 201);
}
if ($method === 'PATCH') {
$targetId = str_replace('eq.', '', $query['id'] ?? '');
foreach (self::$profiles as &$profile) {
if ($profile['id'] === $targetId) {
$profile = array_merge($profile, $request->data());
}
}
unset($profile);
return Http::response([], 200);
}
return Http::response([], 200);
}
}