Automation init...4

This commit is contained in:
최준흠 2024-09-21 11:33:14 +09:00
parent 269a1bd038
commit 854a064a23
17 changed files with 386 additions and 639 deletions

View File

@ -2,33 +2,33 @@
namespace App\Controllers\Cloudflare; namespace App\Controllers\Cloudflare;
use App\Entities\Cloudflare\AccountEntity; use App\Controllers\MVController;
use App\Libraries\MySocket\Cloudflare\AccountSocket;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface; 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\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; use AuthTrait;
private $_mySocket = null;
private $_model = null; private $_model = null;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{ {
parent::initController($request, $response, $logger); parent::initController($request, $response, $logger);
$this->session = $this->session_AccountTrait(); $this->session = $this->session_AuthTrait();
$this->class_name = 'Account'; $this->class_name = 'Account';
helper($this->class_name); helper($this->class_name);
} }
final protected function getMySocket(): AccountSocket
final protected function getMySocket(): CloudflareSocket
{ {
if ($this->_mySocket === null) { if ($this->_mySocket === null) {
$this->_mySocket = new AccountSocket($auth_uid); $this->_mySocket = new CloudflareSocket();
} }
return $this->_mySocket; return $this->_mySocket;
} }
@ -41,77 +41,46 @@ class AccountController extends MyCloudflare
return $this->_model; 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']; $this->filter_fields = ['status'];
parent::create_form_process(); $this->action = DB_ACTION["CREATE"];
$this->getModel()->setAction($this->action);
} }
public function create_form(): RedirectResponse|string public function create_form(): RedirectResponse|string
{ {
try { return $this->create_form_process();
$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): 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 = [ $this->getMySocket()->setAPIKey($this->formDatas['apikey']);
'name' => $name . "'s Account", $result = $this->getMySocket()->getAccount()->addAccount($this->formDatas['id']);
'type' => 'standard', $this->formDatas[$this->getModel()->PK()] = $result->id;
]; $this->formDatas[$this->getModel()->getTitleField()] = $result->name;
$result = $this->getClient()->post("accounts", $datas); $this->formDatas['type'] = $result->type;
$result = json_decode($result->getBody()); $this->formDatas['status'] = 'use';
if (!$result->success) { $this->formDatas['updated_at'] = $result->created_on;
throw new \Exception(var_export($result, true)); $this->formDatas['created_at'] = $result->created_on;
} return $this->getModel()->create($this->formDatas);
//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);
} }
public function create(): RedirectResponse public function create(): RedirectResponse
{ {
$this->getModel()->transStart(); return parent::create_process();
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();
}
} }
} }

View File

@ -1,52 +0,0 @@
<?php
namespace App\Controllers\Cloudflare\Admin;
use Psr\Log\LoggerInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\RequestInterface;
use App\Libraries\MyStorage\AccountStorage;
use App\Libraries\MySocket\Cloudflare\AccountSocket;
use App\Controllers\Cloudflare\MyCloudflare;
use App\Traits\AuthTrait;
class AccountController extends MyCloudflare
{
use AuthTrait;
private $_email = "";
private $_api_key = "";
private $_mySocket = null;
private $_myStorage = null;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
$this->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__ . "=> 작업을 완료하였습니다.");
}
}

View File

@ -1,79 +0,0 @@
<?php
namespace App\Controllers\Cloudflare\Admin;
use App\Controllers\CommonController;
use App\Entities\Cloudflare\AuthEntity;
use App\Models\Cloudflare\AuthModel;
use App\Traits\AuthTrait;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
class AuthController extends CommonController
{
use AuthTrait;
private $_model = null;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
$this->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();
}
}
}

View File

@ -1,22 +0,0 @@
<?php
namespace App\Controllers\Cloudflare;
use App\Controllers\CommonController;
use Psr\Log\LoggerInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\RequestInterface;
abstract class MyCloudflare extends CommonController
{
private $_email = "";
private $_api_key = "";
private $_mySocket = null;
private $_myStorage = null;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
}
abstract protected function getMySocket();
abstract protected function getMyStorage();
}

