Skip to content

Commit

Permalink
Merge pull request #12 from Ecomailcz/auth-token2
Browse files Browse the repository at this point in the history
Support authorization token
  • Loading branch information
pekral committed Aug 18, 2018
2 parents c497b84 + d79879a commit 9f5bb73
Show file tree
Hide file tree
Showing 5 changed files with 121 additions and 13 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ $enableSelfSignedCertificate
);
```

## Vygenerování autorizačního tokenu
```
$client = new Client('https://demo.flexibee.eu', 'demo', 'winstrom', 'winstrom', 'adresar');
$tokens = $client->getAuthAndRefreshToken();
```

## Vytvoření či editace záznamu
```
$client = new Client('https://demo.flexibee.eu', 'demo', 'winstrom', 'winstrom', 'adresar');
Expand Down
78 changes: 65 additions & 13 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace EcomailFlexibee;

use Consistence\ObjectPrototype;
use EcomailFlexibee\Exception\EcomailFlexibeeAnotherError;
use EcomailFlexibee\Exception\EcomailFlexibeeInvalidAuthorization;
use EcomailFlexibee\Exception\EcomailFlexibeeNoEvidenceResult;
use EcomailFlexibee\Exception\EcomailFlexibeeRequestError;
Expand Down Expand Up @@ -46,13 +47,39 @@ class Client extends ObjectPrototype
*/
private $queryBuilder;

public function __construct(string $url, string $company, string $user, string $password, string $evidence, bool $selfSignedCertificate = false)
/**
* @var null|string
*/
private $authSessionId;

public function __construct(string $url, string $company, string $user, string $password, string $evidence, bool $selfSignedCertificate = false, ?string $authSessionId = null)
{
$this->user = $user;
$this->password = $password;
$this->evidence = $evidence;
$this->selfSignedCertificate = $selfSignedCertificate;
$this->queryBuilder = new QueryBuilder($company, $evidence, $url);
$this->authSessionId = $authSessionId;
}

/**
* @return string[]
* @throws \EcomailFlexibee\Exception\EcomailFlexibeeAnotherError
* @throws \EcomailFlexibee\Exception\EcomailFlexibeeInvalidAuthorization
* @throws \EcomailFlexibee\Exception\EcomailFlexibeeNoEvidenceResult
* @throws \EcomailFlexibee\Exception\EcomailFlexibeeRequestError
*/
public function getAuthAndRefreshToken(): array
{
$headers = [
'Content-Type: application/x-www-form-urlencoded',
];
$queryParameters['username'] = $this->user;
$queryParameters['password'] = $this->password;
$result = $this->makeRequest(Method::get(Method::POST), $this->queryBuilder->createAuthTokenUrl(), [], $headers, $queryParameters);
unset($result['success']);

return $result;
}

public function deleteById(int $id): void
Expand Down Expand Up @@ -188,44 +215,61 @@ public function getPdfById(int $id, array $queryParams = []): string
* @param \EcomailFlexibee\Http\Method $httpMethod
* @param string $url
* @param mixed[] $postFields
* @param string[] $headers
* @param string[] $queryParameters
* @return mixed[]
* @throws \EcomailFlexibee\Exception\EcomailFlexibeeAnotherError
* @throws \EcomailFlexibee\Exception\EcomailFlexibeeInvalidAuthorization
* @throws \EcomailFlexibee\Exception\EcomailFlexibeeNoEvidenceResult
* @throws \EcomailFlexibee\Exception\EcomailFlexibeeRequestError
*/
public function makeRequest(Method $httpMethod, string $url, array $postFields): array
public function makeRequest(Method $httpMethod, string $url, array $postFields = [], array $headers = [], array $queryParameters = []): array
{
/** @var resource $ch */
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPAUTH, TRUE);
curl_setopt($ch, CURLOPT_USERPWD, sprintf('%s:%s', $this->user, $this->password));
if ($this->authSessionId !== null) {
curl_setopt($ch, CURLOPT_HTTPAUTH, FALSE);
$headers[] = sprintf('X-authSessionId: %s', $this->authSessionId);
} else {
curl_setopt($ch, CURLOPT_HTTPAUTH, TRUE);
curl_setopt($ch, CURLOPT_USERPWD, sprintf('%s:%s', $this->user, $this->password));
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $httpMethod->getValue());
curl_setopt($ch, CURLOPT_USERAGENT, 'Ecomail.cz Flexibee client (https://github.com/Ecomailcz/flexibee-client)');

