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

converting mysql to mongodb (Wip)

parent c903c156
Branches master
No related tags found
No related merge requests found
vendor/
\ No newline at end of file
/vendor/
\ No newline at end of file
File moved
File moved
File moved
File moved
......@@ -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);
......
......@@ -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
......@@ -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
......@@ -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
......
......@@ -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;
......
......@@ -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()
......
......@@ -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";
}
......@@ -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)){
?>
......
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