2020-02-24 22:17:16 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Services\Migration;
|
|
|
|
|
|
|
|
use Unirest\Request;
|
|
|
|
use Unirest\Request\Body;
|
|
|
|
|
|
|
|
class AuthService
|
|
|
|
{
|
|
|
|
protected $username;
|
|
|
|
protected $password;
|
|
|
|
protected $endpoint = 'https://app.invoiceninja.com';
|
|
|
|
protected $uri = '/api/v1/login?include=token';
|
|
|
|
protected $errors = [];
|
|
|
|
protected $token;
|
|
|
|
protected $isSuccessful;
|
|
|
|
|
|
|
|
|
|
|
|
public function __construct(string $username, string $password)
|
|
|
|
{
|
|
|
|
$this->username = $username;
|
|
|
|
$this->password = $password;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function endpoint(string $endpoint)
|
|
|
|
{
|
|
|
|
$this->endpoint = $endpoint;
|
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function start()
|
|
|
|
{
|
|
|
|
$data = [
|
|
|
|
'email' => $this->username,
|
|
|
|
'password' => $this->password,
|
|
|
|
];
|
|
|
|
|
|
|
|
$body = Body::json($data);
|
|
|
|
|
2020-11-12 11:04:50 +01:00
|
|
|
try {
|
|
|
|
$response = Request::post($this->getUrl(), $this->getHeaders(), $body);
|
2020-02-24 22:17:16 +01:00
|
|
|
|
2020-11-12 11:04:50 +01:00
|
|
|
$this->isSuccessful = true;
|
|
|
|
$this->token = $response->body->data[0]->token->token;
|
2020-04-06 23:23:57 +02:00
|
|
|
|
2020-11-12 11:04:50 +01:00
|
|
|
if (in_array($response->code, [401, 422, 500])) {
|
2020-04-06 23:23:57 +02:00
|
|
|
$this->isSuccessful = false;
|
2020-11-12 11:04:50 +01:00
|
|
|
$this->processErrors($response->body);
|
2020-04-06 23:23:57 +02:00
|
|
|
}
|
2020-11-12 11:04:50 +01:00
|
|
|
} catch (\Exception $e) {
|
|
|
|
info($e->getMessage());
|
2020-02-24 22:17:16 +01:00
|
|
|
|
|
|
|
$this->isSuccessful = false;
|
2020-11-12 11:04:50 +01:00
|
|
|
$this->errors = [trans('texts.migration_went_wrong')];
|
2020-02-24 22:17:16 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function isSuccessful()
|
|
|
|
{
|
|
|
|
return $this->isSuccessful;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getAccountToken()
|
|
|
|
{
|
|
|
|
if ($this->isSuccessful) {
|
|
|
|
return $this->token;
|
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public function getErrors()
|
|
|
|
{
|
|
|
|
return $this->errors;
|
|
|
|
}
|
|
|
|
|
|
|
|
private function getHeaders()
|
|
|
|
{
|
|
|
|
return [
|
|
|
|
'X-Requested-With' => 'XMLHttpRequest',
|
|
|
|
'Content-Type' => 'application/json',
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
private function getUrl()
|
|
|
|
{
|
|
|
|
return $this->endpoint . $this->uri;
|
|
|
|
}
|
|
|
|
|
|
|
|
private function processErrors($errors)
|
|
|
|
{
|
|
|
|
$array = (array) $errors;
|
|
|
|
|
|
|
|
$this->errors = $array;
|
|
|
|
}
|
|
|
|
}
|