BxAiProxyAuth.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup AIProxy AI Proxy
  7. * @ingroup UnaModules
  8. *
  9. * @{
  10. */
  11. class BxAiProxyAuth
  12. {
  13. /**
  14. * @param callable(string): ?array $fLookup client_id to an OAuth client row. Not called when the key is empty.
  15. * @return array{ok:bool, code:int}
  16. */
  17. public function authenticate(string $sKey, string $sSign, string $sBody, callable $fLookup): array
  18. {
  19. if ($sKey === '')
  20. return $this->denied();
  21. $mixedClient = $fLookup($sKey);
  22. $sSecret = is_array($mixedClient) ? (string)($mixedClient['client_secret'] ?? '') : '';
  23. if ($sSecret === '')
  24. return $this->denied();
  25. $sExpected = hash_hmac('sha256', $sBody, $sSecret);
  26. try {
  27. $bMatch = hash_equals($sExpected, $sSign);
  28. }
  29. catch (Throwable $oException) {
  30. $bMatch = false;
  31. }
  32. if (!$bMatch)
  33. return $this->denied();
  34. return ['ok' => true, 'code' => 200];
  35. }
  36. /**
  37. * @return array{ok:bool, code:int}
  38. */
  39. public function authenticateRequest(string $sKey, string $sSign, string $sBody): array
  40. {
  41. return $this->authenticate($sKey, $sSign, $sBody, function (string $sClientId) {
  42. if (!BxDolModuleQuery::getInstance()->isEnabledByName('bx_oauth'))
  43. return null;
  44. $mixed = BxDolService::call('bx_oauth', 'get_clients_by', [[
  45. 'type' => 'client_id',
  46. 'client_id' => $sClientId,
  47. ]]);
  48. return is_array($mixed) ? $mixed : null;
  49. });
  50. }
  51. /**
  52. * @return array{ok:bool, code:int}
  53. */
  54. protected function denied(): array
  55. {
  56. return ['ok' => false, 'code' => 401];
  57. }
  58. }
  59. /** @} */