if ($this->selfSignedCertificate) {

if ($this->selfSignedCertificate || $this->authSessionId !== null) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
}

$postData = [];
if (count($postFields) !== 0) {
$postData['winstrom'] = $postFields;
(json_encode($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/xmln',
));
}

if (count($queryParameters) !== 0) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($queryParameters));
}

if (count($headers) !== 0) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}

$output = curl_exec($ch);
$result = null;

if (mb_strpos($url, '.pdf') !== false) {
return ['result' => $output];
}

if (is_string($output)) {
$result = json_decode($output, true)['winstrom'];
if (is_string($output) && !$httpMethod->equalsValue(Method::DELETE)) {
$resultData = json_decode($output, true);
$result = array_key_exists('winstrom', $resultData) ? $resultData['winstrom'] : $resultData;
}

if (curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200 && curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 201) {
Expand Down Expand Up @@ -253,12 +297,20 @@ public function makeRequest(Method $httpMethod, string $url, array $postFields):
return [];
}

if (array_key_exists('success', $result) && !$result['success']) {
throw new EcomailFlexibeeAnotherError($result);
}

if (isset($result['results'])) {
return $result['results'];
}

unset($result['@version']);
return array_values($result)[0];
if (isset($result['@version'])) {
unset($result['@version']);
return array_values($result)[0];
}

return $result;
}

}
23 changes: 23 additions & 0 deletions src/Exception/EcomailFlexibeeAnotherError.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php declare(strict_types = 1);

namespace EcomailFlexibee\Exception;

use Consistence\PhpException;
use Throwable;

class EcomailFlexibeeAnotherError extends PhpException
{

/**
* EcomailFlexibeeAnotherError constructor.
*
* @param mixed[] $responseData
* @param null|\Throwable $previous
*/
public function __construct(array $responseData, ?Throwable $previous = null)
{
$jsonData = json_encode($responseData, JSON_UNESCAPED_UNICODE);
parent::__construct(is_string($jsonData) ? $jsonData : '', $previous);
}

}
7 changes: 7 additions & 0 deletions src/Http/QueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ public function __construct(string $company, string $evidence, string $host, ?Pa
$this->evidence = $evidence;
}

public function createAuthTokenUrl(): string
{
$this->setPath(new Path('/login-logout/login.json'));

return $this->getUrl();
}

/**
* @param int $id
* @param mixed[] $queryParams
Expand Down
20 changes: 20 additions & 0 deletions tests/ClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,26 @@ public function setUp(): void
$this->client = new Client(Config::HOST, Config::COMPANY, Config::USERNAME, Config::PASSWORD, Config::EVIDENCE);
}

public function testGetAuthToken(): void
{
$authToken = $this->client->getAuthAndRefreshToken();
$this->assertCount(2, $authToken);
$this->assertArrayHasKey('refreshToken', $authToken);
$this->assertArrayHasKey('authSessionId', $authToken);
$client = new Client(Config::HOST, Config::COMPANY, Config::USERNAME, Config::PASSWORD, Config::EVIDENCE,false, $authToken['authSessionId']);
$evidenceData = [
'nazev' => $this->faker->company,
];
$id = $client->save($evidenceData, null);
$code = $client->getById($id)['kod'];
$evidenceItem = $client->getByCustomId(sprintf('code:%s', $code));
$this->assertCount(1, $evidenceItem);
$this->assertEquals($id, (int) $evidenceItem[0]['id']);
$client->deleteByCustomId(sprintf('code:%s', $code));
$this->assertCount(0, $client->findByCustomId(sprintf('code:%s', $code)));

}

public function testCRUDForCustomIds(): void
{
$evidenceData = [
Expand Down

0 comments on commit 9f5bb73

Please sign in to comment.