src/Service/AgencyCabinetAuth.php line 60

Open in your IDE?
  1. <?php
  2. namespace App\Service;
  3. use App\Entity\Manager;
  4. use App\Repository\ManagerRepository;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Psr\Log\LoggerInterface;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  10. use Symfony\Contracts\HttpClient\HttpClientInterface;
  11. /**
  12.  * Вхід менеджера агенції в кабінет pro (SPEC-T22, SPEC-T24, SPEC-T27).
  13.  *
  14.  * Спершу — сесійний вхід pro: пароль на `/login/auth` або «Увійти в кабінет» з адмінки. Інакше — cookie
  15.  * `authautologin`, яку ставлять control і вхід pro: токен перевіряємо лише на сервері, у content.otpusk.com/me/auth/me.
  16.  * Cookie `loginData` і будь-які дані від клієнта не враховуються (SEC-01).
  17.  */
  18. class AgencyCabinetAuth
  19. {
  20.     public const LOGIN_URL = '/login/auth';
  21.     public const COOKIE = 'authautologin';
  22.     /** Cookie, які прибирає вихід: ті самі, що до T-01. */
  23.     public const LOGOUT_COOKIES = ['authautologin', 'loginData', 'cookie_login'];
  24.     public const COOKIE_DOMAIN = '.otpusk.com';
  25.     /** Заголовок відповіді з причиною, чому вхід не підтверджено: прод-лог пише лише помилки. */
  26.     public const FAILURE_HEADER = 'X-Agency-Cabinet-Auth';
  27.     private const ME_URL = 'https://content.otpusk.com/me/auth/me/';
  28.     /** Новий ключ: значенням `loginData` із сесій до T-01 (їх писав неперевірений POST /api/login) не довіряємо. */
  29.     private const SESSION_KEY = 'agencyCabinet';
  30.     /** Входи, які сесія pro пам'ятає сама, без cookie `authautologin`. */
  31.     private const SESSION_LOGINS = ['password', 'admin'];
  32.     private HttpClientInterface $httpClient;
  33.     private ManagerRepository $managers;
  34.     private EntityManagerInterface $em;
  35.     private LoggerInterface $logger;
  36.     /** Причина останньої невдачі manager(): no-token, rejected, unavailable, no-agency, no-manager, no-admin. */
  37.     private ?string $failure = null;
  38.     public function __construct(
  39.         HttpClientInterface $httpClient,
  40.         ManagerRepository $managers,
  41.         EntityManagerInterface $em,
  42.         LoggerInterface $logger
  43.     ) {
  44.         $this->httpClient = $httpClient;
  45.         $this->managers = $managers;
  46.         $this->em = $em;
  47.         $this->logger = $logger;
  48.     }
  49.     public function manager(Request $request): ?Manager
  50.     {
  51.         $this->failure = null;
  52.         $session = $request->getSession();
  53.         $cached = $session->get(self::SESSION_KEY);
  54.         if (is_array($cached) && in_array($cached['via'] ?? null, self::SESSION_LOGINS, true)) {
  55.             if ($cached['via'] === 'admin' && !$this->adminStillHere($session, $cached['admin'] ?? null)) {
  56.                 // Співробітник вийшов з адмінки чи втратив роль: кабінет агенції більше не відкриваємо.
  57.                 $session->remove(self::SESSION_KEY);
  58.                 return $this->fail('no-admin');
  59.             }
  60.             $manager = $this->managers->findOneById((int) ($cached['managerId'] ?? 0));
  61.             if ($manager) {
  62.                 return $manager;
  63.             }
  64.             // Менеджера чи агенцію вимкнули: такий вхід більше не діє.
  65.             $session->remove(self::SESSION_KEY);
  66.             $cached = null;
  67.         }
  68.         $token = $request->cookies->get(self::COOKIE);
  69.         // Значення control — `hmac~` + password_hash (`$2y$10$…`, з `/` і `.`). Відкидаємо лише те, що
  70.         // зламає заголовок Cookie: пробіли, керівні символи, `;` і `,`.
  71.         if (!is_string($token) || !preg_match('/^[\x21-\x7E]{1,512}$/', $token) || strpbrk($token, ';,') !== false) {
  72.             $session->remove(self::SESSION_KEY);
  73.             return $this->fail('no-token');
  74.         }
  75.         // Сесія пам'ятає менеджера лише для того самого токена: вихід чи вхід іншим агентом у control
  76.         // змінює cookie, і ми перевіряємо його заново.
  77.         $tokenHash = hash('sha256', $token);
  78.         if (is_array($cached) && ($cached['token'] ?? null) === $tokenHash) {
  79.             return $this->managers->findOneById($cached['managerId']) ?? $this->fail('no-manager');
  80.         }
  81.         $session->remove(self::SESSION_KEY);
  82.         $user = $this->fetchUser($token, (string) $request->headers->get('User-Agent', ''));
  83.         if ($user === null) {
  84.             return null;
  85.         }
  86.         if (!isset($user['id'], $user['services']['agency']['id'])) {
  87.             return $this->fail('no-agency');
  88.         }
  89.         $manager = $this->managers->findOneById((int) $user['id']);
  90.         if (!$manager) {
  91.             // Рядки managers/agencies пишуть тригери userServices; без активного рядка агент не увійде.
  92.             $this->logger->error('Agency cabinet: no active managers row for otpusk user', ['userId' => $user['id']]);
  93.             return $this->fail('no-manager');
  94.         }
  95.         $this->syncNames($manager, $user);
  96.         $session->set(self::SESSION_KEY, ['managerId' => $manager->getId(), 'via' => 'cookie', 'token' => $tokenHash]);
  97.         return $manager;
  98.     }
  99.     /**
  100.      * Сесійний вхід: `password` — форма `/login/auth`, `admin` — «Увійти в кабінет» в адмінці ($admin — username).
  101.      * Новий id сесії: id, відомий до входу, не дає чужого кабінету.
  102.      */
  103.     public function logIn(Request $request, Manager $manager, string $via, ?string $admin = null): void
  104.     {
  105.         if (!in_array($via, self::SESSION_LOGINS, true)) {
  106.             throw new \InvalidArgumentException('Unknown agency cabinet login: '.$via);
  107.         }
  108.         $session = $request->getSession();
  109.         $session->migrate(true);
  110.         $session->set(self::SESSION_KEY, ['managerId' => $manager->getId(), 'via' => $via, 'admin' => $via === 'admin' ? $admin : null]);
  111.     }
  112.     /** Username співробітника, що увійшов у кабінет з адмінки, або null. */
  113.     public function impersonatedBy(Request $request): ?string
  114.     {
  115.         $cached = $request->getSession()->get(self::SESSION_KEY);
  116.         return is_array($cached) && ($cached['via'] ?? null) === 'admin' ? ($cached['admin'] ?? null) : null;
  117.     }
  118.     public function failure(): ?string
  119.     {
  120.         return $this->failure;
  121.     }
  122.     /** Вхід pro з поверненням на сторінку, яку відкривали (історія 15 SPEC-T27). */
  123.     public function loginRedirectUrl(Request $request): string
  124.     {
  125.         $query = $request->getQueryString();
  126.         return self::LOGIN_URL.'?bl='.urlencode($request->getPathInfo().($query !== null ? '?'.$query : ''));
  127.     }
  128.     public function logout(Request $request, Response $response): void
  129.     {
  130.         $request->getSession()->remove(self::SESSION_KEY);
  131.         foreach (self::LOGOUT_COOKIES as $name) {
  132.             $response->headers->clearCookie($name, '/', self::COOKIE_DOMAIN);
  133.             $response->headers->clearCookie($name, '/');
  134.         }
  135.     }
  136.     private function fetchUser(string $token, string $userAgent): ?array
  137.     {
  138.         try {
  139.             $response = $this->httpClient->request('GET', self::ME_URL, [
  140.                 // `_` — як у control: обхід кешу проміжних проксі.
  141.                 'query' => ['_' => random_int(123456789, 987654321)],
  142.                 'headers' => [
  143.                     // content.otpusk.com звіряє підпис cookie з User-Agent браузера.
  144.                     'Cookie' => self::COOKIE.'='.$token,
  145.                     'User-Agent' => $userAgent,
  146.                     'Referer' => 'https://pro.otpusk.com',
  147.                 ],
  148.                 'timeout' => 2,
  149.                 'max_duration' => 3,
  150.             ]);
  151.             $status = $response->getStatusCode();
  152.             if ($status === 401) {
  153.                 return $this->fail('rejected');
  154.             }
  155.             if ($status !== 200) {
  156.                 $this->logger->error('Agency cabinet: content.otpusk.com answered '.$status);
  157.                 return $this->fail('unavailable');
  158.             }
  159.             $body = $response->getContent(false);
  160.         } catch (\Throwable $e) {
  161.             $this->logger->error('Agency cabinet: content.otpusk.com auth check failed', ['error' => $e->getMessage()]);
  162.             return $this->fail('unavailable');
  163.         }
  164.         $user = json_decode(preg_replace('/^\xEF\xBB\xBF/', '', $body), true);
  165.         if (!is_array($user)) {
  166.             $this->logger->error('Agency cabinet: content.otpusk.com answered not JSON');
  167.             return $this->fail('unavailable');
  168.         }
  169.         return empty($user['error']) ? $user : $this->fail('rejected');
  170.     }
  171.     /** Вхід з адмінки діє, поки в сесії той самий співробітник SSO з роллю ROLE_PRO_AGENCY. */
  172.     private function adminStillHere(SessionInterface $session, $admin): bool
  173.     {
  174.         $roles = $session->get('roles');
  175.         return is_string($admin) && $admin !== '' && $session->get('admin') === $admin
  176.             && is_array($roles) && in_array('ROLE_PRO_AGENCY', $roles, true);
  177.     }
  178.     /** @return null завжди: для `return $this->fail(…)` */
  179.     private function fail(string $reason)
  180.     {
  181.         $this->failure = $reason;
  182.         return null;
  183.     }
  184.     /** Як до T-01: ім'я менеджера й назва агенції беруться з профілю otpusk. */
  185.     private function syncNames(Manager $manager, array $user): void
  186.     {
  187.         $changed = false;
  188.         if (isset($user['name']) && is_string($user['name']) && $manager->getName() !== $user['name']) {
  189.             $manager->setName($user['name']);
  190.             $changed = true;
  191.         }
  192.         $agency = $manager->getAgency();
  193.         $agencyName = $user['services']['agency']['name'] ?? null;
  194.         if ($agency && is_string($agencyName) && $agencyName !== '' && $agency->getName() !== $agencyName) {
  195.             $agency->setName($agencyName);
  196.             $changed = true;
  197.         }
  198.         if ($changed) {
  199.             $this->em->flush();
  200.         }
  201.     }
  202. }