From 854a064a233a225336fbea30e216d75282638725 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=B5=9C=EC=A4=80=ED=9D=A0?= Date: Sat, 21 Sep 2024 11:33:14 +0900 Subject: [PATCH] Automation init...4 --- .../Cloudflare/AccountController.php | 119 ++++++---------- .../Cloudflare/Admin/AccountController.php | 52 ------- .../Cloudflare/Admin/AuthController.php | 79 ----------- app/Controllers/Cloudflare/MyCloudflare.php | 22 --- app/Controllers/Cloudflare/ZoneController.php | 86 ++++++++++++ app/Controllers/CommonController.php | 84 ----------- app/Controllers/MVController.php | 131 ++++++++++++++++++ app/Entities/Cloudflare/AccountEntity.php | 10 +- app/Entities/Cloudflare/AuthEntity.php | 30 ---- app/Entities/Cloudflare/ZoneEntity.php | 29 ++-- .../MySocket/Cloudflare/AccountSocket.php | 27 ---- app/Libraries/MySocket/CloudflareSocket.php | 51 +++++-- .../MyStorage/Cloudflare/AccountStorage.php | 50 ------- .../MyStorage/Cloudflare/AuthStorage.php | 50 ------- app/Models/Cloudflare/AccountModel.php | 11 +- app/Models/Cloudflare/AuthModel.php | 63 --------- app/Models/Cloudflare/ZoneModel.php | 131 ++++++++---------- 17 files changed, 386 insertions(+), 639 deletions(-) delete mode 100644 app/Controllers/Cloudflare/Admin/AccountController.php delete mode 100644 app/Controllers/Cloudflare/Admin/AuthController.php delete mode 100644 app/Controllers/Cloudflare/MyCloudflare.php create mode 100644 app/Controllers/Cloudflare/ZoneController.php create mode 100644 app/Controllers/MVController.php delete mode 100644 app/Entities/Cloudflare/AuthEntity.php delete mode 100644 app/Libraries/MySocket/Cloudflare/AccountSocket.php delete mode 100644 app/Libraries/MyStorage/Cloudflare/AccountStorage.php delete mode 100644 app/Libraries/MyStorage/Cloudflare/AuthStorage.php delete mode 100644 app/Models/Cloudflare/AuthModel.php diff --git a/app/Controllers/Cloudflare/AccountController.php b/app/Controllers/Cloudflare/AccountController.php index 68397c0..2adbed1 100644 --- a/app/Controllers/Cloudflare/AccountController.php +++ b/app/Controllers/Cloudflare/AccountController.php @@ -2,33 +2,33 @@ namespace App\Controllers\Cloudflare; -use App\Entities\Cloudflare\AccountEntity; -use App\Libraries\MySocket\Cloudflare\AccountSocket; - -use CodeIgniter\HTTP\RedirectResponse; -use CodeIgniter\HTTP\RequestInterface; -use CodeIgniter\HTTP\ResponseInterface; +use App\Controllers\MVController; use Psr\Log\LoggerInterface; +use CodeIgniter\HTTP\ResponseInterface; +use CodeIgniter\HTTP\RequestInterface; +use CodeIgniter\HTTP\RedirectResponse; +use App\Traits\AuthTrait; use App\Models\Cloudflare\AccountModel; -use App\Traits\AccountTrait; +use App\Libraries\MySocket\CloudflareSocket; +use App\Entities\Cloudflare\AccountEntity; -class AccountController extends MyCloudflare +class AccountController extends MVController { - use AccountTrait; - private $_mySocket = null; + use AuthTrait; private $_model = null; public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { parent::initController($request, $response, $logger); - $this->session = $this->session_AccountTrait(); + $this->session = $this->session_AuthTrait(); $this->class_name = 'Account'; helper($this->class_name); } - final protected function getMySocket(): AccountSocket + + final protected function getMySocket(): CloudflareSocket { if ($this->_mySocket === null) { - $this->_mySocket = new AccountSocket($auth_uid); + $this->_mySocket = new CloudflareSocket(); } return $this->_mySocket; } @@ -41,77 +41,46 @@ class AccountController extends MyCloudflare return $this->_model; } - protected function create_form_process(): void + protected function create_init(): void { - $this->fields = ['id', 'authkey']; + $this->fields = ['id', 'apikey']; $this->filter_fields = ['status']; - parent::create_form_process(); + $this->action = DB_ACTION["CREATE"]; + $this->getModel()->setAction($this->action); } public function create_form(): RedirectResponse|string { - try { - $this->fields = ['id', 'authkey']; - $this->filter_fields = ['status']; - $this->action = 'create'; - $this->getModel()->setAction($this->action); - $this->session->keepFlashdata(SESSION_NAMES['RETURN_URL']); - return view("/{$this->class_name}/insert", ['attributes' => $this->getAttributes]); - } catch (\Exception $e) { - log_message("error", $e->getMessage()); - return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/")->with(SESSION_NAMES['RETURN_MSG'], $e->getMessage()); - } + return $this->create_form_process(); } - protected function create_process($model): AccountEntity + + //Result 형태 + // [ + // {"id":"078e88a7735965b661715af13031ecb0", + // "name":"Cloudwin002@idcjp.jp's Auth", + // "type":"standard", + // "settings":{ + // "enforce_twofactor":false, + // "api_access_enabled":null, + // "access_approval_expiry":null, + // "use_account_custom_ns_by_default":false + // }, + // "legacy_flags":{"enterprise_zone_quota":{"maximum":0,"current":0,"available":0}}, + // "created_on":"2017-06-26T05:44:49.470184Z"} + // ] + protected function create_process_submit(): AccountEntity { - $datas = [ - 'name' => $name . "'s Account", - 'type' => 'standard', - ]; - $result = $this->getClient()->post("accounts", $datas); - $result = json_decode($result->getBody()); - if (!$result->success) { - throw new \Exception(var_export($result, true)); - } - //Result 형태 - // [ - // {"id":"078e88a7735965b661715af13031ecb0", - // "name":"Cloudwin002@idcjp.jp's Auth", - // "type":"standard", - // "settings":{ - // "enforce_twofactor":false, - // "api_access_enabled":null, - // "access_approval_expiry":null, - // "use_account_custom_ns_by_default":false - // }, - // "legacy_flags":{"enterprise_zone_quota":{"maximum":0,"current":0,"available":0}}, - // "created_on":"2017-06-26T05:44:49.470184Z"} - // ] - $formDatas[$this->getAuthModel()->PK()] = $result->id; - $formDatas[$this->getAuthModel()->getTitleField()] = $result->name; - $formDatas['type'] = $result->type; - $formDatas['status'] = 'use'; - $formDatas['updated_at'] = $result->created_on; - $formDatas['created_at'] = $result->created_on; - return parent::create_process($model); + $this->getMySocket()->setAPIKey($this->formDatas['apikey']); + $result = $this->getMySocket()->getAccount()->addAccount($this->formDatas['id']); + $this->formDatas[$this->getModel()->PK()] = $result->id; + $this->formDatas[$this->getModel()->getTitleField()] = $result->name; + $this->formDatas['type'] = $result->type; + $this->formDatas['status'] = 'use'; + $this->formDatas['updated_at'] = $result->created_on; + $this->formDatas['created_at'] = $result->created_on; + return $this->getModel()->create($this->formDatas); } public function create(): RedirectResponse { - $this->getModel()->transStart(); - try { - $this->fields = ['id', 'authkey']; - $this->filter_fields = ['status']; - $this->action = 'create'; - $this->getModel()->setAction($this->action); - $entity = $this->create_process($this->getModel()); - log_message("notice", __FUNCTION__ . "=>{$entity->getTitle()} 작업을 완료하였습니다."); - 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()); - $this->session->keepFlashdata(SESSION_NAMES['RETURN_URL']); - return redirect()->back()->withInput(); - } + return parent::create_process(); } } diff --git a/app/Controllers/Cloudflare/Admin/AccountController.php b/app/Controllers/Cloudflare/Admin/AccountController.php deleted file mode 100644 index 1003af3..0000000 --- a/app/Controllers/Cloudflare/Admin/AccountController.php +++ /dev/null @@ -1,52 +0,0 @@ -session = $this->session_AuthTrait(); - } - final protected function getMySocket(): AccountSocket - { - if ($this->_mySocket === null) { - $this->_mySocket = new AccountSocket($this->_email, $this->_api_key); - } - return $this->_mySocket; - } - final protected function getMyStorage(): AccountStorage - { - if ($this->_myStorage === null) { - $this->_myStorage = new AccountStorage(); - } - return $this->_myStorage; - } - - public function create(): void - { - $this->_email = $this->request->getVar('email'); - $this->_api_key = $this->request->getVar('key'); - //전송 - $result = $this->getMySocket()->create_process($this->_email); - $formDatas = []; - $formDatas['key'] = $this->_api_key; - $entity = $this->getMyStorage()->create_process($result, $formDatas); - log_message("notice", __FUNCTION__ . "=> 작업을 완료하였습니다."); - } -} diff --git a/app/Controllers/Cloudflare/Admin/AuthController.php b/app/Controllers/Cloudflare/Admin/AuthController.php deleted file mode 100644 index 9ad8a2f..0000000 --- a/app/Controllers/Cloudflare/Admin/AuthController.php +++ /dev/null @@ -1,79 +0,0 @@ -session = $this->session_AuthTrait(); - $this->class_name = 'Auth'; - helper($this->class_name); - } - final protected function getModel(): AuthModel - { - if ($this->_model === null) { - $this->_model = new AuthModel(); - } - return $this->_model; - } - - protected function create_form_process(): void - { - $this->fields = ['id', 'authkey']; - $this->filter_fields = ['status']; - parent::create_form_process(); - } - public function create_form(): RedirectResponse|string - { - try { - $this->fields = ['id', 'authkey']; - $this->filter_fields = ['status']; - $this->action = 'create'; - $this->getModel()->setAction($this->action); - $this->session->keepFlashdata(SESSION_NAMES['RETURN_URL']); - return view("/{$this->class_name}/insert", ['attributes' => $this->getAttributes]); - } catch (\Exception $e) { - log_message("error", $e->getMessage()); - return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/")->with(SESSION_NAMES['RETURN_MSG'], $e->getMessage()); - } - } - protected function create_process($model): AuthEntity - { - return parent::create_process($model); - } - public function create(): RedirectResponse - { - $this->getModel()->transStart(); - try { - $this->fields = ['id', 'authkey']; - $this->filter_fields = ['status']; - $this->action = 'create'; - $this->getModel()->setAction($this->action); - $entity = $this->create_process($this->getModel()); - log_message("notice", __FUNCTION__ . "=>{$entity->getTitle()} 작업을 완료하였습니다."); - 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()); - $this->session->keepFlashdata(SESSION_NAMES['RETURN_URL']); - return redirect()->back()->withInput(); - } - } -} diff --git a/app/Controllers/Cloudflare/MyCloudflare.php b/app/Controllers/Cloudflare/MyCloudflare.php deleted file mode 100644 index a712f76..0000000 --- a/app/Controllers/Cloudflare/MyCloudflare.php +++ /dev/null @@ -1,22 +0,0 @@ -session = $this->session_AuthTrait(); + $this->class_name = 'Zone'; + helper($this->class_name); + } + + final protected function getMySocket(): CloudflareSocket + { + if ($this->_mySocket === null) { + $this->_mySocket = new CloudflareSocket(); + } + return $this->_mySocket; + } + + final protected function getModel(): ZoneModel + { + if ($this->_model === null) { + $this->_model = new ZoneModel(); + } + return $this->_model; + } + + protected function create_init(): void + { + $this->fields = ['id', 'apikey']; + $this->filter_fields = ['status']; + $this->action = 'create'; + $this->getModel()->setAction($this->action); + } + public function create_form(): RedirectResponse|string + { + return $this->create_form_process(); + } + + //Result 형태 + // [ + // {"id":"078e88a7735965b661715af13031ecb0", + // "name":"Cloudwin002@idcjp.jp's Auth", + // "type":"standard", + // "settings":{ + // "enforce_twofactor":false, + // "api_access_enabled":null, + // "access_approval_expiry":null, + // "use_account_custom_ns_by_default":false + // }, + // "legacy_flags":{"enterprise_zone_quota":{"maximum":0,"current":0,"available":0}}, + // "created_on":"2017-06-26T05:44:49.470184Z"} + // ] + protected function create_process_submit(): ZoneEntity + { + $this->getMySocket()->setAPIKey($this->formDatas['apikey']); + $result = $this->getMySocket()->getZone()->addZone($this->formDatas['id']); + $this->formDatas[$this->getModel()->PK()] = $result->id; + $this->formDatas[$this->getModel()->getTitleField()] = $result->name; + $this->formDatas['type'] = $result->type; + $this->formDatas['status'] = 'use'; + $this->formDatas['updated_at'] = $result->created_on; + $this->formDatas['created_at'] = $result->created_on; + return $this->getModel()->create($this->formDatas); + } + public function create(): RedirectResponse + { + return parent::create_process(); + } +} diff --git a/app/Controllers/CommonController.php b/app/Controllers/CommonController.php index 6ca9686..2730189 100644 --- a/app/Controllers/CommonController.php +++ b/app/Controllers/CommonController.php @@ -29,88 +29,4 @@ abstract class CommonController extends BaseController { return $this->_attributes; } - //Field별 Form Option용 - protected function getFormFilterOption(string $filter_field, array $filter_options): array - { - switch ($filter_field) { - default: - $temps = lang($this->class_name . '.' . strtoupper($filter_field)); - if (!is_array($temps)) { - throw new \Exception(__FUNCTION__ . "에서 {$filter_field}의 데이터가 array가 아닙니다.\n" . var_export($temps, true)); - } - $filter_options[$filter_field] = [ - ["" => lang($this->class_name . '.label.' . $filter_field) . ' 선택'], - lang($this->class_name . '.' . strtoupper($filter_field)) - ]; - break; - } - return $filter_options; - } - //Field별 Form Option용 - final public function getFormFilterOptions(array $filter_options = []): array - { - foreach ($this->filter_fields as $filter_field) { - if (is_array($filter_field)) { - throw new \Exception(__FUNCTION__ . "에서 filter_field가 array 입니다.\n" . var_export($filter_field, true)); - } - $filter_options = $this->getFormFilterOption($filter_field, $filter_options); - } - return $filter_options; - } - protected function getFormFieldRule(string $field, array $rules): array - { - if (is_array($field)) { - throw new \Exception(__FUNCTION__ . "=> field가 array 입니다.\n" . var_export($field, true)); - } - switch ($field) { - default: - $rules[$field] = $this->_model->getFieldRule($field, $rules);; - break; - } - return $rules; - } - final public function getFormFieldRules(array $rules = []): array - { - foreach ($this->fields as $field) { - $rules = $this->getFormFieldRule($field, $rules); - } - return $rules; - } - //전송된 데이터 - protected function getFormData(string $field): void - { - switch ($field) { - default: - $this->formDatas[$field] = rtrim($this->request->getVar($field)); - break; - } - } - //전송된 데이터 재정의 - protected function convertFormData(string $field): void - { - switch ($field) { - default: - break; - } - } - protected function create_form_process(): void - { - helper(['form']); - } - protected function create_process($model): mixed - { - //변경할 값 확인 : Upload된 파일 검증시 $this->request->getVar()보다 먼처 체크필요 - $validation = \Config\Services::validation(); - $validation->setRules($model->getFieldRules($this->fields)); - if (!$validation->withRequest($this->request)->run()) { - throw new \Exception("데이터 검증 오류발생\n" . implode("\n", $this->validator->getErrors())); - } - foreach ($this->fields as $field) { - $this->getFormData($field); - } - foreach ($this->fields as $field) { - $this->convertFormData($field); - } - return $model->create($this->formDatas); - } } diff --git a/app/Controllers/MVController.php b/app/Controllers/MVController.php new file mode 100644 index 0000000..1b4c8e8 --- /dev/null +++ b/app/Controllers/MVController.php @@ -0,0 +1,131 @@ +class_name . '.' . strtoupper($filter_field)); + if (!is_array($temps)) { + throw new \Exception(__FUNCTION__ . "에서 {$filter_field}의 데이터가 array가 아닙니다.\n" . var_export($temps, true)); + } + $filter_options[$filter_field] = [ + ["" => lang($this->class_name . '.label.' . $filter_field) . ' 선택'], + lang($this->class_name . '.' . strtoupper($filter_field)) + ]; + break; + } + return $filter_options; + } + //Field별 Form Option용 + final public function getFormFilterOptions(array $filter_options = []): array + { + foreach ($this->filter_fields as $filter_field) { + if (is_array($filter_field)) { + throw new \Exception(__FUNCTION__ . "에서 filter_field가 array 입니다.\n" . var_export($filter_field, true)); + } + $filter_options = $this->getFormFilterOption($filter_field, $filter_options); + } + return $filter_options; + } + protected function getFormFieldRule(string $field, array $rules): array + { + if (is_array($field)) { + throw new \Exception(__FUNCTION__ . "=> field가 array 입니다.\n" . var_export($field, true)); + } + switch ($field) { + default: + $rules[$field] = $this->_model->getFieldRule($field, $rules);; + break; + } + return $rules; + } + final public function getFormFieldRules(array $rules = []): array + { + foreach ($this->fields as $field) { + $rules = $this->getFormFieldRule($field, $rules); + } + return $rules; + } + //전송된 데이터 검증 + protected function validateFormData(): void + { + //변경할 값 확인 : Upload된 파일 검증시 $this->request->getVar()보다 먼처 체크필요 + $validation = \Config\Services::validation(); + $validation->setRules($this->getModel()->getFieldRules($this->fields)); + if (!$validation->withRequest($this->request)->run()) { + throw new \Exception("데이터 검증 오류발생\n" . implode("\n", $this->validator->getErrors())); + } + } + //전송된 데이터 + protected function getFormData(string $field): void + { + switch ($field) { + default: + $this->formDatas[$field] = rtrim($this->request->getVar($field)); + break; + } + } + //전송된 데이터 재정의 + protected function convertFormData(string $field): void + { + switch ($field) { + default: + break; + } + } + + final public function create_form_process(): RedirectResponse|string + { + helper(['form']); + try { + $this->create_init(); + $this->create_form_process(); + $this->session->keepFlashdata(SESSION_NAMES['RETURN_URL']); + return view("/{$this->class_name}/insert", ['attributes' => $this->getAttributes]); + } catch (\Exception $e) { + log_message("error", $e->getMessage()); + return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/")->with(SESSION_NAMES['RETURN_MSG'], $e->getMessage()); + } + } + abstract protected function create_process_submit(): mixed; + final protected function create_process(): mixed + { + $this->getModel()->transStart(); + try { + $this->create_init(); + $this->validateFormData(); + foreach ($this->fields as $field) { + $this->getFormData($field); + } + foreach ($this->fields as $field) { + $this->convertFormData($field); + } + $entity = $this->create_process_submit(); + log_message("notice", __FUNCTION__ . "=>{$entity->getTitle()} 작업을 완료하였습니다."); + 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()); + $this->session->keepFlashdata(SESSION_NAMES['RETURN_URL']); + return redirect()->back()->withInput(); + } + } +} diff --git a/app/Entities/Cloudflare/AccountEntity.php b/app/Entities/Cloudflare/AccountEntity.php index 35984b7..84319f3 100644 --- a/app/Entities/Cloudflare/AccountEntity.php +++ b/app/Entities/Cloudflare/AccountEntity.php @@ -8,7 +8,7 @@ class AccountEntity extends CommonEntity { public function __toString() { - return "{$this->getPK()}|{$this->getTitle()}|{$this->getKey()}|{$this->attributes['type']}|{$this->attributes['status']}"; + return "{$this->getPK()}|{$this->getTitle()}|{$this->getAPIKey()}|{$this->attributes['type']}|{$this->attributes['status']}"; } public function getPK(): int { @@ -16,15 +16,15 @@ class AccountEntity extends CommonEntity } public function getTitle(): string { - return $this->attributes['email']; + return $this->attributes['id']; } public function setTitle(string $title): void { - $this->attributes['email'] = $title; + $this->attributes['id'] = $title; } //Common Function - public function getKey(): string + public function getAPIKey(): string { - return $this->attributes['key']; + return $this->attributes['apikey']; } } diff --git a/app/Entities/Cloudflare/AuthEntity.php b/app/Entities/Cloudflare/AuthEntity.php deleted file mode 100644 index b715937..0000000 --- a/app/Entities/Cloudflare/AuthEntity.php +++ /dev/null @@ -1,30 +0,0 @@ -getPK()}|{$this->getTitle()}|{$this->getKey()}|{$this->attributes['type']}|{$this->attributes['status']}"; - } - public function getPK(): int - { - return $this->attributes['uid']; - } - public function getTitle(): string - { - return $this->attributes['id']; - } - public function setTitle(string $title): void - { - $this->attributes['id'] = $title; - } - //Common Function - public function getKey(): string - { - return $this->attributes['key']; - } -} diff --git a/app/Entities/Cloudflare/ZoneEntity.php b/app/Entities/Cloudflare/ZoneEntity.php index 4eac641..83c673e 100644 --- a/app/Entities/Cloudflare/ZoneEntity.php +++ b/app/Entities/Cloudflare/ZoneEntity.php @@ -1,27 +1,26 @@ getPK()}|{$this->attributes['account_uid']}|{$this->getTitle()}|{$this->attributes['development_mode']}|{$this->attributes['ipv6']}|{$this->attributes['security_level']}"; + } + public function getPK(): int { return $this->attributes['uid']; } - public function getTitle() + public function getTitle(): string { - return $this->attributes['domain']; + return $this->attributes['id']; } - public function __toString() + public function setTitle(string $title): void { - return "uid:{$this->attributes['uid']}|account_uid:{$this->attributes['account_uid']}|domain:{$this->attributes['domain']}|{$this->attributes['development_mode']}|{$this->attributes['ipv6']}|{$this->attributes['security_level']}"; - } - public function getParentField(): string - { - return "account_uid"; + $this->attributes['id'] = $title; } + //Common Function } diff --git a/app/Libraries/MySocket/Cloudflare/AccountSocket.php b/app/Libraries/MySocket/Cloudflare/AccountSocket.php deleted file mode 100644 index b0c220c..0000000 --- a/app/Libraries/MySocket/Cloudflare/AccountSocket.php +++ /dev/null @@ -1,27 +0,0 @@ - $name . "'s Account", - 'type' => $type, - ]; - $result = $this->getClient()->post("accounts", $datas); - $result = json_decode($result->getBody()); - if (!$result->success) { - throw new \Exception(var_export($result, true)); - } - return $result; - } -} diff --git a/app/Libraries/MySocket/CloudflareSocket.php b/app/Libraries/MySocket/CloudflareSocket.php index 8dbfa7c..eb648d6 100644 --- a/app/Libraries/MySocket/CloudflareSocket.php +++ b/app/Libraries/MySocket/CloudflareSocket.php @@ -4,8 +4,11 @@ namespace App\Libraries\MySocket; use App\Libraries\CommonLibrary; use App\Models\Cloudflare\AccountModel; -use Cloudflare\API\Adapter\Guzzle; use Cloudflare\API\Auth\APIKey; +use Cloudflare\API\Adapter\Guzzle; +use Cloudflare\API\Endpoints\Zones; +use Cloudflare\API\Endpoints\Accounts; +use Cloudflare\API\Endpoints\DNS; class CloudflareSocket extends CommonLibrary { @@ -14,15 +17,24 @@ class CloudflareSocket extends CommonLibrary private static int $_request_timewait = 60; private $_accountModel = null; private $_clients = []; - private $_auth_uid = ""; - public function __construct(string $auth_uid) + protected $_apikey = ""; + public function __construct() { parent::__construct(); - $this->initClients(); - $this->_auth_uid = $auth_uid; + $this->initAdapters(); self::$_request_max = getenv("cfmgr.request.max"); } - + final public function getAPIKey(): string + { + if ($this->_apikey == "") { + throw new \Exception("APIKey가 정의되지 않았습니다."); + } + return $this->_apikey; + } + final public function setAPIKey(string $apikey): void + { + $this->_apikey = $apikey; + } final protected function getAccountModel(): AccountModel { if ($this->_accountModel === null) { @@ -30,19 +42,19 @@ class CloudflareSocket extends CommonLibrary } return $this->_accountModel; } - final public function initClients(): void + final public function initAdapters(): void { foreach ($this->getAccountModel()->getEntitys() as $entity) { - $this->_clients[$entity->getKey()] = new Guzzle( - new APIKey($entity->getTitle(), $entity->getKey()) + $this->_clients[$entity->getAPIKey()] = new Guzzle( + new APIKey($entity->getTitle(), $entity->getAPIKey()) ); } } - final public function getClient(): Guzzle + private function getAdapter(): Guzzle { - if (!array_key_exists($this->_auth_uid, $this->_clients)) { - throw new \Exception(+__FUNCTION__ . " => {$this->_auth_uid}에 해당하는 Adapter를 찾을수 없습니다."); + if (!array_key_exists($this->getAPIKey(), $this->_clients)) { + throw new \Exception(+__FUNCTION__ . " => {$this->getAPIKey()}에 해당하는 Adapter를 찾을수 없습니다."); } if (self::$_request >= self::$_request_max) { log_message('warning', sprintf("--Cloudflare API Call %s초 대기 시작--", self::$_request_timewait)); @@ -51,6 +63,19 @@ class CloudflareSocket extends CommonLibrary log_message('warning', sprintf("--Cloudflare API Call %s초 대기 종료--", self::$_request_timewait)); } self::$_request++; - return $this->_client; + return $this->_clients[$this->getAPIKey()]; + } + + public function getAccount(): Accounts + { + return new Accounts($this->getAdapter()); + } + public function getZone(): Zones + { + return new Zones($this->getAdapter()); + } + public function getRecord(): DNS + { + return new DNS($this->getAdapter()); } } diff --git a/app/Libraries/MyStorage/Cloudflare/AccountStorage.php b/app/Libraries/MyStorage/Cloudflare/AccountStorage.php deleted file mode 100644 index 74a87ac..0000000 --- a/app/Libraries/MyStorage/Cloudflare/AccountStorage.php +++ /dev/null @@ -1,50 +0,0 @@ -_accountModel === null) { - $this->_accountModel = new AccountModel(); - } - return $this->_accountModel; - } - - final public function create_process($result, array $formDatas): AccountEntity - { - //Result 형태 - // [ - // {"id":"078e88a7735965b661715af13031ecb0", - // "name":"Cloudwin002@idcjp.jp's Account", - // "type":"standard", - // "settings":{ - // "enforce_twofactor":false, - // "api_access_enabled":null, - // "access_approval_expiry":null, - // "use_account_custom_ns_by_default":false - // }, - // "legacy_flags":{"enterprise_zone_quota":{"maximum":0,"current":0,"available":0}}, - // "created_on":"2017-06-26T05:44:49.470184Z"} - // ] - $formDatas[$this->getAccountModel()->PK()] = $result->id; - $formDatas[$this->getAccountModel()->getTitleField()] = $result->name; - $formDatas['type'] = $result->type; - $formDatas['status'] = 'use'; - $formDatas['updated_at'] = $result->created_on; - $formDatas['created_at'] = $result->created_on; - $entity = $this->getAccountModel()->create($formDatas); - log_message("notice", __FUNCTION__ . "=> {$entity->getTitle()} 생성을 완료하였습니다."); - return $entity; - } -} diff --git a/app/Libraries/MyStorage/Cloudflare/AuthStorage.php b/app/Libraries/MyStorage/Cloudflare/AuthStorage.php deleted file mode 100644 index f789ae6..0000000 --- a/app/Libraries/MyStorage/Cloudflare/AuthStorage.php +++ /dev/null @@ -1,50 +0,0 @@ -_accountModel === null) { - $this->_accountModel = new AuthModel(); - } - return $this->_accountModel; - } - - final public function create_process($result, array $formDatas): AuthEntity - { - //Result 형태 - // [ - // {"id":"078e88a7735965b661715af13031ecb0", - // "name":"Cloudwin002@idcjp.jp's Auth", - // "type":"standard", - // "settings":{ - // "enforce_twofactor":false, - // "api_access_enabled":null, - // "access_approval_expiry":null, - // "use_account_custom_ns_by_default":false - // }, - // "legacy_flags":{"enterprise_zone_quota":{"maximum":0,"current":0,"available":0}}, - // "created_on":"2017-06-26T05:44:49.470184Z"} - // ] - $formDatas[$this->getAuthModel()->PK()] = $result->id; - $formDatas[$this->getAuthModel()->getTitleField()] = $result->name; - $formDatas['type'] = $result->type; - $formDatas['status'] = 'use'; - $formDatas['updated_at'] = $result->created_on; - $formDatas['created_at'] = $result->created_on; - $entity = $this->getAuthModel()->create($formDatas); - log_message("notice", __FUNCTION__ . "=> {$entity->getTitle()} 생성을 완료하였습니다."); - return $entity; - } -} diff --git a/app/Models/Cloudflare/AccountModel.php b/app/Models/Cloudflare/AccountModel.php index e89bbcd..4bcf764 100644 --- a/app/Models/Cloudflare/AccountModel.php +++ b/app/Models/Cloudflare/AccountModel.php @@ -12,18 +12,23 @@ class AccountModel extends Model protected $primaryKey = 'uid'; protected $useAutoIncrement = false; protected $returnType = AccountEntity::class; //object,array,entity명::class - protected $allowedFields = ['uid', 'auth_uid', 'title', 'type', 'status', 'updated_at', 'created_at']; + protected $allowedFields = ['uid', 'id', 'apikey', 'oldkey', 'type', 'status', 'updated_at', 'created_at']; protected $useTimestamps = true; public function getTitleField(): string { - return 'title'; + return 'id'; } public function getFieldRule(string $field, array $rules): array { switch ($field) { - case "auth_uid": + case "id": + $rules[$field] = "required|valid_emailvalid_email|is_unique[cloudflareauth.id]"; + case "apikey": $rules[$field] = $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] = $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}/]";; + break; case "type": $rules[$field] = "if_exist|trim|string"; break; diff --git a/app/Models/Cloudflare/AuthModel.php b/app/Models/Cloudflare/AuthModel.php deleted file mode 100644 index 14dfdc9..0000000 --- a/app/Models/Cloudflare/AuthModel.php +++ /dev/null @@ -1,63 +0,0 @@ -where($this->getPKField(), $uid); - return $this->getEntity(); - } - public function getEntityByID(string $id): null | AuthEntity - { - $this->where($this->getTitleField(), $id); - return $this->getEntity(); - } - - //create용 - public function create(array $formDatas = []): AuthEntity - { - $formDatas['oldkey'] = $formDatas['authkey']; - return $this->create_process(new AuthEntity(), $formDatas); - } - //modify용 - public function modify(AuthEntity $entity, array $formDatas): AuthEntity - { - //입력후 authkey값을 oldkey값에 넣어주기 위함 - $formDatas['oldkey'] = $entity->authkey; - return $this->modify_process($entity, $formDatas); - } -} diff --git a/app/Models/Cloudflare/ZoneModel.php b/app/Models/Cloudflare/ZoneModel.php index 431705c..1e6865a 100644 --- a/app/Models/Cloudflare/ZoneModel.php +++ b/app/Models/Cloudflare/ZoneModel.php @@ -1,94 +1,65 @@ 'if_exist|min_length[10]|max_length[200]', - 'account_uid' => 'if_exist|min_length[10]|max_length[200]', - 'domain' => 'if_exist|string', - 'name_servers' => 'if_exist|string', - 'plan' => 'if_exist|string', - 'development_mode' => 'if_exist|in_list[on,off]', - 'ipv6' => 'if_exist|in_list[on,off]', - 'security_level' => 'if_exist|string', - 'status' => 'if_exist|string', - 'updated_at' => 'if_exist|valid_date', - 'created_at' => 'if_exist|valid_date', - ]; - // 'security_level' => 'if_exist|in_list[essentially_off,low,medium,under_attack]', - // 'status' => 'if_exist|in_list[active,pending]', - protected $validationMessages = []; - protected $skipValidation = true; - protected $cleanValidationRules = true; - - // Callbacks - protected $allowCallbacks = true; - protected $beforeInsert = []; - protected $afterInsert = []; - protected $beforeUpdate = []; - protected $afterUpdate = []; - protected $beforeFind = []; - protected $afterFind = []; - protected $beforeDelete = []; - protected $afterDelete = []; - - public function getTableName() + const TITLE_FIELD = "id"; + const PARENT_FIELD = "account_uid"; + public function getFieldRule(string $field, array $rules): array { - return $this->table; - } - - public function getEntity(string $uid): ZoneEntity - { - $entity = $this->asObject(ZoneEntity::class)->where('uid', $uid)->first(); - if (is_null($entity)) { - throw new \Exception(__METHOD__ . "에서 {$uid} 해당 정보가 없습니다."); + switch ($field) { + case "account_uid": + $rules[$field] = $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 "domain": + case "plan": + $rules[$field] = "required|trim|string"; + break; + case "name_servers": + case "security_level": + $rules[$field] = "if_exist|trim|string"; + break; + case "development_mode": + case "ipv6": + $rules[$field] = "if_exist|in_list[on,off]"; + break; + default: + $rules = parent::getFieldRule($field, $rules); + break; } - return $entity; + return $rules; } - public function getEntitys(array $wheres) + public function getEntityByPK(int $uid): null | ZoneEntity { - return $this->asObject(ZoneEntity::class)->where($wheres)->findAll(); + $this->where($this->getPKField(), $uid); + return $this->getEntity(); + } + public function getEntityByID(string $id): null | ZoneEntity + { + $this->where($this->getTitleField(), $id); + return $this->getEntity(); } - //Index 검색용 - public function setIndexWordFilter(string $word) + //create용 + public function create(array $formDatas = []): ZoneEntity { - $subquery = $this->db->table('cloudflarerecord')->select('zone_uid')->like('content', $word, 'both'); - $this->like('domain', $word, 'both'); //befor , after , both - $this->orWhereIn('uid', $subquery); + return $this->create_process(new ZoneEntity(), $formDatas); } - public function setIndexDateFilter($start, $end) + //modify용 + public function modify(ZoneEntity $entity, array $formDatas): ZoneEntity { - $this->where('created_at >=', $start); - $this->where('created_at <=', $end); - } - public function setIndexOrderBy($field, $order = 'ASC') - { - $this->orderBy("domain ASC, {$field} {$order}"); + return $this->modify_process($entity, $formDatas); } //도메인이 이미 존재하는지 체크 @@ -98,4 +69,22 @@ class ZoneModel extends Model $this->where('domain', $domain); return is_null($this->first()) ? true : false; } + + //Index 검색용 + public function setIndexWordFilter(string $word) + { + $subquery = $this->db->table('cloudflarerecord')->select('zone_uid')->like('content', $word, 'both'); + $this->like('domain', $word, 'both'); //befor , after , both + $this->orWhereIn('uid', $subquery); + } + + public function setIndexDateFilter($start, $end) + { + $this->where('created_at >=', $start); + $this->where('created_at <=', $end); + } + public function setIndexOrderBy($field, $order = 'ASC') + { + $this->orderBy("domain ASC, {$field} {$order}"); + } }