Skip to content
Snippets Groups Projects
Commit 364bb8b9 authored by root's avatar root
Browse files

converting mysql to mongodb (Wip)

parent c903c156
No related branches found
No related tags found
No related merge requests found
vendor/ /vendor/
\ No newline at end of file \ No newline at end of file
File moved
File moved
File moved
File moved
...@@ -6,12 +6,13 @@ ${basename(__FILE__, '.php')} = function () { ...@@ -6,12 +6,13 @@ ${basename(__FILE__, '.php')} = function () {
and $this->isAuthenticated() and $this->isAuthenticated()
and isset($this->_request['peer']) and isset($this->_request['peer'])
and !empty($this->_request['peer']) and !empty($this->_request['peer'])
and isset($this->_request['email'])
and !empty($this->_request['email'])
) { ) {
try { try {
$wg = new wireguard('wg0'); $wg = new wireguard('wg0');
$ip_net = new ipNetwork($wg->getCIDR(),$wg->device);
$data = [ $data = [
"data" => $wg->addPeer($this->_request['peer'],$ip_net->getNextIp()) "result" => $wg->addPeer($this->_request['peer'],$this->_request['email'])
]; ];
$data = $this->json($data); $data = $this->json($data);
$this->response($data, 200); $this->response($data, 200);
......
...@@ -5,38 +5,26 @@ include_once ($_SERVER['DOCUMENT_ROOT'].'/api/lib/database.class.php'); ...@@ -5,38 +5,26 @@ include_once ($_SERVER['DOCUMENT_ROOT'].'/api/lib/database.class.php');
class User class User
{ {
private $db; private $db;
private $user; private $data;
private $collection;
public function __construct($username) public function __construct($username)
{ {
$query = "SELECT * FROM `auth` WHERE `username` = '$username' OR `email` = '$username';"; $this->db = Database::getConnection();
$this->db = database::getconnection(); $this->collection = $this->db->auth;
$result = $this->db->query($query); $this->data = $this->collection->findOne([
'$or' => [
if($result->num_rows > 0) ['username' => $username],
{ ['email' => $username]
$this->user = $result->fetch_assoc(); ]
} ]);
else
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
...@@ -2,68 +2,29 @@ ...@@ -2,68 +2,29 @@
require_once __DIR__ . '/../../vendor/autoload.php'; require_once __DIR__ . '/../../vendor/autoload.php';
class database class Database
{ {
public static $conn = null; private static $db = null;
public $mongoClient; /**
* @return MongoDB\Database
public function __construct() */
public static function getConnection()
{ {
if(!extension_loaded('mongodb')){ if (Database::$db == null) {
die("Extension not loaded properly"); $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"); return Database::$db;
if(!$this->mongoClient){
http_response_code(500);
die('Cannot connect to database');
}
} }
public function getMongodb($db){ public static function getArray($val)
return $this->mongoClient->$db;
}
static function getconnection()
{ {
return json_decode(json_encode($val), true);
$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;
} }
} }
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
...@@ -8,7 +8,7 @@ class ipNetwork ...@@ -8,7 +8,7 @@ class ipNetwork
public $networks = null; public $networks = null;
public $wgdevice; public $wgdevice;
public function __construct($cidr,$wgdevice) public function __construct($cidr, $wgdevice)
{ {
$this->cidr = $cidr; $this->cidr = $cidr;
$this->wgdevice = $wgdevice; $this->wgdevice = $wgdevice;
...@@ -19,12 +19,12 @@ class ipNetwork ...@@ -19,12 +19,12 @@ class ipNetwork
public function getNetwork() public function getNetwork()
{ {
if (!$this->networks) { if(!$this->networks){
$val = $this->collection->findOne([ $filter = ['cidr' => $this->cidr, 'wgdevice' => $this->wgdevice];
'cidr' => $this->cidr $this->networks = $this->collection->findOne($filter);
]); $this->db->getArray($this->networks);
return $this->db->getArray($val); return $this->networks;
} else { }else{
return $this->networks; return $this->networks;
} }
} }
...@@ -93,24 +93,49 @@ class ipNetwork ...@@ -93,24 +93,49 @@ class ipNetwork
return $val['ip_addr']; return $val['ip_addr'];
} }
public function allocateIp($ip, $owner, $publickey, $privatekey) public function allocateIp($ip, $owner, $publickey)
{ {
$this->collection->updateOne([ try {
'ip_addr' => $ip, $this->collection->updateOne([
'wgdevice' => $this->wgdevice 'ip_addr' => $ip,
], [ 'wgdevice' => $this->wgdevice
'$set' => [ ], [
'allocated' => true, '$set' => [
'owner' => $owner, 'allocated' => true,
'allocation_time' => time(), 'owner' => $owner,
'public_key' => $publickey, 'allocation_time' => time(),
'private_key' => $privatekey, 'public_key' => $publickey
] ]
]); ]);
return true;
} catch (Exception $e) {
return false;
}
} }
//resume from here - allocate unique key only //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 generateIdFromCidr() {}
public function getIp($ip) {} //function stubs public function getIp($ip) {} //function stubs
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
require_once($_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php'); require_once($_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php');
use Mailgun\Mailgun; use Mailgun\Mailgun;
use MongoDB\Collection;
class signup class signup
{ {
...@@ -10,7 +11,9 @@ class signup ...@@ -10,7 +11,9 @@ class signup
private $email; private $email;
public $userid; public $userid;
public $token; public $token;
private $db; private $db;
private $collection;
function __construct($username, $password, $email) function __construct($username, $password, $email)
...@@ -21,38 +24,33 @@ class signup ...@@ -21,38 +24,33 @@ class signup
$this->username = $username; $this->username = $username;
$this->password = $password; $this->password = $password;
$this->email = $email; $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) $this->db = Database::getConnection();
{
$query = "SELECT `username`, `id` FROM `auth` WHERE `username` = '$username';";
$this->db = database::getconnection(); $this->collection = $this->db->auth;
$result = $this->db->query($query);
if ($result->num_rows > 0) { $exist = $this->collection->findOne(['username' => $username]);
return true; 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 { } else {
return false; $this->userid = $result->getInsertedId();
} }
} }
function sendVerificationMail() function sendVerificationMail()
{ {
$config_json = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/../env.json'); $config_json = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/../env.json');
...@@ -139,16 +137,17 @@ class signup ...@@ -139,16 +137,17 @@ class signup
public static function verifyAccount($token) public static function verifyAccount($token)
{ {
$query = "SELECT * FROM apis.auth WHERE token='$token';";
$db = Database::getConnection(); $db = Database::getConnection();
$result = $db->query($query); $Collection = $db->auth;
if ($result->num_rows > 0) {
$row = $result->fetch_assoc(); $result = $Collection->findOne(['token' => $token]);
if ($row['active'] == 1) { if ($result['active'] == 1) {
throw new Exception("Already Verified"); return "Already Verified";
} } else {
$query = "UPDATE `apis`.`auth` SET `active` = '1' WHERE (`token` = '$token');"; $Collection->updateOne(['token' => $token], ['$set' => ['active' => 1]]);
$db->query($query); return "Verified";
}
if ($result->getModifiedCount() == 1) {
return true; return true;
} else { } else {
return false; return false;
......
...@@ -25,9 +25,19 @@ class wireguard ...@@ -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) public function removepeer($public)
...@@ -35,7 +45,14 @@ class wireguard ...@@ -35,7 +45,14 @@ class wireguard
$cmd = "sudo wg set $this->device peer $public remove"; $cmd = "sudo wg set $this->device peer $public remove";
$result = 0; $result = 0;
trim(system($cmd, $result)); 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() public function getPeers()
......
...@@ -5,17 +5,13 @@ ...@@ -5,17 +5,13 @@
require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/database.class.php'); 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/ipnetworks.class.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/api/lib/wireguard.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";
}
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
require_once $_SERVER['DOCUMENT_ROOT'].'/api/lib/signup.class.php'; require_once $_SERVER['DOCUMENT_ROOT'].'/api/lib/signup.class.php';
require_once($_SERVER['DOCUMENT_ROOT']."/api/lib/database.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{ try{
if(signup::verifyAccount($token)){ if(signup::verifyAccount($token)){
?> ?>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment