Files
portal-api/app/Services/Customer/CustomerImpersonationService.php
T
2026-09-28 16:39:22 +07:00

62 lines
2.0 KiB
PHP

<?php
namespace App\Services\Customer;
use App\Http\Resources\Api\Client\ClientResource;
use App\Models\Log;
use App\Models\User;
use App\Repositories\Customer\CustomerRepositoryInterface;
use App\Services\Api\Client\ClientAuthService;
use App\Services\Customer\Concerns\ResolvesCustomer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Tymon\JWTAuth\Facades\JWTAuth;
class CustomerImpersonationService
{
use ResolvesCustomer;
private const TTL_SECONDS = 120;
public function __construct(
private readonly CustomerRepositoryInterface $customerRepository,
private readonly ClientAuthService $clientAuthService,
) {}
/**
* Tạo mã impersonate một lần (hiệu lực 120s) để admin đăng nhập hộ khách hàng.
* portal-client đổi code lấy token qua endpoint public `v1/client/impersonate/exchange`.
*/
public function createLoginCode(string $uuid, User $admin, Request $request): string
{
$customer = $this->resolveCustomer($uuid);
abort_if((int) $customer->status !== 1, 422, 'Khách hàng không hoạt động, không thể đăng nhập hộ.');
$token = JWTAuth::fromUser($customer);
$refreshToken = $this->clientAuthService->createRefreshToken($customer->id);
$clientResource = (new ClientResource($customer->loadCount(['vps', 'hosting', 'domain'])))->resolve($request);
$code = Str::random(48);
Cache::put("impersonate:{$code}", [
'token' => $token,
'refresh_token' => $refreshToken,
'client' => $clientResource,
], self::TTL_SECONDS);
Log::create([
'agent' => 'admin',
'client_ip' => $request->ip(),
'description' => sprintf(
'%s đăng nhập hộ khách hàng %s',
$admin->username ?? $admin->email ?? 'Admin',
$customer->email,
),
'customer_id' => $customer->id,
]);
return $code;
}
}