ldc-boutique-cnc-sable/app/Providers/AuthServiceProvider.php

95 lines
2.9 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Providers;
use App\Dto\FaqDto;
use App\Dto\PageDto;
use App\Dto\TagDto;
use App\Models\Customer;
use App\Policies\Backend\FaqPolicy;
use App\Policies\Backend\PagePolicy;
use App\Policies\Backend\TagPolicy;
use App\Policies\Frontend\BasketPolicy;
use App\Services\CrmService;
use Domain\Models\ValueObjects\BasketProduct;
use Domain\Services\ShopperService;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Gate;
use Infrastructure\Adapters\Services\AppAdminAuthService;
use Infrastructure\Adapters\Services\AppCustomerAuthService;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array<class-string, class-string>
*/
#[\Override]
protected $policies = [
// * Policies Exceptions
BasketProduct::class => BasketPolicy::class,
FaqDto::class => FaqPolicy::class,
PageDto::class => PagePolicy::class,
TagDto::class => TagPolicy::class,
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->app->singleton(
AppAdminAuthService::class,
fn ($app): AppAdminAuthService => new AppAdminAuthService(
Auth::guard('backend')
)
);
$this->app->singleton(
AppCustomerAuthService::class,
fn ($app): AppCustomerAuthService => new AppCustomerAuthService(
Auth::guard('frontend'),
$app->make(CrmService::class)
)
);
Auth::shouldUse($this->currentRouteGuard());
Gate::define(
'customerPassOrders',
fn (Customer $customer): bool => resolve(ShopperService::class)
->canCustomerPassOrdersApp($customer->getId())
);
$this->registerPolicies();
Gate::guessPolicyNamesUsing(function (string $modelClass) {
$context = $this->currentRouteGuard() === 'frontend' ? 'Frontend' : 'Backend';
$classBasename = class_basename($modelClass);
$policyClass = "App\\Policies\\{$context}\\{$classBasename}Policy";
return class_exists($policyClass) ? $policyClass : null;
});
}
private function currentRouteGuard(): string
{
$request = $this->app->make(Request::class);
$defaultGuard = Config::string('auth.defaults.guard', 'frontend');
return match (true) {
$request->is('bo', 'bo/*') => 'backend',
$request->is('api', 'api/*') => 'api',
default => $defaultGuard,
};
}
}