vpn.keks.cloud/app/Console/Commands/ImportDevices.php

79 lines
2.0 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Models\User;
use App\Models\VPN;
use App\Models\VPNAccess;
use App\Services\WGRest;
use Illuminate\Console\Command;
class ImportDevices extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'wgrest:import-devices';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Get All Devices from WGREST server and add to db';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @param WGRest $wgrest
* @return int
*/
public function handle(WGRest $wgrest)
{
$res = $wgrest->listDevices();
foreach($res as $network) {
$setAdmins = false;
$this->info("Update Device: ".$network["name"]);
$vpn = VPN::query()->where("name", "=", $network["name"])->first();
if(is_null($vpn)) {
$this->info("Create New Device: ".$network["name"]);
$vpn = new VPN();
$vpn->displayName = $network["name"];
$setAdmins = true;
}
$vpn->name = $network["name"];
$vpn->listen_port = $network["listen_port"];
$vpn->network = $network["network"];
$vpn->private_key = $network["private_key"];
$vpn->public_key = $network["public_key"];
$vpn->saveOrFail();
if($setAdmins) {
$admins = User::findAdmins();
foreach($admins as $admin) {
$access = new VPNAccess();
$access->user_id = $admin->id;
$access->vpn_id = $vpn->id;
$access->status = "Admin";
$access->saveOrFail();
}
}
}
return 0;
}
}