View File

@ -0,0 +1,86 @@
<?php
namespace App\Controllers\Cloudflare;
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\ZoneModel;
use App\Libraries\MySocket\CloudflareSocket;
use App\Entities\Cloudflare\ZoneEntity;
class ZoneController extends MVController
{
use AuthTrait;
private $_model = null;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
$this->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();
}
}

View File

@ -29,88 +29,4 @@ abstract class CommonController extends BaseController
{ {
return $this->_attributes; 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);
}
} }

View File

@ -0,0 +1,131 @@
<?php
namespace App\Controllers;
use Psr\Log\LoggerInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\RedirectResponse;
abstract class MVController extends CommonController
{
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
}
abstract protected function create_init(): void;
abstract protected function getModel(): mixed;
//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 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();
}
}
}

View File

@ -8,7 +8,7 @@ class AccountEntity extends CommonEntity
{ {
public function __toString() 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 public function getPK(): int
{ {
@ -16,15 +16,15 @@ class AccountEntity extends CommonEntity
} }
public function getTitle(): string public function getTitle(): string
{ {
return $this->attributes['email']; return $this->attributes['id'];
} }
public function setTitle(string $title): void public function setTitle(string $title): void
{ {
$this->attributes['email'] = $title; $this->attributes['id'] = $title;
} }
//Common Function //Common Function
public function getKey(): string public function getAPIKey(): string
{ {
return $this->attributes['key']; return $this->attributes['apikey'];
} }
} }

View File

@ -1,30 +0,0 @@
<?php
namespace App\Entities\Cloudflare;
use App\Entities\CommonEntity;
class AuthEntity extends CommonEntity
{
public function __toString()
{
return "{$this->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'];
}
}

View File

@ -1,27 +1,26 @@
<?php <?php
namespace App\Entities\Cloudflare\API; namespace App\Entities\Cloudflare;
class ZoneEntity extends APIEntity use App\Entities\CommonEntity;
class ZoneEntity extends CommonEntity
{ {
protected $datamap = []; public function __toString()
protected $dates = ['created_at', 'updated_at', 'deleted_at']; {
protected $casts = []; return "{$this->getPK()}|{$this->attributes['account_uid']}|{$this->getTitle()}|{$this->attributes['development_mode']}|{$this->attributes['ipv6']}|{$this->attributes['security_level']}";
}
public function getPrimaryKey() public function getPK(): int
{ {
return $this->attributes['uid']; 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']}"; $this->attributes['id'] = $title;
}
public function getParentField(): string
{
return "account_uid";
} }
//Common Function
} }

View File

