| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- <?php
- namespace app\common\library\ps;
- use app\common\model\ps\Factory;
- use think\Request;
- /**
- * 工厂 Open API Key:明文只在生成时返回一次,库中存 SHA256。
- */
- class FactoryApiKey
- {
- /**
- * @param Factory $factory
- * @return string 明文 Key
- */
- public static function generate(Factory $factory)
- {
- $plain = 'psk_' . bin2hex(random_bytes(16));
- $factory->save([
- 'api_key_hash' => hash('sha256', $plain),
- 'api_key_prefix' => substr($plain, 0, 12),
- 'api_key_time' => time(),
- ]);
- return $plain;
- }
- /**
- * @param Request $request
- * @return string
- */
- public static function fromRequest(Request $request)
- {
- $key = trim((string)$request->header('x-api-key', ''));
- if ($key === '') {
- $auth = trim((string)$request->header('authorization', ''));
- if (stripos($auth, 'bearer ') === 0) {
- $key = trim(substr($auth, 7));
- }
- }
- if ($key === '') {
- $key = trim((string)$request->request('api_key', ''));
- }
- return $key;
- }
- /**
- * @param string $plain
- * @return Factory|null
- */
- public static function findFactory($plain)
- {
- $plain = trim((string)$plain);
- if ($plain === '' || strpos($plain, 'psk_') !== 0) {
- return null;
- }
- return Factory::where('api_key_hash', hash('sha256', $plain))
- ->where('status', 'normal')
- ->find();
- }
- }
|