feat: phase 1 — InsForge session auth, role gates, refresh middleware, auth test suites
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Auth;
|
||||
|
||||
use App\Services\InsForge\InsForgeAuthService;
|
||||
use App\Services\InsForge\InsForgeException;
|
||||
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
|
||||
use Illuminate\Contracts\Auth\UserProvider;
|
||||
|
||||
class InsForgeUserProvider implements UserProvider
|
||||
{
|
||||
public function __construct(private readonly InsForgeAuthService $auth) {}
|
||||
|
||||
public function retrieveById($identifier): ?AuthenticatableContract
|
||||
{
|
||||
return $this->auth->profileById($identifier);
|
||||
}
|
||||
|
||||
public function retrieveByToken($identifier, #[\SensitiveParameter] $token): ?AuthenticatableContract
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function updateRememberToken(AuthenticatableContract $user, #[\SensitiveParameter] $token): void {}
|
||||
|
||||
public function retrieveByCredentials(#[\SensitiveParameter] array $credentials): ?AuthenticatableContract
|
||||
{
|
||||
if (! isset($credentials['email'], $credentials['password']) || ! is_string($credentials['email'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return $this->auth->attemptLogin($credentials['email'], (string) $credentials['password']);
|
||||
} catch (InsForgeException $exception) {
|
||||
if ($exception->getCode() === 401) {
|
||||
return null;
|
||||
}
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
}
|
||||
|
||||
public function validateCredentials(AuthenticatableContract $user, #[\SensitiveParameter] array $credentials): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rehashPasswordIfRequired(AuthenticatableContract $user, #[\SensitiveParameter] array $credentials, bool $force = false): void {}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Services\InsForge\InsForgeAuthService;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class RefreshInsForgeToken
|
||||
{
|
||||
public function __construct(private readonly InsForgeAuthService $auth) {}
|
||||
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$expiresIn = InsForgeAuthService::accessTokenExpiresInSeconds();
|
||||
|
||||
if ($expiresIn !== null && $expiresIn < 60 && ! $this->auth->refreshAccessToken()) {
|
||||
Auth::guard('web')->logoutCurrentDevice();
|
||||
|
||||
if ($request->user()) {
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
}
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
+23
-22
@@ -2,47 +2,48 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
// use Illuminate\Contracts\Auth\MustVerifyEmail;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Filament\Models\Contracts\FilamentUser;
|
||||
use Filament\Panel;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
|
||||
class User extends Authenticatable
|
||||
class User extends Authenticatable implements FilamentUser
|
||||
{
|
||||
/** @use HasFactory<\Database\Factories\UserFactory> */
|
||||
use HasFactory, Notifiable;
|
||||
use Notifiable;
|
||||
|
||||
/**
|
||||
* The attributes that are mass assignable.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
protected $fillable = [
|
||||
'id',
|
||||
'name',
|
||||
'email',
|
||||
'password',
|
||||
'role',
|
||||
'is_active',
|
||||
];
|
||||
|
||||
/**
|
||||
* The attributes that should be hidden for serialization.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
protected $hidden = [
|
||||
'password',
|
||||
'remember_token',
|
||||
];
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'email_verified_at' => 'datetime',
|
||||
'password' => 'hashed',
|
||||
'is_active' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
public function canAccessPanel(Panel $panel): bool
|
||||
{
|
||||
return (bool) $this->is_active;
|
||||
}
|
||||
|
||||
public function isAdmin(): bool
|
||||
{
|
||||
return $this->role === 'admin';
|
||||
}
|
||||
|
||||
public function isOperator(): bool
|
||||
{
|
||||
return $this->role === 'operator';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,12 +2,26 @@
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Auth\InsForgeUserProvider;
|
||||
use App\Models\User;
|
||||
use App\Services\InsForge\InsForgeAuthService;
|
||||
use App\Services\InsForge\InsForgeClient;
|
||||
use Illuminate\Contracts\Foundation\Application;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
class AppServiceProvider extends ServiceProvider
|
||||
{
|
||||
private const ADMIN_ONLY_ABILITIES = [
|
||||
'manage-products',
|
||||
'manage-stock',
|
||||
'manage-drivers',
|
||||
'manage-users',
|
||||
'view-reports',
|
||||
'view-activity-logs',
|
||||
];
|
||||
|
||||
/**
|
||||
* Register any application services.
|
||||
*/
|
||||
@@ -22,6 +36,8 @@ class AppServiceProvider extends ServiceProvider
|
||||
$config['timeout'],
|
||||
);
|
||||
});
|
||||
|
||||
Auth::provider('insforge', fn () => new InsForgeUserProvider($this->app->make(InsForgeAuthService::class)));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -29,6 +45,12 @@ class AppServiceProvider extends ServiceProvider
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
//
|
||||
Gate::before(function (User $user, string $ability) {
|
||||
if ($user->isAdmin()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return in_array($ability, self::ADMIN_ONLY_ABILITIES) ? false : null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Providers\Filament;
|
||||
|
||||
use App\Http\Middleware\RefreshInsForgeToken;
|
||||
use Filament\Http\Middleware\Authenticate;
|
||||
use Filament\Http\Middleware\AuthenticateSession;
|
||||
use Filament\Http\Middleware\DisableBladeIconComponents;
|
||||
@@ -51,6 +52,7 @@ class AdminPanelProvider extends PanelProvider
|
||||
SubstituteBindings::class,
|
||||
DisableBladeIconComponents::class,
|
||||
DispatchServingFilamentEvent::class,
|
||||
RefreshInsForgeToken::class,
|
||||
])
|
||||
->authMiddleware([
|
||||
Authenticate::class,
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\InsForge;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Session;
|
||||
|
||||
class InsForgeAuthService
|
||||
{
|
||||
public const SESSION_ACCESS_TOKEN = 'insforge_access_token';
|
||||
|
||||
public const SESSION_REFRESH_COOKIE = 'insforge_refresh_cookie';
|
||||
|
||||
public function __construct(private readonly InsForgeClient $client) {}
|
||||
|
||||
public function attemptLogin(string $email, string $password): User
|
||||
{
|
||||
$response = $this->client->send('POST', '/api/auth/sessions', [
|
||||
'email' => $email,
|
||||
'password' => $password,
|
||||
]);
|
||||
|
||||
$body = $response->json() ?? [];
|
||||
|
||||
$accessToken = $body['accessToken'] ?? $body['access_token'] ?? null;
|
||||
|
||||
if (! is_string($accessToken) || $accessToken === '') {
|
||||
throw new InsForgeException(null, 500, 'InsForge login response did not contain an access token.');
|
||||
}
|
||||
|
||||
Session::put(self::SESSION_ACCESS_TOKEN, $accessToken);
|
||||
Session::put(self::SESSION_REFRESH_COOKIE, $this->extractRefreshCookie($response) ?? ($body['refreshToken'] ?? null));
|
||||
|
||||
$authUser = is_array($body['user'] ?? null) ? $body['user'] : [];
|
||||
|
||||
$profile = $this->ensureProfile(
|
||||
id: $authUser['id'] ?? null,
|
||||
email: $email,
|
||||
password: $password,
|
||||
fallbackName: $authUser['name']
|
||||
?? (is_array($authUser['profile'] ?? null) ? ($authUser['profile']['name'] ?? null) : null)
|
||||
?? explode('@', $email)[0],
|
||||
);
|
||||
|
||||
return $this->hydrateProfile($profile);
|
||||
}
|
||||
|
||||
public function profileById(?string $id): ?User
|
||||
{
|
||||
if ($id === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$profile = $this->client
|
||||
->withToken(Session::get(self::SESSION_ACCESS_TOKEN))
|
||||
->getRecord('users', $id);
|
||||
|
||||
if ($profile === null || ! ($profile['is_active'] ?? false)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->hydrateProfile($profile);
|
||||
}
|
||||
|
||||
public function refreshAccessToken(): bool
|
||||
{
|
||||
$cookie = Session::get(self::SESSION_REFRESH_COOKIE);
|
||||
|
||||
if (! is_string($cookie) || $cookie === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
$response = $this->client->send('POST', '/api/auth/refresh', headers: ['Cookie' => $cookie]);
|
||||
} catch (InsForgeException) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$accessToken = ($response->json() ?? [])['accessToken']
|
||||
?? ($response->json() ?? [])['access_token']
|
||||
?? null;
|
||||
|
||||
if (! is_string($accessToken) || $accessToken === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
Session::put(self::SESSION_ACCESS_TOKEN, $accessToken);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function clearSession(): void
|
||||
{
|
||||
Session::forget([self::SESSION_ACCESS_TOKEN, self::SESSION_REFRESH_COOKIE]);
|
||||
}
|
||||
|
||||
public static function accessTokenExpiresInSeconds(): ?int
|
||||
{
|
||||
$token = Session::get(self::SESSION_ACCESS_TOKEN);
|
||||
|
||||
if (! is_string($token) || substr_count($token, '.') !== 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$payload = json_decode(base64_decode(strtr(explode('.', $token)[1], '-_', '+/').str_repeat('=', 4 - strlen(explode('.', $token)[1]) % 4), true), true);
|
||||
|
||||
return isset($payload['exp']) ? (int) $payload['exp'] - time() : null;
|
||||
}
|
||||
|
||||
private function ensureProfile(?string $id, string $email, string $password, string $fallbackName): array
|
||||
{
|
||||
$existing = $this->client->listRecords('users', ['email' => 'eq.'.$email])[0] ?? null;
|
||||
|
||||
if ($existing !== null) {
|
||||
return $existing;
|
||||
}
|
||||
|
||||
$attributes = array_filter([
|
||||
'id' => $id,
|
||||
'name' => $fallbackName,
|
||||
'email' => $email,
|
||||
'password' => Hash::make($password),
|
||||
'role' => 'operator',
|
||||
'is_active' => true,
|
||||
], fn ($value) => $value !== null);
|
||||
|
||||
$this->client->insertRecord('users', [$attributes], asUser: false);
|
||||
|
||||
return $this->client->listRecords('users', ['email' => 'eq.'.$email])[0] ?? $attributes;
|
||||
}
|
||||
|
||||
private function hydrateProfile(array $profile): User
|
||||
{
|
||||
$user = new User;
|
||||
|
||||
$user->forceFill([
|
||||
'id' => $profile['id'],
|
||||
'name' => $profile['name'] ?? '',
|
||||
'email' => $profile['email'],
|
||||
'password' => $profile['password'] ?? '',
|
||||
'role' => $profile['role'] ?? 'operator',
|
||||
'is_active' => (bool) ($profile['is_active'] ?? false),
|
||||
]);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
private function extractRefreshCookie($response): ?string
|
||||
{
|
||||
foreach ((array) $response->headers() as $name => $values) {
|
||||
if (strtolower((string) $name) !== 'set-cookie') {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ((array) $values as $value) {
|
||||
$firstPair = explode(';', trim((string) $value))[0];
|
||||
|
||||
if (str_contains($firstPair, 'refresh')) {
|
||||
return $firstPair;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -13,8 +13,7 @@ class InsForgeClient
|
||||
private readonly string $apiKey,
|
||||
private readonly int $timeout = 30,
|
||||
private readonly ?string $accessToken = null,
|
||||
) {
|
||||
}
|
||||
) {}
|
||||
|
||||
public function withToken(?string $accessToken): self
|
||||
{
|
||||
@@ -48,7 +47,7 @@ class InsForgeClient
|
||||
|
||||
public function getRecord(string $table, string $id, array $params = []): ?array
|
||||
{
|
||||
$params['id'] = 'eq.' . $id;
|
||||
$params['id'] = 'eq.'.$id;
|
||||
$params['limit'] = 1;
|
||||
|
||||
return $this->listRecords($table, $params)[0] ?? null;
|
||||
@@ -99,13 +98,13 @@ class InsForgeClient
|
||||
$query = [];
|
||||
|
||||
foreach ($filters as $column => $value) {
|
||||
$query[$column] = str_starts_with((string) $value, 'eq.') ? $value : 'eq.' . $value;
|
||||
$query[$column] = str_starts_with((string) $value, 'eq.') ? $value : 'eq.'.$value;
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
private function request(string $method, string $path, array $body = null, array $query = [], bool $asUser = false): Response
|
||||
public function send(string $method, string $path, array $body = [], array $query = [], bool $asUser = false, array $headers = []): Response
|
||||
{
|
||||
if ($asUser && $this->accessToken === null) {
|
||||
throw new InsForgeException(null, 401, 'No user access token available for this request.');
|
||||
@@ -114,13 +113,14 @@ class InsForgeClient
|
||||
try {
|
||||
$http = Http::baseUrl(rtrim($this->baseUrl, '/'))
|
||||
->timeout($this->timeout)
|
||||
->withHeaders($headers)
|
||||
->withToken($asUser ? $this->accessToken : $this->apiKey);
|
||||
|
||||
$verb = strtolower($method);
|
||||
|
||||
$response = in_array($verb, ['get', 'head'])
|
||||
? $http->{$verb}($path, $query)
|
||||
: $http->{$verb}($path, $body ?? []);
|
||||
: $http->{$verb}($path, $body);
|
||||
|
||||
throw_unless($response->successful(), fn () => InsForgeException::fromResponse(
|
||||
$response->status(),
|
||||
@@ -129,7 +129,12 @@ class InsForgeClient
|
||||
|
||||
return $response;
|
||||
} catch (ConnectionException $e) {
|
||||
throw new InsForgeException(null, 0, 'InsForge connection failed: ' . $e->getMessage());
|
||||
throw new InsForgeException(null, 0, 'InsForge connection failed: '.$e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private function request(string $method, string $path, ?array $body = null, array $query = [], bool $asUser = false): Response
|
||||
{
|
||||
return $this->send($method, $path, $body ?? [], $query, $asUser);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user