1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-10 05:02:36 +01:00
invoiceninja/app/Services/Migration/AuthService.php

126 lines
2.7 KiB
PHP
Raw Normal View History

<?php
2020-12-10 15:04:59 +01:00
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2020. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://opensource.org/licenses/AAL
*/
namespace App\Services\Migration;
use Unirest\Request;
use Unirest\Request\Body;
class AuthService
{
protected $username;
protected $password;
2020-12-10 15:04:59 +01:00
protected $apiSecret;
protected $endpoint = 'https://app.invoiceninja.com';
protected $uri = '/api/v1/login?include=token';
2020-12-10 15:04:59 +01:00
protected $errors = [];
protected $token;
protected $isSuccessful;
2020-12-10 15:04:59 +01:00
public function __construct(string $username, string $password, string $apiSecret = null)
{
$this->username = $username;
$this->password = $password;
2020-12-10 15:04:59 +01:00
$this->apiSecret = $apiSecret;
}
public function endpoint(string $endpoint)
{
$this->endpoint = $endpoint;
return $this;
}
public function start()
{
$data = [
'email' => $this->username,
'password' => $this->password,
];
$body = Body::json($data);
2021-03-26 14:14:08 +01:00
$response = Request::post($this->getUrl(), $this->getHeaders(), $body);
2021-03-26 14:14:08 +01:00
if (in_array($response->code, [401])) {
info($response->raw_body);
$this->isSuccessful = false;
$this->processErrors($response->body->message);
} elseif (in_array($response->code, [200])) {
2020-11-12 11:04:50 +01:00
$this->isSuccessful = true;
$this->token = $response->body->data[0]->token->token;
2021-03-26 14:14:08 +01:00
} else {
info($response->raw_body);
$this->isSuccessful = false;
2020-11-12 11:04:50 +01:00
$this->errors = [trans('texts.migration_went_wrong')];
}
return $this;
}
public function isSuccessful()
{
return $this->isSuccessful;
}
public function getAccountToken()
{
if ($this->isSuccessful) {
return $this->token;
}
return null;
}
2020-12-10 15:04:59 +01:00
public function getApiSecret()
{
return $this->apiSecret;
}
public function getErrors()
{
return $this->errors;
}
private function getHeaders()
{
2020-12-10 15:04:59 +01:00
$headers = [
'X-Requested-With' => 'XMLHttpRequest',
'Content-Type' => 'application/json',
];
2020-12-10 15:04:59 +01:00
if (!is_null($this->apiSecret)) {
$headers['X-Api-Secret'] = $this->apiSecret;
}
return $headers;
}
private function getUrl()
{
return $this->endpoint . $this->uri;
}
private function processErrors($errors)
{
2021-03-26 14:14:08 +01:00
$array = (array)$errors;
$this->errors = $array;
}
}