FactoryApiKey.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace app\common\library\ps;
  3. use app\common\model\ps\Factory;
  4. use think\Request;
  5. /**
  6. * 工厂 Open API Key:明文只在生成时返回一次,库中存 SHA256。
  7. */
  8. class FactoryApiKey
  9. {
  10. /**
  11. * @param Factory $factory
  12. * @return string 明文 Key
  13. */
  14. public static function generate(Factory $factory)
  15. {
  16. $plain = 'psk_' . bin2hex(random_bytes(16));
  17. $factory->save([
  18. 'api_key_hash' => hash('sha256', $plain),
  19. 'api_key_prefix' => substr($plain, 0, 12),
  20. 'api_key_time' => time(),
  21. ]);
  22. return $plain;
  23. }
  24. /**
  25. * @param Request $request
  26. * @return string
  27. */
  28. public static function fromRequest(Request $request)
  29. {
  30. $key = trim((string)$request->header('x-api-key', ''));
  31. if ($key === '') {
  32. $auth = trim((string)$request->header('authorization', ''));
  33. if (stripos($auth, 'bearer ') === 0) {
  34. $key = trim(substr($auth, 7));
  35. }
  36. }
  37. if ($key === '') {
  38. $key = trim((string)$request->request('api_key', ''));
  39. }
  40. return $key;
  41. }
  42. /**
  43. * @param string $plain
  44. * @return Factory|null
  45. */
  46. public static function findFactory($plain)
  47. {
  48. $plain = trim((string)$plain);
  49. if ($plain === '' || strpos($plain, 'psk_') !== 0) {
  50. return null;
  51. }
  52. return Factory::where('api_key_hash', hash('sha256', $plain))
  53. ->where('status', 'normal')
  54. ->find();
  55. }
  56. }