update backend p20.1 p20.2

This commit is contained in:
2026-04-16 13:16:43 +08:00
parent a870793704
commit ff9951bb43
11 changed files with 440 additions and 21 deletions
+12 -4
View File
@@ -62,13 +62,14 @@ class ApiKey extends Model
*/
public static function generate(int $user_id, string $name, ?string $expires_at = null): array
{
$plain_key = bin2hex(random_bytes(32));
$token = bin2hex(random_bytes(32));
$plain_key = $user_id . '#' . $token;
$model = static::query()->create([
'user_id' => $user_id,
'name' => $name,
'key_hash' => hash('sha256', $plain_key),
'key_prefix' => substr($plain_key, 0, 8),
'key_hash' => hash('sha256', $token),
'key_prefix' => substr($token, 0, 8),
'expires_at' => $expires_at,
'enabled' => true,
'created_at' => \Carbon\Carbon::now(),
@@ -82,9 +83,16 @@ class ApiKey extends Model
*/
public static function findByPlainKey(string $plain_key): ?static
{
$hash = hash('sha256', $plain_key);
// 仅支持新格式: {user_id}#{token}
if (!str_contains($plain_key, '#')) {
return null;
}
[$user_id, $token] = explode('#', $plain_key, 2);
$hash = hash('sha256', $token);
return static::query()
->where('user_id', (int) $user_id)
->where('key_hash', $hash)
->where(function ($query): void {
$query->whereNull('expires_at')