diff --git a/.gitignore b/.gitignore index a725465aee245635a2bd129af54858ed32c84cb8..42cd73d9573dd58ecae4b5a923698274ced492aa 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1 @@ -vendor/ \ No newline at end of file +/vendor/ \ No newline at end of file diff --git a/api/apis/Auth/current.php b/api/apis/auth/current.php similarity index 100% rename from api/apis/Auth/current.php rename to api/apis/auth/current.php diff --git a/api/apis/Auth/login.php b/api/apis/auth/login.php similarity index 100% rename from api/apis/Auth/login.php rename to api/apis/auth/login.php diff --git a/api/apis/Auth/refreshtoken.php b/api/apis/auth/refreshtoken.php similarity index 100% rename from api/apis/Auth/refreshtoken.php rename to api/apis/auth/refreshtoken.php diff --git a/api/apis/Auth/signup.php b/api/apis/auth/signup.php similarity index 100% rename from api/apis/Auth/signup.php rename to api/apis/auth/signup.php diff --git a/api/apis/wg/addpeer.php b/api/apis/wg/addpeer.php index 8292d8ebf79dbe344397bffbac59cb3eaa21efc3..92874f57a1ec3cb51d17f25eead73a078a51e96b 100644 --- a/api/apis/wg/addpeer.php +++ b/api/apis/wg/addpeer.php @@ -6,12 +6,13 @@ ${basename(__FILE__, '.php')} = function () { and $this->isAuthenticated() and isset($this->_request['peer']) and !empty($this->_request['peer']) + and isset($this->_request['email']) + and !empty($this->_request['email']) ) { try { $wg = new wireguard('wg0'); - $ip_net = new ipNetwork($wg->getCIDR(),$wg->device); $data = [ - "data" => $wg->addPeer($this->_request['peer'],$ip_net->getNextIp()) + "result" => $wg->addPeer($this->_request['peer'],$this->_request['email']) ]; $data = $this->json($data); $this->response($data, 200); diff --git a/api/lib/User.class.php b/api/lib/User.class.php index 0c04f5b08135c75fb1c6a1ec8efce58b4b6448c3..97d54b7e1711041309315bb8079fbd643c3aa62e 100644 --- a/api/lib/User.class.php +++ b/api/lib/User.class.php @@ -5,38 +5,26 @@ include_once ($_SERVER['DOCUMENT_ROOT'].'/api/lib/database.class.php'); class User { private $db; - private $user; + private $data; + private $collection; public function __construct($username) { - $query = "SELECT * FROM `auth` WHERE `username` = '$username' OR `email` = '$username';"; - $this->db = database::getconnection(); - $result = $this->db->query($query); - - if($result->num_rows > 0) - { - $this->user = $result->fetch_assoc(); - } - else + $this->db = Database::getConnection(); + $this->collection = $this->db->auth; + $this->data = $this->collection->findOne([ + '$or' => [ + ['username' => $username], + ['email' => $username] + ] + ]); + + if($this->data == null) { - throw new Exception("User not found"); + throw new Exception ("User not found"); } + } - public function getUsername(){ - return $this->user['username']; - } - - public function getPasswordHash(){ - return $this->user['password']; - } - - public function getEmail(){ - return $this->user['email']; - } - - public function isActive(){ - return $this->user['active']; - } } \ No newline at end of file diff --git a/api/lib/database.class.php b/api/lib/database.class.php index f5c2debb8871160f3b60d68b5bcd0c758daaadca..35428bacc105da11a03b4fc6ebab03dc64c999d2 100644 --- a/api/lib/database.class.php +++ b/api/lib/database.class.php @@ -2,68 +2,29 @@ require_once __DIR__ . '/../../vendor/autoload.php'; -class database +class Database { - public static $conn = null; - public $mongoClient; - - public function __construct() + private static $db = null; + /** + * @return MongoDB\Database + */ + public static function getConnection() { - if(!extension_loaded('mongodb')){ - die("Extension not loaded properly"); + if (Database::$db == null) { + $client = new MongoDB\Client("mongodb://localhost:27017"); + Database::$db = $client->vpn; + if(Database::$db == null){ + throw new Exception("Failed to connect to the database"); + } + } else { + return Database::$db; } - $this->mongoClient = new MongoDB\Client("mongodb://127.0.0.1:27017"); - - if(!$this->mongoClient){ - http_response_code(500); - die('Cannot connect to database'); - } + return Database::$db; } - public function getMongodb($db){ - return $this->mongoClient->$db; - } - - static function getconnection() + public static function getArray($val) { - - $config_path = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/../env.json'); - $get_config = json_decode($config_path,true); - - - try{ - if(database::$conn==null) - { - $servername = $get_config["server"]; - $username = $get_config["username"]; - $password = $get_config["password"]; - $dbname = $get_config["database"]; - - // Create connection - $conn = new mysqli($servername, $username, $password, $dbname); - // Check connection - if ($conn->connect_error) { - throw new Exception("Connection failed: " . $conn->connect_error); - }else{ - database::$conn = $conn; - // echo "establishing new connection\n"; - return database::$conn; - } - }else{ - // echo "establishing existing connection\n"; - return database::$conn; + return json_decode(json_encode($val), true); } } -catch(Exception $e) -{ - echo "Exception Caugh : ".$e->getMessage(); -} - } - - - public function getArray($doc) - { - return json_decode(json_encode($doc),true); - } -} \ No newline at end of file diff --git a/api/lib/ipnetworks.class.php b/api/lib/ipnetworks.class.php index b7532ca88126df6db96ce993636f09b8f4a35775..555604825f4dcab6b83d56e9b087bfec08f7393b 100644 --- a/api/lib/ipnetworks.class.php +++ b/api/lib/ipnetworks.class.php @@ -8,7 +8,7 @@ class ipNetwork public $networks = null; public $wgdevice; - public function __construct($cidr,$wgdevice) + public function __construct($cidr, $wgdevice) { $this->cidr = $cidr; $this->wgdevice = $wgdevice; @@ -19,12 +19,12 @@ class ipNetwork public function getNetwork() { - if (!$this->networks) { - $val = $this->collection->findOne([ - 'cidr' => $this->cidr - ]); - return $this->db->getArray($val); - } else { + if(!$this->networks){ + $filter = ['cidr' => $this->cidr, 'wgdevice' => $this->wgdevice]; + $this->networks = $this->collection->findOne($filter); + $this->db->getArray($this->networks); + return $this->networks; + }else{ return $this->networks; } } @@ -93,24 +93,49 @@ class ipNetwork return $val['ip_addr']; } - public function allocateIp($ip, $owner, $publickey, $privatekey) + public function allocateIp($ip, $owner, $publickey) { - $this->collection->updateOne([ - 'ip_addr' => $ip, - 'wgdevice' => $this->wgdevice - ], [ - '$set' => [ - 'allocated' => true, - 'owner' => $owner, - 'allocation_time' => time(), - 'public_key' => $publickey, - 'private_key' => $privatekey, - - ] - ]); + try { + $this->collection->updateOne([ + 'ip_addr' => $ip, + 'wgdevice' => $this->wgdevice + ], [ + '$set' => [ + 'allocated' => true, + 'owner' => $owner, + 'allocation_time' => time(), + 'public_key' => $publickey + + ] + ]); + return true; + } catch (Exception $e) { + return false; + } } //resume from here - allocate unique key only + public function deallocate($public) + { + try { + $this->collection->updateOne([ + 'public_key' => $public, + 'wgdevice' => $this->wgdevice + ], [ + '$set' => [ + 'allocated' => false, + 'owner' => "", + 'allocation_time' => "", + 'public_key' => "" + + ] + ]); + return true; + } catch (Exception $e) { + return false; + } + } + public function generateIdFromCidr() {} public function getIp($ip) {} //function stubs diff --git a/api/lib/signup.class.php b/api/lib/signup.class.php index e74903aeee9004d8f49df368730b7e540e84383e..d5829b969d1290ba049264724cf2a46357891da4 100644 --- a/api/lib/signup.class.php +++ b/api/lib/signup.class.php @@ -2,6 +2,7 @@ require_once($_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php'); use Mailgun\Mailgun; +use MongoDB\Collection; class signup { @@ -10,7 +11,9 @@ class signup private $email; public $userid; public $token; + private $db; + private $collection; function __construct($username, $password, $email) @@ -21,38 +24,33 @@ class signup $this->username = $username; $this->password = $password; $this->email = $email; - if ($this->userexits($username)) { - throw new Exception("user already exist"); - } - $query = "INSERT INTO `auth` (`username`, `password`, `email`, `active`,`token`) - VALUES ('$username', '$password', '$email', '0','$this->token');"; - - $this->db = database::getconnection(); - $result = $this->db->query($query); - - if (!$result) { - throw new Exception("Failed : " . $this->db->error); - } else { - $this->userid = $this->db->insert_id; - $this->sendVerificationMail(); - } - } - public function userexits($username) - { - $query = "SELECT `username`, `id` FROM `auth` WHERE `username` = '$username';"; + $this->db = Database::getConnection(); - $this->db = database::getconnection(); - $result = $this->db->query($query); + $this->collection = $this->db->auth; - if ($result->num_rows > 0) { - return true; + $exist = $this->collection->findOne(['username' => $username]); + if ($exist) { + throw new Exception("User already exists"); + } + $result = $this->collection->insertOne([ + 'username' => $username, + 'password' => $password, + 'email' => $email, + 'token' => $this->token, + 'active' => 0 + ]); + + if ($result->getInsertedCount() !== 1) { + throw new Exception("Error inserting user"); } else { - return false; + $this->userid = $result->getInsertedId(); } } + + function sendVerificationMail() { $config_json = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/../env.json'); @@ -139,16 +137,17 @@ class signup public static function verifyAccount($token) { - $query = "SELECT * FROM apis.auth WHERE token='$token';"; $db = Database::getConnection(); - $result = $db->query($query); - if ($result->num_rows > 0) { - $row = $result->fetch_assoc(); - if ($row['active'] == 1) { - throw new Exception("Already Verified"); - } - $query = "UPDATE `apis`.`auth` SET `active` = '1' WHERE (`token` = '$token');"; - $db->query($query); + $Collection = $db->auth; + + $result = $Collection->findOne(['token' => $token]); + if ($result['active'] == 1) { + return "Already Verified"; + } else { + $Collection->updateOne(['token' => $token], ['$set' => ['active' => 1]]); + return "Verified"; + } + if ($result->getModifiedCount() == 1) { return true; } else { return false; diff --git a/api/lib/wireguard.class.php b/api/lib/wireguard.class.php index 58b2383b7eab207e60c69761ee491e0d9fb52169..b9351239c3d74d0ffe6ecca79e04dc86a2c71333 100644 --- a/api/lib/wireguard.class.php +++ b/api/lib/wireguard.class.php @@ -25,9 +25,19 @@ class wireguard } - public function addpeer($public, $ip) // here to resume + public function addpeer($public, $email) { - $cmd = "sudo wg set $this->device peer $public allowed-ips $ip/32"; + $ip_net = new ipNetwork($this->getCIDR(),$this->device); + $next_ip = $ip_net->getNextIp(); + $result = null; + $cmd = "sudo wg set $this->device peer $public allowed-ips $next_ip/32"; + system($cmd,$result); + if($result == 0){ + $res = $ip_net->allocateIp($next_ip,$email,$public); + return $res; + }else{ + return false; + } } public function removepeer($public) @@ -35,7 +45,14 @@ class wireguard $cmd = "sudo wg set $this->device peer $public remove"; $result = 0; trim(system($cmd, $result)); - return $result == 0; + if($result == 0){ + $remove = new ipNetwork($this->getCIDR(),$this->device); + $remove->deallocate($public); + return true; + } + else{ + return false; + } } public function getPeers() diff --git a/test.php b/test.php index 7d8c51f5d23413fa400e516dad58e59320730888..a7b8dc90c968429fd9bc3bdaef3c79d111f5ed38 100644 --- a/test.php +++ b/test.php @@ -5,17 +5,13 @@ require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/database.class.php'); require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/ipnetworks.class.php'); require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/wireguard.class.php'); +require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/signup.class.php'); +require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/User.class.php'); + + +// $signup = new signup("sanjay","sanjay@123?","email2sanjay@gmail.com"); +$user = new User("sanay"); -try{ - $wg = new wireguard('wg0'); - $ip = new ipNetwork($wg->getCIDR(),$wg->device); - $ipp = $ip->getNextIp(); - print($ipp); - $ip->allocateIp($ipp,"sanjay","JIk4Oj2UdryKh2ssrwuOsyAJEJXeAYnLCjf6fyqEWlA=","+PEmIqALukuqyw7OyTUGKf1+YItTdoyQ0aD5TBpwzVU="); -}catch(Exception $e) -{ - echo "can't insert value bluk duplicate entry"; -} diff --git a/verify.php b/verify.php index e2ae45c0d456dda886bd20a531332050f85f2d8c..fcfee06cb2e0e38fb8f31c70416824df1a72cbb5 100644 --- a/verify.php +++ b/verify.php @@ -3,7 +3,7 @@ require_once $_SERVER['DOCUMENT_ROOT'].'/api/lib/signup.class.php'; require_once($_SERVER['DOCUMENT_ROOT']."/api/lib/database.class.php"); -$token = mysqli_real_escape_string(database::getConnection(), $_GET['token']); +$token = (string) $_GET['token']; try{ if(signup::verifyAccount($token)){ ?>