84 lines
2.3 KiB
PHP
84 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Models\Peer;
|
|
use App\Models\User;
|
|
use App\Models\VPN;
|
|
use App\Models\VPNAccess;
|
|
use App\Services\WGRest;
|
|
use Illuminate\Console\Command;
|
|
use IPTools\Network;
|
|
|
|
class ImportPeers extends Command
|
|
{
|
|
/**
|
|
* The name and signature of the console command.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $signature = 'wgrest:import-peers';
|
|
|
|
/**
|
|
* The console command description.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $description = 'Get All Peers for all Devices';
|
|
|
|
/**
|
|
* 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)
|
|
{
|
|
$vpns = VPN::query()->get();
|
|
foreach ($vpns as $vpn) {
|
|
$internalPeers = Peer::query()->where("vpn_id", "=", $vpn->id)->get();
|
|
$this->info("Import for ".$vpn->name);
|
|
$knownpeers=[];
|
|
foreach ($internalPeers as $p) {
|
|
$knownpeers[] = $p->public_key;
|
|
}
|
|
|
|
$peers = $wgrest->getPeers($vpn->name);
|
|
foreach ($peers as $peer) {
|
|
if(!in_array($peer["public_key"], $knownpeers)) {
|
|
$this->info("Import ".$peer["public_key"]);
|
|
$peerToSave = new Peer();
|
|
$peerToSave->name = "import";
|
|
$peerToSave->public_key = $peer["public_key"];
|
|
$peerToSave->allowed_ips = implode(",", $peer["allowed_ips"]);
|
|
if(isset($peer["preshared_key"])) {
|
|
$peerToSave->preshared_key = $peer["preshared_key"];
|
|
}
|
|
|
|
if(count($peer["allowed_ips"]) == 1) {
|
|
$n = Network::parse($peer["allowed_ips"][0]);
|
|
if((string)$n->getNetmask()=="255.255.255.255") {
|
|
$peerToSave->ip = (string)$n->getIP();
|
|
$peerToSave->allowed_ips = null;
|
|
}
|
|
}
|
|
|
|
$peerToSave->imported = true;
|
|
$peerToSave->vpn_id = $vpn->id;
|
|
$peerToSave->saveOrFail();
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|