63 lines
1.7 KiB
PHP
63 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use Illuminate\Support\Facades\Http;
|
|
use Illuminate\Support\Facades\Cache;
|
|
use Exception;
|
|
|
|
class AdminService
|
|
{
|
|
private $baseUrl;
|
|
private $username;
|
|
private $password;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->baseUrl = env('THINGSBOARD_URL', 'http://65.0.131.117:8080');
|
|
$this->username = env('THINGSBOARD_USERNAME', 'tenant1@thingsboard.org');
|
|
$this->password = env('THINGSBOARD_PASSWORD', 'tenant1');
|
|
}
|
|
|
|
public function getToken()
|
|
{
|
|
if (Cache::has('thingsboard_token')) {
|
|
return Cache::get('thingsboard_token');
|
|
}
|
|
|
|
$response = Http::withHeaders([
|
|
'accept' => 'application/json',
|
|
'Content-Type' => 'application/json',
|
|
])->post("{$this->baseUrl}/api/auth/login", [
|
|
'username' => $this->username,
|
|
'password' => $this->password,
|
|
]);
|
|
|
|
if ($response->successful()) {
|
|
$token = $response->json('token');
|
|
Cache::put('thingsboard_token', $token, now()->addMinutes(15));
|
|
return $token;
|
|
} else {
|
|
throw new Exception('Unable to authenticate with ThingsBoard: ' . $response->body());
|
|
}
|
|
}
|
|
|
|
public function createUser(array $data)
|
|
{
|
|
$token = $this->getToken();
|
|
|
|
|
|
$response = Http::withHeaders([
|
|
'Authorization' => "Bearer $token",
|
|
'accept' => 'application/json',
|
|
'Content-Type' => 'application/json',
|
|
])->post(env('THINGSBOARD_CREATE_USER_URL'), $data);
|
|
|
|
if ($response->successful()) {
|
|
return $response->json();
|
|
} else {
|
|
throw new Exception('Failed to create user: ' . $response->body());
|
|
}
|
|
}
|
|
}
|