forked from laysense/laysite
63 lines
2.5 KiB
PHP
63 lines
2.5 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Content;
|
|
|
|
use App\Config\Environment;
|
|
use PDO;
|
|
use RuntimeException;
|
|
|
|
final class OAuthCredentials
|
|
{
|
|
public static function store(PDO $pdo, int $layout, string $secret): void
|
|
{
|
|
if ($secret === '' || strlen($secret) > 4096 || str_contains($secret, "\0")) {
|
|
throw new DesignFieldError('provider_secret', '客户端密钥为空或格式无效。');
|
|
}
|
|
$revision = bin2hex(random_bytes(16));
|
|
$encrypted = SiteSecrets::encrypt($secret, self::context($layout, $revision));
|
|
$pdo->prepare('INSERT INTO layout_oauth_credentials (layout_id, revision, encrypted_secret) VALUES (?, ?, ?)
|
|
ON CONFLICT (layout_id) DO UPDATE SET revision = excluded.revision, encrypted_secret = excluded.encrypted_secret')
|
|
->execute([$layout, $revision, $encrypted]);
|
|
}
|
|
|
|
public static function read(int $layout, string $revision): string
|
|
{
|
|
$query = Database::connect()->prepare('SELECT encrypted_secret FROM layout_oauth_credentials WHERE layout_id = ? AND revision = ?');
|
|
$query->execute([$layout, $revision]);
|
|
$value = $query->fetchColumn();
|
|
if (!is_string($value)) {
|
|
throw new RuntimeException('客户端密钥尚未配置或已更新。');
|
|
}
|
|
|
|
return SiteSecrets::decrypt($value, self::context($layout, $revision));
|
|
}
|
|
|
|
public static function migrateLegacy(PDO $pdo): void
|
|
{
|
|
$layouts = $pdo->query("SELECT id, payload FROM design_presets WHERE kind = 'header' AND preset = 'member'")->fetchAll();
|
|
$update = $pdo->prepare('UPDATE design_presets SET payload = ?, version = version + 1 WHERE id = ?');
|
|
foreach ($layouts as $layout) {
|
|
$payload = json_decode($layout['payload'], true, flags: JSON_THROW_ON_ERROR);
|
|
$variable = $payload['provider']['secret_env'] ?? null;
|
|
if (!is_string($variable)) {
|
|
continue;
|
|
}
|
|
unset($payload['provider']['secret_env']);
|
|
if (preg_match('/^LAYSITE_OAUTH_[A-Z0-9_]{1,45}$/D', $variable)) {
|
|
$secret = Environment::get($variable);
|
|
if (is_string($secret) && $secret !== '') {
|
|
self::store($pdo, (int) $layout['id'], $secret);
|
|
}
|
|
}
|
|
$update->execute([Database::json($payload), $layout['id']]);
|
|
}
|
|
}
|
|
|
|
private static function context(int $layout, string $revision): string
|
|
{
|
|
return 'laysite-oauth:' . $layout . ':' . $revision;
|
|
}
|
|
}
|