diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 77de753..1f0c68c 100644 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -19,21 +19,26 @@ $routes->group('admin', ['namespace' => 'App\Controllers\Admin'], function ($rou $routes->get('/', 'UserController::index'); }); $routes->group('cloudflare', ['namespace' => 'App\Controllers\Admin\Cloudflare'], function ($routes) { + $routes->cli('/reload', 'CloudflareController::reload'); + $routes->group('auth', function ($routes) { + $routes->get('/', 'AuthController::index'); + $routes->get('create', 'AuthController::create_form'); + $routes->post('create', 'AuthController::create'); + $routes->get('modify/(:num)', 'AuthController::modify_form/$1'); + $routes->post('modify/(:num)', 'AuthController::modify/$1'); + $routes->post('create', 'AuthController::create'); + }); $routes->group('account', function ($routes) { $routes->get('/', 'AccountController::index'); - $routes->get('create', 'AccountController::create_form'); - $routes->post('create', 'AccountController::create'); + $routes->post('create/(:uuid)', 'AccountController::create'); }); $routes->group('zone', function ($routes) { $routes->get('/', 'ZoneController::index'); - $routes->get('create', 'ZoneController::create_form'); $routes->post('create/(:uuid)', 'ZoneController::create/$1'); }); $routes->group('record', function ($routes) { $routes->get('/', 'RecordController::index'); - $routes->get('create', 'RecordController::create_form'); $routes->post('create/(:uuid)', 'RecordController::create/$1'); }); }); }); - diff --git a/app/Controllers/Admin/Cloudflare/AccountController.php b/app/Controllers/Admin/Cloudflare/AccountController.php index cfcbd1d..003f3b8 100644 --- a/app/Controllers/Admin/Cloudflare/AccountController.php +++ b/app/Controllers/Admin/Cloudflare/AccountController.php @@ -2,19 +2,19 @@ namespace App\Controllers\Admin\Cloudflare; -use App\Libraries\MySocket\Cloudflare\AccountSocket; -use App\Models\Cloudflare\AccountModel; -use CodeIgniter\HTTP\RedirectResponse; -use CodeIgniter\HTTP\RequestInterface; -use CodeIgniter\HTTP\ResponseInterface; use Psr\Log\LoggerInterface; +use CodeIgniter\HTTP\ResponseInterface; +use CodeIgniter\HTTP\RequestInterface; +use CodeIgniter\HTTP\RedirectResponse; +use App\Models\Cloudflare\AccountModel; +use App\Libraries\MySocket\Cloudflare\ZoneSocket; +use App\Libraries\MySocket\Cloudflare\AccountSocket; class AccountController extends CloudflareController { private $_mySocket = null; private $_model = null; - private $_email = ""; - private $_auth_key = ""; + private $_auth_key = null; public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { parent::initController($request, $response, $logger); @@ -33,44 +33,10 @@ class AccountController extends CloudflareController final protected function getMySocket(): AccountSocket { if ($this->_mySocket === null) { - $this->_mySocket = new AccountSocket($this->_email, $this->_auth_key); + $this->_mySocket = new AccountSocket($this->_auth_key); } return $this->_mySocket; } - //생성 - public function create_form(): RedirectResponse|string - { - $this->fields = ['id', 'authkey']; - $this->field_rules = $this->getModel()->getFieldRules(__FUNCTION__, $this->fields); - $this->filter_fields = []; - $this->field_options = $this->getFormFieldOptions($this->filter_fields); - return $this->create_form_procedure(); - } - protected function create_process(): void - { - parent::create_process(); - $results = $this->getMySocket()->create(); - $this->entitys = []; - foreach ($results as $result) { - $this->formDatas = $this->getMySocket()->getArrayByResult($result); - $entity = $this->getModel()->create($this->formDatas); - log_message("notice", "Account:" . __FUNCTION__ . "=> {$entity->getTitle()} 작업을 완료하였습니다."); - $this->entitys[] = $entity; - } - } - public function create(): RedirectResponse - { - $this->fields = ['id', 'authkey']; - $this->field_rules = $this->getModel()->getFieldRules(__FUNCTION__, $this->fields); - // $this->filter_fields = []; - // $this->field_options = $this->getFormFieldOptions($this->filter_fields); - $this->create_validate(); - $this->formDatas = $this->getFormDatas(); - //Socket 인증용 - $this->_email = $this->formDatas['id']; - $this->auth_key = $this->formDatas['authkey']; - return $this->create_procedure(); - } // 리스트 public function index(): string { @@ -81,4 +47,22 @@ class AccountController extends CloudflareController $this->field_options = $this->getFormFieldOptions($this->filter_fields); return $this->list_procedure(); } + public function reload(): RedirectResponse + { + try { + //Transaction Start + $this->getModel()->transStart(); + foreach ($this->getModel()->getEntitys as $entity) { + $zone_socket = new ZoneSocket($entity); + $zone_socket->reload(); + } + return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/"); + } catch (\Exception $e) { + //Transaction Rollback + $this->getModel()->transRollback(); + log_message("error", $e->getMessage()); + $this->session->setFlashdata(SESSION_NAMES['RETURN_MSG'], __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage()); + return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/"); + } + } } diff --git a/app/Controllers/Admin/Cloudflare/AuthController.php b/app/Controllers/Admin/Cloudflare/AuthController.php new file mode 100644 index 0000000..c014b38 --- /dev/null +++ b/app/Controllers/Admin/Cloudflare/AuthController.php @@ -0,0 +1,106 @@ +class_name = "Auth"; + $this->class_path .= $this->class_name; + $this->title = lang("{$this->class_path}.title"); + helper($this->class_path); + } + final protected function getModel(): AuthModel + { + if ($this->_model === null) { + $this->_model = new AuthModel(); + } + return $this->_model; + } + private function init(string $action): void + { + $this->fields = [$this->getModel()::TITLE, 'authkey', 'status']; + $this->field_rules = $this->getModel()->getFieldRules($action, $this->fields); + $this->filter_fields = ['status']; + $this->field_options = $this->getFormFieldOptions($this->filter_fields); + } + //생성 + public function create_form(): RedirectResponse|string + { + $this->init('create'); + return $this->create_form_procedure(); + } + protected function create_process(): void + { + parent::create_process(); + $entity = $this->getModel()->create($this->formDatas); + } + public function create(): RedirectResponse + { + $this->init(__FUNCTION__); + $this->create_validate($this->_fields); + $this->formDatas = $this->getFormDatas(); + return $this->create_procedure(); + } + //수정 + public function modify_form(): RedirectResponse|string + { + $this->init('modify'); + return $this->create_form_procedure(); + } + protected function modify_process(): void + { + parent::modify_process(); + $this->entity = $this->getModel()->modify($this->entity, $this->formDatas); + } + public function modify(string $uid): RedirectResponse + { + $this->entity = $this->getModel()->getEntityByPK($uid); + if ($this->entity === null) { + throw new \Exception("해당 정보를 찾을수 없습니다."); + } + $this->init(__FUNCTION__);; + $this->modify_validate($this->_fields); + $this->formDatas = $this->getFormDatas(); + return $this->create_procedure(); + } + // 리스트 + public function index(): string + { + $this->fields = [$this->getModel()::TITLE, 'oldkey', 'status', 'updated_at', 'created_at']; + $this->field_rules = $this->getModel()->getFieldRules(__FUNCTION__, $this->fields); + $this->filter_fields = ['status']; + $this->batchjob_fields = ['status']; + $this->field_options = $this->getFormFieldOptions($this->filter_fields); + return $this->list_procedure(); + } + + public function reload(): RedirectResponse + { + try { + //Transaction Start + $this->getModel()->transStart(); + foreach ($this->getModel()->getEntitys as $entity) { + $account_socket = new AccountSocket($entity); + $account_socket->reload(); + } + return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/"); + } catch (\Exception $e) { + //Transaction Rollback + $this->getModel()->transRollback(); + log_message("error", $e->getMessage()); + $this->session->setFlashdata(SESSION_NAMES['RETURN_MSG'], __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage()); + return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/"); + } + } +} diff --git a/app/Controllers/Admin/Cloudflare/CloudflareController.php b/app/Controllers/Admin/Cloudflare/CloudflareController.php index 23382ee..843b2eb 100644 --- a/app/Controllers/Admin/Cloudflare/CloudflareController.php +++ b/app/Controllers/Admin/Cloudflare/CloudflareController.php @@ -2,17 +2,19 @@ namespace App\Controllers\Admin\Cloudflare; -use App\Controllers\Admin\AdminController; -use App\Models\Cloudflare\AccountModel; -use App\Models\Cloudflare\RecordModel; -use App\Models\Cloudflare\ZoneModel; -use CodeIgniter\HTTP\RedirectResponse; -use CodeIgniter\HTTP\RequestInterface; -use CodeIgniter\HTTP\ResponseInterface; use Psr\Log\LoggerInterface; +use CodeIgniter\HTTP\ResponseInterface; +use CodeIgniter\HTTP\RequestInterface; +use App\Models\Cloudflare\ZoneModel; +use App\Models\Cloudflare\RecordModel; +use App\Models\Cloudflare\AuthModel; +use App\Models\Cloudflare\AccountModel; +use App\Entities\Cloudflare\AccountEntity; +use App\Controllers\Admin\AdminController; abstract class CloudflareController extends AdminController { + private $_authModel = null; private $_accountModel = null; private $_zoneModel = null; private $_recordModel = null; @@ -21,7 +23,13 @@ abstract class CloudflareController extends AdminController parent::initController($request, $response, $logger); $this->class_path .= "Cloudflare/"; } - abstract protected function getMySocket(): mixed; + final protected function getAuthModel(): AuthModel + { + if ($this->_authModel === null) { + $this->_authModel = new AuthModel(); + } + return $this->_authModel; + } final protected function getAccountModel(): AccountModel { if ($this->_accountModel === null) { @@ -43,19 +51,4 @@ abstract class CloudflareController extends AdminController } return $this->_recordModel; } - final protected function reload_procedure(): RedirectResponse - { - try { - //Transaction Start - $this->getModel()->transStart(); - $$this->getMySocket()->reload($this->getModel()); - return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/"); - } catch (\Exception $e) { - //Transaction Rollback - $this->getModel()->transRollback(); - log_message("error", $e->getMessage()); - $this->session->setFlashdata(SESSION_NAMES['RETURN_MSG'], __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage()); - return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/"); - } - } } diff --git a/app/Controllers/Admin/Cloudflare/RecordController.php b/app/Controllers/Admin/Cloudflare/RecordController.php index a157088..ad50fef 100644 --- a/app/Controllers/Admin/Cloudflare/RecordController.php +++ b/app/Controllers/Admin/Cloudflare/RecordController.php @@ -11,8 +11,6 @@ use Psr\Log\LoggerInterface; class RecordController extends CloudflareController { - private $_myLibrary = null; - private $_account_entity = null; private $_zone_entity = null; public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { @@ -32,7 +30,7 @@ class RecordController extends CloudflareController final protected function getMySocket(): RecordSocket { if ($this->_mySocket === null) { - $this->_mySocket = new RecordSocket($this->_account_entity, $this->_zone_entity); + $this->_mySocket = new RecordSocket($this->_zone_entity); } return $this->_mySocket; } @@ -70,46 +68,34 @@ class RecordController extends CloudflareController } return $formDatas; } - //생성 - public function create_form(): RedirectResponse|string + private function init(string $action): void { $this->fields = [$this->getModel()::PARENT, 'type', 'content', 'proxied', 'hosts']; - $this->field_rules = $this->getModel()->getFieldRules(__FUNCTION__, $this->fields); + $this->field_rules = $this->getModel()->getFieldRules($action, $this->fields); $this->filter_fields = [$this->getModel()::PARENT, 'type', 'proxied']; $this->field_options = $this->getFormFieldOptions($this->filter_fields); - return $this->create_form_procedure(); } - protected function create_validate(): void + //생성 + protected function create_validate(array $fields): void { //hosts를 제외한 fields Valid처리 - $this->validateFormDatas(array_diff($this->fields, ['hosts'])); + parent::create_validate(array_diff($fields, ['hosts'])); } protected function create_process(): void { $this->_zone_entity = $this->getZoneModel()->getEntityByPK($this->formDatas[$this->getModel()::PARENT]); - $this->_account_entity = $this->getAccountModel()->getEntityByPK($this->_zone_entity->getParent()); - if ($this->_account_entity === null) { - throw new \Exception("해당 계정정보를 찾을수 없습니다."); - } //Record생성 foreach ($this->formDatas['hosts'] as $host) { - $result = $this->getMySocket()->create($host, [ - 'type' => $this->formDatas['type'], - 'content' => $this->formDatas['content'], - 'proxied' => $this->formDatas['proxied'], - ]); + $result = $this->getMySocket()->create($host, $this->formDatas['type'], $this->formDatas['content'], $this->formDatas['proxied']); $formDatas = $this->getMySocket()->getArrayByResult($result); - $entity = $this->getRecordModel()->create($formDatas); - log_message("notice", "Record:" . __FUNCTION__ . "=> 작업을 완료하였습니다."); + $entity = $this->getRecordModel()->create($formDatas); + log_message("debug", "Record:{$entity->getTitle()} 작업을 완료하였습니다."); } } public function create(): RedirectResponse { - $this->fields = [$this->getModel()::PARENT, 'type', 'content', 'proxied', 'hosts']; - $this->field_rules = $this->getModel()->getFieldRules(__FUNCTION__, $this->fields); - // $this->filter_fields = [$this->getModel()::PARENT, 'type', 'proxied']; - // $this->field_options = $this->getFormFieldOptions($this->filter_fields); - $this->create_validate(); + $this->init(__FUNCTION__); + $this->create_validate($this->fields); $this->formDatas = $this->getFormDatas(); //부모데이터 정의 $this->_account_entity = $this->getAccountModel()->getEntityByPK($this->formDatas[$this->getModel()::PARENT]); @@ -126,12 +112,4 @@ class RecordController extends CloudflareController $this->field_options = $this->getFormFieldOptions($this->filter_fields); return $this->list_procedure(); } - //reload - public function reload(string $zone_uid): RedirectResponse - { - //부모데이터 정의 - $this->_zone_entity = $this->getZoneModel()->getEntityByPK($zone_uid); - $this->_account_entity = $this->getAccountModel()->getEntityByPK($this->_zone_entity->getParent()); - return $this->reload_procedure(); - } } diff --git a/app/Controllers/Admin/Cloudflare/ZoneController.php b/app/Controllers/Admin/Cloudflare/ZoneController.php index 8e4f503..1ea553f 100644 --- a/app/Controllers/Admin/Cloudflare/ZoneController.php +++ b/app/Controllers/Admin/Cloudflare/ZoneController.php @@ -33,6 +33,7 @@ class ZoneController extends CloudflareController final protected function getMySocket(): ZoneSocket { if ($this->_mySocket === null) { + $this->_mySocket = new ZoneSocket($this->_account_entity); } return $this->_mySocket; @@ -76,11 +77,18 @@ class ZoneController extends CloudflareController } return $formDatas; } + private function init(string $action): void + { + $this->fields = [$this->getModel()::PARENT, 'domains', 'hosts', 'type', 'content', 'proxied']; + $this->field_rules = $this->getModel()->getFieldRules($action, $this->fields); + $this->filter_fields = [$this->getModel()::PARENT, 'development_mode', 'ipv6', 'security_level', 'status']; + $this->field_options = $this->getFormFieldOptions($this->filter_fields); + } //생성 - protected function create_validate(): void + protected function create_validate(array $fields): void { //domains,hosts를 제외한 fields Valid처리 - $this->validateFormDatas(array_diff($this->fields, ['domains', 'hosts'])); + parent::create_validate(array_diff($fields, ['domains', 'hosts'])); } protected function create_process(): void { @@ -88,66 +96,28 @@ class ZoneController extends CloudflareController //Zone생성 $zone_entitys = []; foreach ($this->formDatas['domains'] as $domain) { - //Storage용 - $result = $this->getMySocket()->create($domain); - $formDatas = $this->getMySocket()->getArrayByResult($result); - $entity = $this->getModel()->create($formDatas); - //아래는 추가 셋팅 ipv6 TurnOFF , //Development mode TurnOFF - $entity = $this->getMySocket()->setCFSetting($entity, 'ipv6', 'off'); - $entity = $this->getMySocket()->setCFSetting($entity, 'development_mode', 'off'); - $entity = $this->getMySocket()->setCFSetting($entity, 'security_level', 'medium'); - log_message("notice", "Zone:" . __FUNCTION__ . "=> 작업을 완료하였습니다."); + $entity = $this->getMySocket()->create($domain); + log_message("debug", "Zone:{$entity->getTitle()} 작업을 완료하였습니다."); $zone_entitys[] = $entity; } //Record생성 foreach ($zone_entitys as $zone_entity) { - $record = new RecordSocket($this->_account_entity, $zone_entity); + $record_socket = new RecordSocket($entity); foreach ($this->formDatas['hosts'] as $host) { - $result = $record->create($host, [ - 'type' => $this->formDatas['type'], - 'content' => $this->formDatas['content'], - 'proxied' => $this->formDatas['proxied'], - ]); - $formDatas = $record->getArrayByResult($result); - $entity = $this->getRecordModel()->create($formDatas); - log_message("notice", "Record:" . __FUNCTION__ . "=> 작업을 완료하였습니다."); + $entity = $record_socket->create($host, $this->formDatas['type'], $this->formDatas['content'], $this->formDatas['proxied']); + log_message("debug", "Record:{$entity->getTitle()} 작업을 완료하였습니다."); } } } public function create(): RedirectResponse { - $this->fields = [$this->getModel()::PARENT, 'domains', 'hosts', 'type', 'content', 'proxied']; - $this->field_rules = $this->getModel()->getFieldRules(__FUNCTION__, $this->fields); - // $this->filter_fields = [$this->getModel()::PARENT, 'type', 'proxied']; - // $this->field_options = $this->getFormFieldOptions($this->filter_fields); - $this->create_validate(); + $this->init(__FUNCTION__); + $this->create_validate($this->_fields); $this->formDatas = $this->getFormDatas(); //부모데이터 정의 $this->_account_entity = $this->getAccountModel()->getEntityByPK($this->formDatas[$this->getModel()::PARENT]); return $this->create_procedure(); } - // //수정 - // protected function modify_process(): void - // { - // $this->entity = $this->getMySocket()->modify($this->entity, $this->formDatas); - // } - // public function modify(string $uid): RedirectResponse - // { - // $this->entity = $this->getModel()->getEntityByPK($uid); - // if ($this->entity === null) { - // throw new \Exception("해당 정보를 찾을수 없습니다."); - // } - // //부모데이터 정의 - // $this->_account_entity = $this->getAccountModel()->getEntityByPK($this->entity->getParent()); - - // $this->fields = [$this->getModel()::PARENT, 'domains', 'hosts', 'type', 'content', 'proxied']; - // $this->field_rules = $this->getModel()->getFieldRules(__FUNCTION__, $this->fields); - // // $this->filter_fields = [$this->getModel()::PARENT, 'type', 'proxied']; - // // $this->field_options = $this->getFormFieldOptions($this->filter_fields); - // $this->modify_validate(); - // $this->formDatas = $this->getFormDatas(); - // return $this->create_procedure(); - // } // 리스트 public function index(): string { @@ -159,10 +129,22 @@ class ZoneController extends CloudflareController return $this->list_procedure(); } //reload - public function reload(string $account_uid): RedirectResponse + public function reload(): RedirectResponse { - //부모데이터 정의 - $this->_account_entity = $this->getAccountModel()->getEntityByPK($account_uid); - return $this->reload_procedure(); + try { + //Transaction Start + $this->getModel()->transStart(); + foreach ($this->getModel()->getEntitys as $entity) { + $record_socket = new RecordSocket($entity); + $record_socket->reload(); + } + return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/"); + } catch (\Exception $e) { + //Transaction Rollback + $this->getModel()->transRollback(); + log_message("error", $e->getMessage()); + $this->session->setFlashdata(SESSION_NAMES['RETURN_MSG'], __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage()); + return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/"); + } } } diff --git a/app/Controllers/MVController.php b/app/Controllers/MVController.php index 2d46f3d..7f8961f 100644 --- a/app/Controllers/MVController.php +++ b/app/Controllers/MVController.php @@ -56,23 +56,19 @@ abstract class MVController extends CommonController } return $formDatas; } - final protected function validateFormDatas(array $fields): void + // 생성 + protected function create_validate(array $fields): void { //변경할 값 확인 : Upload된 파일 검증시 $this->request->getVar()보다 먼처 체크필요 $this->validation = service('validation'); $this->validation->setRules($this->getModel()->getFieldRules($fields)); if (!$this->validation->withRequest($this->request)->run()) { - throw new \Exception("{$this->class_name}의 {$this->action} 작업 데이터 검증 오류발생\n" . implode( + throw new \Exception("{$this->class_name} 작업 데이터 검증 오류발생\n" . implode( "\n", $this->validation->getErrors() )); } } - // 생성 - protected function create_validate(): void - { - $this->validateFormDatas($this->fields); - } protected function create_form_process(): void {} final protected function create_form_procedure(): RedirectResponse|string { @@ -97,6 +93,7 @@ abstract class MVController extends CommonController //Transaction Start $this->getModel()->transStart(); $this->create_process(); + log_message("notice", __FUNCTION__ . "=> 작업을 완료하였습니다."); return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/"); } catch (\Exception $e) { //Transaction Rollback @@ -108,9 +105,17 @@ abstract class MVController extends CommonController } } // 수정 - protected function modify_validate(): void + protected function modify_validate(array $fields): void { - $this->validateFormDatas($this->fields); + //변경할 값 확인 : Upload된 파일 검증시 $this->request->getVar()보다 먼처 체크필요 + $this->validation = service('validation'); + $this->validation->setRules($this->getModel()->getFieldRules($fields)); + if (!$this->validation->withRequest($this->request)->run()) { + throw new \Exception("{$this->class_name} 작업 데이터 검증 오류발생\n" . implode( + "\n", + $this->validation->getErrors() + )); + } } protected function modify_form_process(): void {} final protected function modify_form_procedure(): RedirectResponse|string @@ -136,6 +141,7 @@ abstract class MVController extends CommonController //Transaction Start $this->getModel()->transStart(); $this->modify_process(); + log_message("notice", __FUNCTION__ . "=> 작업을 완료하였습니다."); return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/"); } catch (\Exception $e) { //Transaction Rollback diff --git a/app/Entities/Cloudflare/AccountEntity.php b/app/Entities/Cloudflare/AccountEntity.php index b587ce8..a914ec8 100644 --- a/app/Entities/Cloudflare/AccountEntity.php +++ b/app/Entities/Cloudflare/AccountEntity.php @@ -9,7 +9,7 @@ class AccountEntity extends CommonEntity { public function __toString() { - return "{$this->getPK()}|{$this->getTitle()}|{$this->getAuthKey()}|{$this->attributes['type']}|{$this->attributes['status']}"; + return "{$this->getPK()}|{$this->getTitle()}|{$this->attributes['type']}|{$this->attributes['status']}"; } public function getPK(): string { @@ -24,12 +24,8 @@ class AccountEntity extends CommonEntity $this->attributes[AccountModel::TITLE] = $title; } //Common Function - public function getID(): string + public function getParent(): string { - return $this->attributes['id']; - } - public function getAuthKey(): string - { - return $this->attributes['authkey']; + return $this->attributes[AccountModel::PARENT]; } } diff --git a/app/Entities/Cloudflare/AuthEntity.php b/app/Entities/Cloudflare/AuthEntity.php new file mode 100644 index 0000000..9246347 --- /dev/null +++ b/app/Entities/Cloudflare/AuthEntity.php @@ -0,0 +1,35 @@ +getPK()}|{$this->getTitle()}|{$this->getAuthKey()}|{$this->attributes['status']}"; + } + public function getPK(): string + { + return $this->attributes[AuthModel::PK]; + } + public function getTitle(): string + { + return $this->attributes[AuthModel::TITLE]; + } + public function setTitle(string $title): void + { + $this->attributes[AuthModel::TITLE] = $title; + } + //Common Function + public function getID(): string + { + return $this->attributes['id']; + } + public function getAuthKey(): string + { + return $this->attributes['authkey']; + } +} diff --git a/app/Helpers/Admin/Cloudflare/Account_helper.php b/app/Helpers/Admin/Cloudflare/Account_helper.php index 429d73e..c93f28f 100644 --- a/app/Helpers/Admin/Cloudflare/Account_helper.php +++ b/app/Helpers/Admin/Cloudflare/Account_helper.php @@ -1,4 +1,7 @@ "select-field"]); // // return form_multiselect($field, $field_options[$field], is_array($value) ? [...$value] : [$value], [...$attributes]); // foreach ($viewDatas['field_options'][$field] as $key => $label) { @@ -28,21 +31,10 @@ function getFieldForm_AccountHelper(string $field, mixed $value, array $viewData // } // return implode(" ", $checkboxs); break; - case 'content': - case 'head': - case 'tail': - $form = form_textarea($field, html_entity_decode($value), ['class' => 'editor', 'rows' => '20', 'cols' => '100']); - break; case "type": case "status": $form = form_dropdown($field, $viewDatas['field_options'][$field], $value, $attributes); break; - case 'id': - $form = form_input($field, $value, ["placeholder" => "예)sample@test.com", "style" => "width:60%; ::placeholder{color:silver; opacity: 1;}"]); - break; - case 'name': - $form = form_input($field, $value, ["placeholder" => "예)", "style" => "width:60%; ::placeholder{color:silver; opacity: 1;}"]); - break; case 'updated_at': case 'created_at': $form = form_input($field, $value, ['class' => 'calender']); @@ -72,13 +64,6 @@ function getFieldView_AccountHelper(string $field, mixed $entity, array $viewDat case 'sale': $value = number_format(!$value ? 0 : $value) . "원"; break; - case 'stock': - case 'view_cnt': - $value = number_format(!$value ? 0 : $value); - break; - case 'content': - $value = html_entity_decode($value); - break; case 'updated_at': case 'created_at': $value = $value ? date("Y-m-d", strtotime($value)) : ""; @@ -112,8 +97,7 @@ function getListHeaders_AccountHelper(string $field, array $viewDatas, array $at function getListColumns_AccountHelper(string $field, mixed $entity, array $viewDatas, array $attributes = []): string { switch ($field) { - case 'title': - case 'name': + case AccountModel::TITLE: $value = anchor( current_url() . '/view/' . $entity->getPK(), getFieldView_AccountHelper($field, $entity, $viewDatas), diff --git a/app/Helpers/Admin/Cloudflare/Auth_helper.php b/app/Helpers/Admin/Cloudflare/Auth_helper.php new file mode 100644 index 0000000..768e2cf --- /dev/null +++ b/app/Helpers/Admin/Cloudflare/Auth_helper.php @@ -0,0 +1,123 @@ +%s", + implode(" ", $attributes), + lang("{$viewDatas['class_path']}.label.{$field}") + ); + break; + } + return $label; +} +//header.php에서 getFieldForm_Helper사용 +function getFieldForm_AuthHelper(string $field, mixed $value, array $viewDatas, array $attributes = []): string +{ + $value = $value ?: DEFAULTS['EMPTY']; + switch ($field) { + case AuthModel::TITLE: + $form = form_input($field, $value, ["placeholder" => "예)sample@test.com", "style" => "width:60%; ::placeholder{color:silver; opacity: 1;}"]); + break; + case 'head': + case 'tail': + $form = form_textarea($field, html_entity_decode($value), ['class' => 'editor', 'rows' => '20', 'cols' => '100']); + break; + case "status": + $form = form_dropdown($field, $viewDatas['field_options'][$field], $value, $attributes); + break; + case 'updated_at': + case 'created_at': + $form = form_input($field, $value, ['class' => 'calender']); + break; + default: + $form = form_input($field, $value, ["style" => "width:60%;"]); + break; + } + return $form; +} // + +function getFieldView_AuthHelper(string $field, mixed $entity, array $viewDatas, array $attributes = []) +{ + $value = $entity->$field ?: DEFAULTS['EMPTY']; + switch ($field) { + case 'category_uid': + foreach (array_values($viewDatas['field_options'][$field]) as $category_2depths) { + foreach ($category_2depths as $key => $depth) { + if ($key == $depth) { + $value = $depth; + } + } + } + break; + case 'cost': + case 'price': + case 'sale': + $value = number_format(!$value ? 0 : $value) . "원"; + break; + case 'content': + $value = html_entity_decode($value); + break; + case 'updated_at': + case 'created_at': + $value = $value ? date("Y-m-d", strtotime($value)) : ""; + break; + default: + if (in_array($field, $viewDatas['filter_fields']) && $value) { + $value = $viewDatas['field_options'][$field][$value]; + } + break; + } + return $value; +} // + +function getListHeaders_AuthHelper(string $field, array $viewDatas, array $attributes = []): string +{ + $label = getFieldLabel_AuthHelper($field, $viewDatas, $attributes); + if ($field == $viewDatas['order_field']) { + $label .= $viewDatas['order_value'] == 'ASC' ? ICONS["UP"] : ICONS["DOWN"]; + } + $order_value = $viewDatas['order_value'] == 'DESC' ? "ASC" : "DESC"; + $viewDatas['uri']->addQuery('order_field', $field); + $viewDatas['uri']->addQuery('order_value', $order_value); + $header = anchor((string)$viewDatas['uri'], $label); + switch ($field) { + case 'title': + $attributes = [...$attributes, "class=\"col-2\""]; + break; + } + return sprintf("%s", implode(" ", $attributes), $header); +} +function getListColumns_AuthHelper(string $field, mixed $entity, array $viewDatas, array $attributes = []): string +{ + switch ($field) { + case AuthModel::TITLE: + $value = anchor( + current_url() . '/view/' . $entity->getPK(), + getFieldView_AuthHelper($field, $entity, $viewDatas), + ["target" => "_self"] + ); + break; + default: + if (in_array($field, $viewDatas['filter_fields'])) { + $attributes["onChange"] = sprintf( + 'location.href="%s/toggle/%s/%s?%s="+this.options[this.selectedIndex].value', + current_url(), + $entity->getPK(), + $field, + $field + ); + $value = getFieldForm_AuthHelper($field, $entity, $viewDatas, $attributes); + } + $value = getFieldView_AuthHelper($field, $entity, $viewDatas); + break; + } + return $value; +} diff --git a/app/Helpers/Admin/Cloudflare/Record_helper.php b/app/Helpers/Admin/Cloudflare/Record_helper.php index a6135e2..804f082 100644 --- a/app/Helpers/Admin/Cloudflare/Record_helper.php +++ b/app/Helpers/Admin/Cloudflare/Record_helper.php @@ -1,4 +1,7 @@ "select-field"]); // // return form_multiselect($field, $field_options[$field], is_array($value) ? [...$value] : [$value], [...$attributes]); // foreach ($viewDatas['field_options'][$field] as $key => $label) { @@ -28,7 +31,7 @@ function getFieldForm_RecordHelper(string $field, mixed $value, array $viewDatas // } // return implode(" ", $checkboxs); break; - case 'content': + case RecordModel::TITLE: $form = form_input($field, $value, ["placeholder" => "예)123.123.123.123", "style" => "width:60%; ::placeholder{color:silver; opacity: 1;}"]); break; case 'hosts': @@ -69,13 +72,6 @@ function getFieldView_RecordHelper(string $field, mixed $entity, array $viewData case 'sale': $value = number_format(!$value ? 0 : $value) . "원"; break; - case 'stock': - case 'view_cnt': - $value = number_format(!$value ? 0 : $value); - break; - case 'content': - $value = html_entity_decode($value); - break; case 'updated_at': case 'created_at': $value = $value ? date("Y-m-d", strtotime($value)) : ""; @@ -109,8 +105,7 @@ function getListHeaders_RecordHelper(string $field, array $viewDatas, array $att function getListColumns_RecordHelper(string $field, mixed $entity, array $viewDatas, array $attributes = []): string { switch ($field) { - case 'title': - case 'name': + case RecordModel::TITLE: $value = anchor( current_url() . '/view/' . $entity->getPK(), getFieldView_RecordHelper($field, $entity, $viewDatas), diff --git a/app/Helpers/Admin/Cloudflare/Zone_helper.php b/app/Helpers/Admin/Cloudflare/Zone_helper.php index 10a8955..2b73950 100644 --- a/app/Helpers/Admin/Cloudflare/Zone_helper.php +++ b/app/Helpers/Admin/Cloudflare/Zone_helper.php @@ -1,4 +1,7 @@ "select-field"]); // // return form_multiselect($field, $field_options[$field], is_array($value) ? [...$value] : [$value], [...$attributes]); // foreach ($viewDatas['field_options'][$field] as $key => $label) { @@ -28,14 +31,13 @@ function getFieldForm_ZoneHelper(string $field, mixed $value, array $viewDatas, // } // return implode(" ", $checkboxs); break; - case 'content': - $form = form_input($field, $value, ["placeholder" => "예)123.123.123.123", "style" => "width:60%; ::placeholder{color:silver; opacity: 1;}"]); + case ZoneModel::TITLE: + $form = form_input($field, $value, ["placeholder" => "예)example.com", "style" => "width:60%; ::placeholder{color:silver; opacity: 1;}"]); break; case 'domains': case 'hosts': $form = form_textarea($field, html_entity_decode($value), ['class' => 'editor', 'rows' => '5']); break; - case "type": case "proxied": case "development_mode": case "ipv6": @@ -72,10 +74,6 @@ function getFieldView_ZoneHelper(string $field, mixed $entity, array $viewDatas, case 'sale': $value = number_format(!$value ? 0 : $value) . "원"; break; - case 'stock': - case 'view_cnt': - $value = number_format(!$value ? 0 : $value); - break; case 'content': $value = html_entity_decode($value); break; @@ -112,8 +110,7 @@ function getListHeaders_ZoneHelper(string $field, array $viewDatas, array $attri function getListColumns_ZoneHelper(string $field, mixed $entity, array $viewDatas, array $attributes = []): string { switch ($field) { - case 'title': - case 'name': + case ZoneModel::TITLE: $value = anchor( current_url() . '/view/' . $entity->getPK(), getFieldView_ZoneHelper($field, $entity, $viewDatas), diff --git a/app/Language/en/Admin/Cloudflare/Account.php b/app/Language/en/Admin/Cloudflare/Account.php index 86f818c..12fd1ef 100644 --- a/app/Language/en/Admin/Cloudflare/Account.php +++ b/app/Language/en/Admin/Cloudflare/Account.php @@ -3,11 +3,8 @@ return [ 'title' => "Account정보", 'label' => [ 'uid' => "번호", - 'id' => "인증ID", - 'authkey' => "인증Key", - 'oldkey' => "이전인증Key", - 'title' => "인증명", - 'type' => "인증방식", + 'title' => "계정명", + 'type' => "계정형식", 'status' => "상태", 'updated_at' => "수정일", 'created_at' => "작성일", diff --git a/app/Language/en/Admin/Cloudflare/Auth.php b/app/Language/en/Admin/Cloudflare/Auth.php new file mode 100644 index 0000000..b2e1aff --- /dev/null +++ b/app/Language/en/Admin/Cloudflare/Auth.php @@ -0,0 +1,17 @@ + "Auth정보", + 'label' => [ + 'uid' => "번호", + 'id' => "인증ID", + 'authkey' => "인증Key", + 'oldkey' => "이전인증Key", + 'status' => "상태", + 'updated_at' => "수정일", + 'created_at' => "작성일", + ], + "STATUS" => [ + "use" => "사용", + "unuse" => "사용않함", + ], +]; diff --git a/app/Libraries/MySocket/Cloudflare/AccountSocket.php b/app/Libraries/MySocket/Cloudflare/AccountSocket.php index 6db7ee5..9f161b9 100644 --- a/app/Libraries/MySocket/Cloudflare/AccountSocket.php +++ b/app/Libraries/MySocket/Cloudflare/AccountSocket.php @@ -2,15 +2,26 @@ namespace App\Libraries\MySocket\Cloudflare; -use App\Libraries\MySocket\CloudflareSocket; use App\Models\Cloudflare\AccountModel; +use App\Libraries\MySocket\CloudflareSocket; +use App\Entities\Cloudflare\AuthEntity; class AccountSocket extends CloudflareSocket { - public function __construct(string $email, string $auth_key) + private $_model = null; + private $_auth_entity = null; + public function __construct(AuthEntity $auth_entity) { - parent::__construct(); - $this->setAdapter($email, $auth_key); + $this->_auth_entity = $auth_entity; + parent::__construct($auth_entity); + } + + protected function getModel(): AccountModel + { + if ($this->_model === null) { + $this->_model = new AccountModel(); + } + return $this->_model; } //Result 형태 // [ @@ -36,8 +47,20 @@ class AccountSocket extends CloudflareSocket $formDatas['created_at'] = $result->created_on; return $formDatas; } - public function create(): array + public function reload(): void { - return $this->reload_procedure('accounts'); + log_message("notice", "-----{$this->_auth_entity->getTitle()} 처리 시작-----"); + $entity_uids = []; + $results = $this->reload_procedure("accounts"); + foreach ($results as $result) { + $formDatas = $this->getArrayByResult($result); + $entity = $this->getModel()->modify($this->getModel()->getEntity(), $formDatas); + $entity_uids[] = $entity->getPK(); + } + //부모키를 기준으로 CF에 존재하지 않는 데이터 삭제용 + $this->getModel()->where(AccountModel::PARENT, $this->_auth_entity); + $this->getModel()->whereNotIn(AccountModel::PK, $entity_uids); + $this->getModel()->delete(); + log_message("notice", "-----{$this->_auth_entity->getTitle()} 처리[" . count($results) . "개] 완료-----"); } } diff --git a/app/Libraries/MySocket/Cloudflare/RecordSocket.php b/app/Libraries/MySocket/Cloudflare/RecordSocket.php index 35b9b52..a242fc9 100644 --- a/app/Libraries/MySocket/Cloudflare/RecordSocket.php +++ b/app/Libraries/MySocket/Cloudflare/RecordSocket.php @@ -2,23 +2,35 @@ namespace App\Libraries\MySocket\Cloudflare; -use App\Entities\Cloudflare\AccountEntity; -use App\Entities\Cloudflare\RecordEntity; -use App\Entities\Cloudflare\ZoneEntity; -use App\Libraries\MySocket\CloudflareSocket; use App\Models\Cloudflare\RecordModel; +use App\Libraries\MySocket\CloudflareSocket; +use App\Entities\Cloudflare\ZoneEntity; +use App\Entities\Cloudflare\RecordEntity; +use App\Entities\Cloudflare\AuthEntity; class RecordSocket extends CloudflareSocket { - private $_myStorage = null; - private $_account_entity = null; + private $_model = null; private $_zone_entity = null; - public function __construct(AccountEntity $account_entity, ZoneEntity $zone_entity) + public function __construct(ZoneEntity $zone_entity) { - parent::__construct(); - $this->_account_entity = $account_entity; $this->_zone_entity = $zone_entity; - $this->setAdapter($account_entity->getID(), $account_entity->getAuthKey()); + $account_entity = $this->getAccountModel()->getEntityByPK($this->_zone_entity->getParent()); + if ($account_entity === null) { + throw new \Exception("해당 계정정보를 찾을수 없습니다."); + } + $auth_entity = $this->getAuthModel()->getEntityByPK($account_entity->getParent()); + if ($auth_entity === null) { + throw new \Exception("해당 계정정보를 찾을수 없습니다."); + } + parent::__construct($auth_entity); + } + protected function getModel(): RecordModel + { + if ($this->_model === null) { + $this->_model = new RecordModel(); + } + return $this->_model; } public function getArrayByResult($result, array $formDatas = []): array { @@ -38,21 +50,22 @@ class RecordSocket extends CloudflareSocket $formDatas['created_at'] = $result->created_on; return $formDatas; } - public function create(string $host, array $formDatas): mixed + public function create(string $host, string $type, string $content, string $proxied): RecordEntity { //Socket용 //도메인생성을 위해 Cloudflare에 전송 - $cf = $this->request()->post('zones/' . $this->_zone_entity->getPK() . '/dns_records', [ + $cf = $this->getClient()->post('zones/' . $this->_zone_entity->getPK() . '/dns_records', [ 'name' => $host, - 'type' => $formDatas['type'], - 'content' => $formDatas['content'], - 'proxied' => isset($formDatas['proxied']) && $formDatas['proxied'] === 'on' ? true : false + 'type' => $type, + 'content' => $content, + 'proxied' => $proxied === 'on' ? true : false ]); $cf = json_decode($cf->getBody()); if (!$cf->success) { throw new \Exception("Record:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true)); } - return $cf->result; + $formDatas = $this->getArrayByResult($cf->result); + return $this->getModel()->create($formDatas); } public function modify(RecordEntity $entity, array $formDatas): RecordEntity { @@ -72,7 +85,7 @@ class RecordSocket extends CloudflareSocket $datas['proxied'] = false; $datas['ttl'] = 120; } - $cf = $this->request()->put('zones/' . $this->_zone_entity->getPK() . '/dns_records', $datas); + $cf = $this->getClient()->put('zones/' . $this->_zone_entity->getPK() . '/dns_records', $datas); $cf = json_decode($cf->getBody()); if (!$cf->success) { throw new \Exception("Record:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true)); @@ -82,38 +95,51 @@ class RecordSocket extends CloudflareSocket } public function delete(RecordEntity $entity): void { - $cf = $this->request()->delete('zones/' . $this->_zone_entity->getPK() . '/dns_records/' . $entity->getPK()); + $cf = $this->getClient()->delete('zones/' . $this->_zone_entity->getPK() . '/dns_records/' . $entity->getPK()); $cf = json_decode($cf->getBody()); if (!$cf->success) { throw new \Exception("Record:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true)); } log_message("notice", "Record:" . __FUNCTION__ . "=> 작업을 완료하였습니다."); } - public function sync(RecordEntity $entity): RecordEntity + public function sync(RecordEntity $entity): void { - $cf = $this->request()->get('zones/' . $this->_zone_entity->getPK() . '/dns_records/' . $entity->getPK()); - $cf = json_decode($cf->getBody()); - if (!$cf->success) { - throw new \Exception(__FUNCTION__ . "에서 실패:\n" . var_export($cf, true)); - } - log_message("notice", "Record:" . __FUNCTION__ . "=> 작업을 완료하였습니다."); - return new RecordEntity($this->getArrayByResult($cf->result)); + //Sync형태 + // $cf = $this->getClient()->get("zones/{$this->_zone_entity->getPK()}/dns_records/" . $entity->getPK()); + // $cf = json_decode($cf->getBody()); + // if (!$cf->success) { + // throw new \Exception(__FUNCTION__ . "에서 실패:\n" . var_export($cf, true)); + // } + // return new RecordEntity($this->getArrayByResult($cf->result)); + //Async형태 + $promise = $this->getClient()->getAsync("zones/{$this->_zone_entity->getPK()}/dns_records/{$entity->getPK()}"); + $promise->then( + onFulfilled: function ($response) use ($entity): RecordEntity { + $record = json_decode($response->getBody(), true)['result']; + return $this->getModel()->modify($entity, $this->getArrayByResult($record)); + }, + onRejected: function ($error) { + log_message('error', 'Failed to fetch DNS records: ' . $error->getMessage()); + // throw new \Exception('Failed to fetch DNS records: ' . $error->getMessage()); + } + ); + $promise->wait(); } //Reload - public function reload(RecordModel $model): void + public function reload(): void { log_message("notice", "-----{$this->_zone_entity->getTitle()} 처리 시작-----"); $entity_uids = []; $results = $this->reload_procedure("zones/{$this->_zone_entity->getPK()}/dns_records"); foreach ($results as $result) { $formDatas = $this->getArrayByResult($result); - $entity = $model->modify($model->getEntity(), $formDatas); + $entity = $this->getModel()->modify($this->getModel()->getEntity(), $formDatas); $entity_uids[] = $entity->getPK(); } //부모키를 기준으로 CF에 존재하지 않는 데이터 삭제용 - $model->where($model::PARENT, $this->_zone_entity); - $model->whereNotIn($model::PK, $entity_uids); - $model->delete(); + $this->getModel()->where(RecordModel::PARENT, $this->_zone_entity); + $this->getModel()->whereNotIn(RecordModel::PK, $entity_uids); + $this->getModel()->delete(); log_message("notice", "-----{$this->_zone_entity->getTitle()} 처리[" . count($results) . "개] 완료-----"); } } diff --git a/app/Libraries/MySocket/Cloudflare/ZoneSocket.php b/app/Libraries/MySocket/Cloudflare/ZoneSocket.php index d12c9ac..ed169f7 100644 --- a/app/Libraries/MySocket/Cloudflare/ZoneSocket.php +++ b/app/Libraries/MySocket/Cloudflare/ZoneSocket.php @@ -2,22 +2,33 @@ namespace App\Libraries\MySocket\Cloudflare; -use App\Entities\Cloudflare\AccountEntity; -use App\Entities\Cloudflare\ZoneEntity; -use App\Libraries\MySocket\CloudflareSocket; use App\Models\Cloudflare\ZoneModel; +use App\Libraries\MySocket\CloudflareSocket; +use App\Entities\Cloudflare\ZoneEntity; +use App\Entities\Cloudflare\AuthEntity; +use App\Entities\Cloudflare\AccountEntity; class ZoneSocket extends CloudflareSocket { - private $_myStorage = null; + private $_model = null; private $_account_entity = null; public function __construct(AccountEntity $account_entity) { - parent::__construct(); $this->_account_entity = $account_entity; - $this->setAdapter($account_entity->getID(), $account_entity->getAuthKey()); + $auth_entity = $this->getAuthModel()->getEntityByPK($this->_account_entity->getParent()); + if ($auth_entity === null) { + throw new \Exception("해당 계정정보를 찾을수 없습니다."); + } + parent::__construct($auth_entity); } - public function getArrayByResult($result, array $formDatas = []): array + protected function getModel(): ZoneModel + { + if ($this->_model === null) { + $this->_model = new ZoneModel(); + } + return $this->_model; + } + protected function getArrayByResult($result, array $formDatas = []): array { $formDatas[ZoneModel::PK] = $result->id; $formDatas[ZoneModel::PARENT] = $result->account->id; @@ -47,9 +58,9 @@ class ZoneSocket extends CloudflareSocket return $formDatas; } //Cfzone에서 가져온 값을 zone에 setting - final public function getCFSetting(ZoneEntity $entity): ZoneEntity + protected function getCFSetting(ZoneEntity $entity): ZoneEntity { - $cf = $this->request()->patch('zones/' . $entity->getPK() . '/settings/'); + $cf = $this->getClient()->patch('zones/' . $entity->getPK() . '/settings/'); $cf = json_decode($cf->getBody()); if (!$cf->success) { throw new \Exception("Zone:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true)); @@ -69,9 +80,9 @@ class ZoneSocket extends CloudflareSocket } return $entity; } - public function setCFSetting(ZoneEntity $entity, string $field, string $value): ZoneEntity + protected function setCFSetting(ZoneEntity $entity, string $field, string $value): ZoneEntity { - $cf = $this->request()->patch('zones/' . $entity->getPK() . '/settings/' . $field, array('value' => $value)); + $cf = $this->getClient()->patch('zones/' . $entity->getPK() . '/settings/' . $field, array('value' => $value)); $cf = json_decode($cf->getBody()); if (!$cf->success || $cf->result->id !== $field) { throw new \Exception("Zone:" . __FUNCTION__ . "에서 {$field}->{$value} 변경실패:\n" . var_export($cf, true)); @@ -80,11 +91,11 @@ class ZoneSocket extends CloudflareSocket $entity->$field = $cf->result->value; return $entity; } - public function create(string $domain, bool $jump_start = false): mixed + public function create(string $domain, bool $jump_start = false): ZoneEntity { //Socket용 //도메인생성을 위해 Cloudflare에 전송 - $cf = $this->request()->post('zones/', [ + $cf = $this->getClient()->post('zones/', [ 'accountId' => $this->_account_entity->getPK(), 'name' => $domain, 'jump_start' => $jump_start, @@ -93,7 +104,14 @@ class ZoneSocket extends CloudflareSocket if (!$cf->success) { throw new \Exception("Zone:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true)); } - return $cf->result; + //Storage용 + $formDatas = $this->getArrayByResult($cf->result); + $entity = $this->getModel()->create($formDatas); + //아래는 추가 셋팅 ipv6 TurnOFF , //Development mode TurnOFF + $entity = $this->setCFSetting($entity, 'ipv6', 'off'); + $entity = $this->setCFSetting($entity, 'development_mode', 'off'); + $entity = $this->setCFSetting($entity, 'security_level', 'medium'); + return $entity; } public function modify(ZoneEntity $entity, array $formDatas): ZoneEntity { @@ -106,7 +124,7 @@ class ZoneSocket extends CloudflareSocket } public function delete(ZoneEntity $entity): void { - $cf = $this->request()->delete('zones/' . $entity->getPK()); + $cf = $this->getClient()->delete('zones/' . $entity->getPK()); $cf = json_decode($cf->getBody()); if (!$cf->success) { throw new \Exception("Zone:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true)); @@ -115,7 +133,7 @@ class ZoneSocket extends CloudflareSocket } public function sync(ZoneEntity $entity): ZoneEntity { - $cf = $this->request()->get('zones/' . $entity->getPK()); + $cf = $this->getClient()->get('zones/' . $entity->getPK()); $cf = json_decode($cf->getBody()); if (!$cf->success) { throw new \Exception("Zone:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true)); @@ -124,20 +142,20 @@ class ZoneSocket extends CloudflareSocket return new ZoneEntity($this->getArrayByResult($cf->result)); } //Reload - public function reload(ZoneModel $model): void + public function reload(): void { log_message("notice", "-----{$this->_account_entity->getTitle()} 처리 시작-----"); $entity_uids = []; $results = $this->reload_procedure('zones'); foreach ($results as $result) { $formDatas = $this->getArrayByResult($result); - $entity = $model->modify($model->getEntity(), $formDatas); + $entity = $this->getModel()->modify($this->getModel()->getEntity(), $formDatas); $entity_uids[] = $entity->getPK(); } //부모키를 기준으로 CF에 존재하지 않는 데이터 삭제용 - $model->where($model::PARENT, $this->_account_entity); - $model->whereNotIn($model::PK, $entity_uids); - $model->delete(); + $this->getModel()->where(ZoneModel::PARENT, $this->_account_entity); + $this->getModel()->whereNotIn(ZoneModel::PK, $entity_uids); + $this->getModel()->delete(); log_message("notice", "-----{$this->_account_entity->getTitle()} 처리[" . count($results) . "개] 완료-----"); } } diff --git a/app/Libraries/MySocket/CloudflareSocket.php b/app/Libraries/MySocket/CloudflareSocket.php index d592464..0bf1eb3 100644 --- a/app/Libraries/MySocket/CloudflareSocket.php +++ b/app/Libraries/MySocket/CloudflareSocket.php @@ -3,30 +3,54 @@ namespace App\Libraries\MySocket; -use Cloudflare\API\Auth\APIKey; -use Cloudflare\API\Adapter\Guzzle; +use GuzzleHttp\Client; +use App\Models\Cloudflare\AuthModel; +use App\Models\Cloudflare\AccountModel; use App\Libraries\CommonLibrary; +use App\Entities\Cloudflare\AuthEntity; abstract class CloudflareSocket extends CommonLibrary { private static int $_request = 0; private static int $_request_max = 100; private static int $_request_timewait = 60; - private $_adapter = null; - protected function __construct() + private $_authModel = null; + private $_accountModel = null; + private $_client = null; + private $_auth_entity = null; + protected function __construct(AuthEntity $auth_entity) { parent::__construct(); + $this->_auth_entity = $auth_entity; self::$_request_max = getenv("cfmgr.request.max"); } - abstract public function getArrayByResult($result, array $formDatas = []): array; - final protected function setAdapter(string $email, string $auth_key): void + abstract protected function getArrayByResult($result, array $formDatas = []): array; + final protected function getAuthModel(): AuthModel { - $this->_adapter = new Guzzle(new APIKey($email, $auth_key)); + if ($this->_authModel === null) { + $this->_authModel = new AuthModel(); + } + return $this->_authModel; } - final public function request(): Guzzle + final protected function getAccountModel(): AccountModel { - if ($this->_adapter === null) { - throw new \Exception(+__FUNCTION__ . " => Adapter를 정의하지 않았습니다."); + if ($this->_accountModel === null) { + $this->_accountModel = new AccountModel(); + } + return $this->_accountModel; + } + final protected function getClient(): Client + { + if ($this->_client === null) { + // Guzzle HTTP 클라이언트를 설정하면서 Cloudflare API 토큰 사용 + $this->_client = new Client([ + 'base_uri' => 'https://api.cloudflare.com/client/v4/', + 'headers' => [ + 'X-Auth-Email' => $this->_auth_entity->getID(), // 인증 토큰 사용 + 'X-Auth-Key' => $this->_auth_entity->getAuthKey(), // 인증 토큰 사용 + 'Content-Type' => 'application/json', + ] + ]); } if (self::$_request >= self::$_request_max) { log_message('warning', sprintf("--Cloudflare API Call %s초 대기 시작--", self::$_request_timewait)); @@ -35,8 +59,9 @@ abstract class CloudflareSocket extends CommonLibrary log_message('warning', sprintf("--Cloudflare API Call %s초 대기 종료--", self::$_request_timewait)); } self::$_request++; - return $this->_adapter; + return $this->_client; } + final protected function reload_procedure($uri): array { $page = 1; //Page는 1부터 시작해야함 @@ -48,7 +73,7 @@ abstract class CloudflareSocket extends CommonLibrary 'per_page' => $perpage_max, 'match' => 'all', ]; - $cf = $this->request()->get($uri, $query); + $cf = $this->getClient()->get($uri, $query); $cf = json_decode($cf->getBody()); if (!$cf->success) { throw new \Exception(__FUNCTION__ . "에서 실패:\n" . var_export($cf, true)); diff --git a/app/Models/Cloudflare/AccountModel.php b/app/Models/Cloudflare/AccountModel.php index 913bca7..edf51f6 100644 --- a/app/Models/Cloudflare/AccountModel.php +++ b/app/Models/Cloudflare/AccountModel.php @@ -2,19 +2,21 @@ namespace App\Models\Cloudflare; -use App\Entities\Cloudflare\AccountEntity; use App\Models\CommonModel; +use App\Entities\Cloudflare\AuthEntity; +use App\Entities\Cloudflare\AccountEntity; class AccountModel extends CommonModel { const TABLE = "cloudflareaccount"; const PK = "uid"; const TITLE = "title"; + const PARENT = "account_uid"; protected $table = self::TABLE; protected $primaryKey = self::PK; protected $useAutoIncrement = false; protected $returnType = AccountEntity::class; //object,array,entity명::class - protected $allowedFields = [self::PK, self::TITLE, 'authkey', 'oldkey', 'title', 'type', 'status', 'updated_at', 'created_at']; + protected $allowedFields = [self::PK, self::PARENT, self::TITLE, 'type', 'status', 'updated_at', 'created_at']; protected $useTimestamps = true; public function __construct() { @@ -27,18 +29,11 @@ class AccountModel extends CommonModel public function getFieldRule(string $action, string $field, array $rules): array { switch ($field) { - case self::TITLE: - $rules[$field] = "required|valid_emailvalid_email|is_unique[cloudflareauth.id]"; - break; - case 'id': - $rules[$field] = "required|valid_emailvalid_email|is_unique[cloudflareauth.id]"; - break; - case "authkey": + case self::PARENT: $rules[$field] = "required|regex_match[/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/]"; - ; break; - case "oldkey": - $rules[$field] = "if_exist|regex_match[/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/]"; + case self::TITLE: + $rules[$field] = "required|trim|string"; break; case "type": $rules[$field] = "if_exist|in_list[standard,enterprise]"; @@ -66,9 +61,14 @@ class AccountModel extends CommonModel } public function getEntityByID(string $id): null|AccountEntity { - $this->where('id', $id); + $this->where(self::TITLE, $id); return $this->getEntity(); } + public function getEntitysByParent(AuthEntity $auth_entity) + { + $this->where(self::PARENT, $auth_entity->getPK()); + return $this->getEntitys(); + } //create용 public function create(array $formDatas = []): AccountEntity { diff --git a/app/Models/Cloudflare/AuthModel.php b/app/Models/Cloudflare/AuthModel.php new file mode 100644 index 0000000..0f27c84 --- /dev/null +++ b/app/Models/Cloudflare/AuthModel.php @@ -0,0 +1,75 @@ +orderBy(self::TITLE, 'asc'); + $options = parent::getFormFieldOption($field, $options); + break; + } + return $options; + } + public function getEntityByPK(int $uid): null|AuthEntity + { + $this->where($this->getPKField(), $uid); + return $this->getEntity(); + } + public function getEntityByID(string $id): null|AuthEntity + { + $this->where('id', $id); + return $this->getEntity(); + } + //create용 + public function create(array $formDatas = []): AuthEntity + { + return $this->create_process(new AuthEntity(), $formDatas); + } + //modify용 + public function modify(AuthEntity $entity, array $formDatas): AuthEntity + { + return $this->modify_process($entity, $formDatas); + } +} diff --git a/app/Views/admin/cloudflare/account/index.php b/app/Views/admin/cloudflare/account/index.php index ba262a2..07ba7a6 100644 --- a/app/Views/admin/cloudflare/account/index.php +++ b/app/Views/admin/cloudflare/account/index.php @@ -69,19 +69,4 @@
- - endSection() ?> \ No newline at end of file diff --git a/app/Views/admin/cloudflare/account/create.php b/app/Views/admin/cloudflare/auth/create.php similarity index 80% rename from app/Views/admin/cloudflare/account/create.php rename to app/Views/admin/cloudflare/auth/create.php index 5386d0a..14bbfd8 100644 --- a/app/Views/admin/cloudflare/account/create.php +++ b/app/Views/admin/cloudflare/auth/create.php @@ -3,9 +3,9 @@ - + diff --git a/app/Views/admin/cloudflare/auth/index.php b/app/Views/admin/cloudflare/auth/index.php new file mode 100644 index 0000000..722eacc --- /dev/null +++ b/app/Views/admin/cloudflare/auth/index.php @@ -0,0 +1,87 @@ +extend("layouts/{$viewDatas['layout']}") ?> +section('content') ?> + + + "get")) ?> + + + +
- +
+ + + + + + + + + + + + + status != DEFAULTS['STATUS'] ? 'class="table-danger" rowcolor="red"' : 'rowcolor="red"' ?> onClick="indexRowCheckBoxToggle(this)"> + + + + + + + + + +
번호작업
+ "checkbox_uid_{$entity->getPK()}", "name" => "batchjob_uids[]", "value" => $entity->getPK(), "class" => "batchjobuids_checkboxs"]); ?> + getPK(), $viewDatas['total_count'] - (($viewDatas['page'] - 1) * $viewDatas['per_page'] + $cnt), ["target" => "_self"]) ?> + + getPK(), ICONS['DELETE'], ["class" => "btn btn-sm btn-danger btn-circle", "target" => "_self"]) ?> +
+
+ +
+
+ + + +endSection() ?> \ No newline at end of file diff --git a/app/Views/layouts/admin/left_menu/cloudflare.php b/app/Views/layouts/admin/left_menu/cloudflare.php index d8f5663..7a1f72b 100644 --- a/app/Views/layouts/admin/left_menu/cloudflare.php +++ b/app/Views/layouts/admin/left_menu/cloudflare.php @@ -5,7 +5,10 @@
-

Account

+

Auth

+
+
+

Account

Zone