@ -1,27 +0,0 @@
<?php
namespace App\Libraries\MySocket\Cloudflare;
use App\Libraries\MySocket\CloudflareSocket;
class AccountSocket extends CloudflareSocket
{
public function __construct()
{
parent::__construct();
}
final public function create_process(string $name, string $type = "standard")
{
$datas = [
'name' => $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;
}
}

View File

@ -4,8 +4,11 @@ namespace App\Libraries\MySocket;
use App\Libraries\CommonLibrary; use App\Libraries\CommonLibrary;
use App\Models\Cloudflare\AccountModel; use App\Models\Cloudflare\AccountModel;
use Cloudflare\API\Adapter\Guzzle;
use Cloudflare\API\Auth\APIKey; 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 class CloudflareSocket extends CommonLibrary
{ {
@ -14,15 +17,24 @@ class CloudflareSocket extends CommonLibrary
private static int $_request_timewait = 60; private static int $_request_timewait = 60;
private $_accountModel = null; private $_accountModel = null;
private $_clients = []; private $_clients = [];
private $_auth_uid = ""; protected $_apikey = "";
public function __construct(string $auth_uid) public function __construct()
{ {
parent::__construct(); parent::__construct();
$this->initClients(); $this->initAdapters();
$this->_auth_uid = $auth_uid;
self::$_request_max = getenv("cfmgr.request.max"); 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 final protected function getAccountModel(): AccountModel
{ {
if ($this->_accountModel === null) { if ($this->_accountModel === null) {
@ -30,19 +42,19 @@ class CloudflareSocket extends CommonLibrary
} }
return $this->_accountModel; return $this->_accountModel;
} }
final public function initClients(): void final public function initAdapters(): void
{ {
foreach ($this->getAccountModel()->getEntitys() as $entity) { foreach ($this->getAccountModel()->getEntitys() as $entity) {
$this->_clients[$entity->getKey()] = new Guzzle( $this->_clients[$entity->getAPIKey()] = new Guzzle(
new APIKey($entity->getTitle(), $entity->getKey()) new APIKey($entity->getTitle(), $entity->getAPIKey())
); );
} }
} }
final public function getClient(): Guzzle private function getAdapter(): Guzzle
{ {
if (!array_key_exists($this->_auth_uid, $this->_clients)) { if (!array_key_exists($this->getAPIKey(), $this->_clients)) {
throw new \Exception(+__FUNCTION__ . " => {$this->_auth_uid}에 해당하는 Adapter를 찾을수 없습니다."); throw new \Exception(+__FUNCTION__ . " => {$this->getAPIKey()}에 해당하는 Adapter를 찾을수 없습니다.");
} }
if (self::$_request >= self::$_request_max) { if (self::$_request >= self::$_request_max) {
log_message('warning', sprintf("--Cloudflare API Call %s초 대기 시작--", self::$_request_timewait)); 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)); log_message('warning', sprintf("--Cloudflare API Call %s초 대기 종료--", self::$_request_timewait));
} }
self::$_request++; 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());
} }
} }

View File

