Files
MrleeAdmin/backend/app/service/admin/plugin/ApplicationAuthService.php
T
2026-08-31 11:33:59 +08:00

79 lines
2.3 KiB
PHP

<?php
declare(strict_types=1);
namespace app\service\admin\plugin;
use app\dao\plugin\ApplicationAuthDao;
use app\model\plugin\ApplicationAuth;
use core\base\BaseService;
use core\exception\handler\AdminException;
class ApplicationAuthService extends BaseService
{
public function __construct(ApplicationAuthDao $dao)
{
$this->dao = $dao;
}
public function save(array $data): ?ApplicationAuth
{
try {
return $this->transaction(function () use ($data) {
$data['access_key'] = $data['access_key'] ?? $this->generateAccessKey();
$data['secret_key'] = $data['secret_key'] ?? $this->generateSecretKey();
return $this->dao->save($data);
});
} catch (\Throwable $e) {
throw new AdminException($e->getMessage());
}
}
public function update(string|int $id, array $data): void
{
try {
$this->transaction(function () use ($id, $data) {
unset($data['access_key'], $data['secret_key']);
$model = $this->dao->get($id);
if (!$model) {
throw new AdminException('应用授权不存在');
}
$model->fill($data);
$model->save();
});
} catch (\Throwable $e) {
throw new AdminException($e->getMessage());
}
}
public function resetSecret(string|int $id): array
{
try {
return $this->transaction(function () use ($id) {
$model = $this->dao->get($id);
if (!$model) {
throw new AdminException('应用授权不存在');
}
$model->secret_key = $this->generateSecretKey();
$model->save();
return [
'id' => (string)$model->id,
'secret_key' => $model->secret_key,
];
});
} catch (\Throwable $e) {
throw new AdminException($e->getMessage());
}
}
private function generateAccessKey(): string
{
return 'AK' . strtoupper(bin2hex(random_bytes(16)));
}
private function generateSecretKey(): string
{
return 'SK' . bin2hex(random_bytes(32));
}
}