From 265f8502da56570dd26eb6a3d2c799b9610a99b2 Mon Sep 17 00:00:00 2001 From: Guillaume ARNOUX Date: Sat, 20 Jan 2024 22:16:08 +0100 Subject: [PATCH] base init, login and test connection --- src/Mailcow.php | 119 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 src/Mailcow.php diff --git a/src/Mailcow.php b/src/Mailcow.php new file mode 100644 index 0000000..0a1e6a0 --- /dev/null +++ b/src/Mailcow.php @@ -0,0 +1,119 @@ + 'Mailcow', + 'form' => [ + 'credentials' => [ + 'fields' => [ + [ + 'name' => 'accesshash', + 'type' => 'text', + 'label' => 'API Key', + 'placeholder' => 'API Key to authenticate Mailcow service', + 'required' => true, + ], + ], + ], + ], + ]; + } + + /** + * Returns link to account management page. + * + * @return string + */ + public function getLoginUrl(Server_Account $account = null) + { + return 'https://' . $this->_config['host'] . '/'; + } + + /** + * Returns link to reseller account management. + * + * @return string + */ + public function getResellerLoginUrl(Server_Account $account = null) + { + return $this->getLoginUrl(); + } + + private function _makeRequest($type, $path, $params = []) + { + $host = 'https://' . $this->_config['host'] . '/api/v1/'; + + // Server credentials + $headers['X-API-Key'] = $this->_config['accesshash']; + + // Send POST query + $client = $this->getHttpClient()->withOptions([ + 'verify_peer' => false, + 'verify_host' => false, + 'timeout' => 10 + ]); + $response = $client->request($type, $host . $path, [ + 'headers' => $headers, + 'body' => $params != [] ? $params : null + ]); + $result = $response->getContent(); + + if (str_contains($result, 'authentication failed')) { + throw new Server_Exception('Failed to connect to the :type: server. Please verify your credentials and configuration', [':type:' => 'Mailcow']); + } elseif (str_contains($result, 'error')) { + error_log("Mailcow returned error $result for the " . $params['cmd'] . 'command'); + } + + return $result; + } + + private function _getPackageName(Server_Package $package) + { + $name = $package->getName(); + + return $name; + } + + /** + * This method is called to check if configuration is correct + * and class can connect to server. + * + * @return bool + */ + public function testConnection() + { + + // Make request and check sys info + $result = $this->_makeRequest('GET', 'get/status/version'); + if (str_contains($result, 'version')) { + return true; + } else { + throw new Server_Exception('Failed to connect to the :type: server. Please verify your credentials and configuration', [':type:' => 'Mailcow']); + } + + return true; + } + +}