@ -1,50 +0,0 @@
<?php
namespace App\Libraries\MyStorage;
use App\Libraries\CommonLibrary;
use App\Entities\Cloudflare\AccountEntity;
use App\Models\Cloudflare\AccountModel;
class AccountStorage extends CommonLibrary
{
private $_accountModel = null;
public function __construct()
{
parent::__construct();
}
final protected function getAccountModel(): AccountModel
{
if ($this->_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;
}
}

View File

@ -1,50 +0,0 @@
<?php
namespace App\Libraries\MyStorage;
use App\Libraries\CommonLibrary;
use App\Entities\Cloudflare\AuthEntity;
use App\Models\Cloudflare\AuthModel;
class AuthStorage extends CommonLibrary
{
private $_accountModel = null;
public function __construct()
{
parent::__construct();
}
final protected function getAuthModel(): AuthModel
{
if ($this->_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;
}
}

View File

@ -12,18 +12,23 @@ class AccountModel extends Model
protected $primaryKey = 'uid'; protected $primaryKey = 'uid';
protected $useAutoIncrement = false; protected $useAutoIncrement = false;
protected $returnType = AccountEntity::class; //object,array,entity명::class 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; protected $useTimestamps = true;
public function getTitleField(): string public function getTitleField(): string
{ {
return 'title'; return 'id';
} }
public function getFieldRule(string $field, array $rules): array public function getFieldRule(string $field, array $rules): array
{ {
switch ($field) { 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}/]";; $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; 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": case "type":
$rules[$field] = "if_exist|trim|string"; $rules[$field] = "if_exist|trim|string";
break; break;

View File

@ -1,63 +0,0 @@
<?php
namespace App\Models\Cloudflare;
use App\Entities\Cloudflare\AuthEntity;
use CodeIgniter\Model;
use stdClass;
class AuthModel extends Model
{
protected $table = 'cloudflareauth';
protected $primaryKey = 'uid';
protected $useAutoIncrement = true;
protected $returnType = AuthEntity::class; //object,array,entity명::class
protected $allowedFields = ['uid', 'id', 'authkey', 'oldkey', 'status', 'updated_at', 'created_at'];
protected $useTimestamps = true;
public function getTitleField(): string
{
return 'id';
}
public function getFieldRule(string $field, array $rules): array
{
switch ($field) {
case "id":
$rules[$field] = "required|valid_emailvalid_email|is_unique[cloudflareauth.id]";
break;
case "authkey":
$rules[$field] = "required|trim|smin_length[10]|max_length[200]";
break;
case "oldkey":
$rules[$field] = "if_exist|trim|smin_length[10]|max_length[200]";
break;
default:
$rules = parent::getFieldRule($field, $rules);
break;
}
return $rules;
}
public function getEntityByPK(int $uid): null | AuthEntity
{
$this->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);
}
}

View File

@ -1,94 +1,65 @@
<?php <?php
namespace App\Models\Cloudflare\API; namespace App\Models\Cloudflare;
use App\Entities\Cloudflare\API\ZoneEntity; use App\Entities\Cloudflare\ZoneEntity;
use CodeIgniter\Model; use CodeIgniter\Model;
use stdClass;
class ZoneModel extends Model class ZoneModel extends Model
{ {
const PARENT_FIELD = "account_uid";
protected $DBGroup = 'default';
protected $table = 'cloudflarezone'; protected $table = 'cloudflarezone';
protected $primaryKey = 'uid'; protected $primaryKey = 'uid';
protected $useAutoIncrement = false; protected $useAutoIncrement = false;
protected $insertID = 0; protected $returnType = ZoneEntity::class; //object,array,entity명::class
protected $returnType = 'array'; //object,array,entity명::class protected $allowedFields = ['uid', 'account_uid', 'uid', 'domain', 'name_servers', 'original_name_servers', 'plan', 'development_mode', 'ipv6', 'security_level', 'status', 'updated_at', 'crated_at '];
protected $useSoftDeletes = false;
protected $protectFields = true;
protected $allowedFields = ['uid', 'account_uid', 'uid', 'domain', 'name_servers', 'original_name_servers', 'plan', 'development_mode', 'ipv6', 'security_level', 'status', 'updated_at', 'crated_at'];
// Dates
protected $useTimestamps = true; protected $useTimestamps = true;
protected $dateFormat = 'datetime'; const TITLE_FIELD = "id";
protected $createdField = 'created_at'; const PARENT_FIELD = "account_uid";
protected $updatedField = 'updated_at'; public function getFieldRule(string $field, array $rules): array
protected $deletedField = 'deleted_at';
// Validation
protected $validationRules = [
'uid' => '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()
{ {
return $this->table; 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}/]";;
public function getEntity(string $uid): ZoneEntity break;
{ case "domain":
$entity = $this->asObject(ZoneEntity::class)->where('uid', $uid)->first(); case "plan":
if (is_null($entity)) { $rules[$field] = "required|trim|string";
throw new \Exception(__METHOD__ . "에서 {$uid} 해당 정보가 없습니다."); 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 검색용 //create
public function setIndexWordFilter(string $word) public function create(array $formDatas = []): ZoneEntity
{ {
$subquery = $this->db->table('cloudflarerecord')->select('zone_uid')->like('content', $word, 'both'); return $this->create_process(new ZoneEntity(), $formDatas);
$this->like('domain', $word, 'both'); //befor , after , both
$this->orWhereIn('uid', $subquery);
} }
public function setIndexDateFilter($start, $end) //modify용
public function modify(ZoneEntity $entity, array $formDatas): ZoneEntity
{ {
$this->where('created_at >=', $start); return $this->modify_process($entity, $formDatas);
$this->where('created_at <=', $end);
}
public function setIndexOrderBy($field, $order = 'ASC')
{
$this->orderBy("domain ASC, {$field} {$order}");
} }
//도메인이 이미 존재하는지 체크 //도메인이 이미 존재하는지 체크
@ -98,4 +69,22 @@ class ZoneModel extends Model
$this->where('domain', $domain); $this->where('domain', $domain);
return is_null($this->first()) ? true : false; 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}");
}
} }