function diy_compile($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    $params = loadParameters();
    $srcfile = OAuth2\Request::createFromGlobals()->request["srcfile"];
    $srclib = OAuth2\Request::createFromGlobals()->request["srclib"];
    $device = OAuth2\Request::createFromGlobals()->request["device"];
    $comp = OAuth2\Request::createFromGlobals()->request["comp"];
    $filename = OAuth2\Request::createFromGlobals()->request["filename"];
    $writedevice = OAuth2\Request::createFromGlobals()->request["writedevice"];
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    $diy_error["post"]["device"] = $device;
    $post["srcfile"] = $srcfile;
    //organisation                                  oauth_devices
    $post["device"] = $device;
    //organisation                                  oauth_devices
    $post["comp"] = $comp;
    //organisation                                  oauth_devices
    $post["filename"] = $filename;
    //organisation                                  oauth_devices
    $post["writedevice"] = $writedevice;
    //organisation                                  oauth_devices
    $gump = new GUMP();
    $gump->validation_rules(array('device' => 'required|alpha_numeric', 'filename' => 'required|alpha_numeric', 'comp' => 'required|alpha_numeric', 'writedevice' => 'required|alpha_numeric'));
    $gump->filter_rules(array('device' => 'trim|sanitize_string', 'filename' => 'trim|sanitize_string', 'comp' => 'trim|sanitize_string', 'writedevice' => 'trim|sanitize_string'));
    $validated = $gump->run($post);
    if ($validated === false) {
        $result["parse_errors"] = $gump->get_readable_errors(true);
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $gump->get_readable_errors(true);
    } else {
        try {
            $sourceWriteDir = __DIR__ . '/../../../data/sketches/' . $client_id . '/' . $device . '/' . $filename;
            if (file_exists($sourceWriteDir)) {
                throw new \Exception('Filename ' . $filename . ' for user ' . $client_id . ' and device ' . $device . ' already exists');
            }
            $stmt2 = $storage->prepare('SELECT * FROM oauth_devices WHERE device = :device');
            $stmt2->execute(array('device' => trim($device)));
            $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
            if ($row2["organisation"]) {
                $org = trim($row2["organisation"]);
            }
            if ($row2["mode"]) {
                $mode = trim($row2["mode"]);
            }
            if ($row2["status"]) {
                $status = trim($row2["status"]);
            }
            if ($row2["client_id"]) {
                $devclient_id = trim($row2["client_id"]);
            }
            $orgscopeadmin = "no";
            $orgscopedevel = "no";
            if ($mode == "devel" && $status == "org") {
                $userscopes = explode(' ', trim($userscope));
                $adminscope = $org . "_admin";
                $develscope = $org . "_admin";
                // o user aniki sto scope
                for ($i = 0; $i <= count($userscopes); $i++) {
                    if (trim($userscopes[$i]) == $adminscope) {
                        $orgscopeadmin = "yes";
                    }
                    if (trim($userscopes[$i]) == $develscope) {
                        $orgscopedevel = "yes";
                    }
                }
                // einai o owner
                if ($devclient_id == $client_id) {
                    $orgscopeadmin = "yes";
                }
            }
            // einmai o owner
            if ($mode == "devel" && $status == "private" && $devclient_id == $client_id) {
                $orgscopeadmin = "yes";
            }
            $result["result"]["sketch1"] = $orgscopeadmin;
            if ($orgscopeadmin == "yes" || $orgscopedevel == "yes") {
                try {
                    $stmt2 = $storage->prepare('SELECT * FROM oauth_clients WHERE client_id = :device');
                    $stmt2->execute(array('device' => trim($device)));
                    $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
                    if ($row2["apiport"]) {
                        // *************************************** compiler *********************************
                        // srcfile echeis se base64 ton kodika
                        // compiler echeis ton compiler pou thelei o user   mechri stigmis echoume   gcc, ino
                        // filename to filename pou edosse o user
                        // o poros compilesketch
                        // afou kanei compile
                        // epistrefei
                        // error   ta lathi  h noerrors
                        // binfile    to hex file
                        $compilerserver = diyConfig::read("compiler.host");
                        $compilerserver .= ":" . diyConfig::read("compiler.port");
                        $data1 = 'filename=' . $filename;
                        $data1 .= '&compiler=' . $comp;
                        $data1 .= '&srcfile=' . $srcfile;
                        $fixedFiles = array();
                        foreach ($srclib as $curName => $curFile) {
                            $fixedFiles[] = 'srclib[' . $curName . ']=' . $curFile;
                        }
                        $data1 .= '&' . implode('&', $fixedFiles);
                        $ch = curl_init();
                        curl_setopt($ch, CURLOPT_URL, "{$compilerserver}/api/compilesketch");
                        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
                        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                        curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
                        curl_setopt($ch, CURLOPT_POST, 1);
                        $or = curl_exec($ch);
                        if (!$or) {
                            $or = curl_error($ch);
                        }
                        $result["compiler"] = $or;
                        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
                        $result["status"] = "200";
                        $r = json_decode($or, true);
                        if (!$r) {
                            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: CompilationError";
                            $result["compiler"] = $or;
                            $result["status"] = "500";
                            return $result;
                        }
                        if ($r['status'] != 200) {
                            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: CompilationError";
                            $result["status"] = "500";
                            return $result;
                        }
                        unset($result["compiler"]);
                        // No need to transfer this to the user
                        //$srcfilebase64encode = base64_encode($srcfile);
                        $apiport = trim($row2["apiport"]);
                        // *************************************** compiler *********************************
                        if ($r['status'] == 200 && $writedevice == "yes") {
                            $apiport = trim($row2["apiport"]);
                            $binfile = $r['hex'];
                            $data1 = 'file=base64';
                            $data1 .= '&binfile=' . $binfile;
                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, "http://127.0.0.1:{$apiport}/api/writesketch");
                            curl_setopt($ch, CURLOPT_TIMEOUT, 90);
                            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
                            curl_setopt($ch, CURLOPT_POST, 1);
                            $r = curl_exec($ch);
                            $result["sketch"] = $r;
                            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
                            $result["status"] = "200";
                            //$result["result"]=  $r;
                        }
                        // If we are here with no exceptions then everything went well. Lets save the sketch.
                        $ziptmp = tempnam(sys_get_temp_dir(), 'diytmpzip') . '.tgz';
                        file_put_contents($ziptmp, base64_decode($r['zip']));
                        $p = new PharData($ziptmp);
                        $p->decompress();
                        // creates /path/to/my.tar
                        $ziptmpextracted = str_replace('.tgz', '.tar', $ziptmp);
                        $phar = new PharData($ziptmpextracted);
                        $writeDir = __DIR__ . '/../../../data/sketches/' . $client_id . '/' . $filename;
                        $phar->extractTo($sourceWriteDir);
                    }
                } catch (Exception $e) {
                    $diy_error["db"] = $e->getCode();
                    $result["status"] = $e->getCode();
                    $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
                }
            }
        } catch (Exception $e) {
            $diy_error["db"] = $e->getCode();
            $result["status"] = $e->getCode();
            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
        }
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
function diy_removedevice($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    //$params = loadParameters();
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    $userscope = $up->scope;
    $device = OAuth2\Request::createFromGlobals()->query["device"];
    $diy_error["post"]["device"] = $device;
    $post["device"] = $device;
    // to client_id tou device			oauth_devices	oauth_clients	oauth_public_keys
    //$result["result"]["up"] =  $up;
    $gump = new GUMP();
    $gump->validation_rules(array('device' => 'required|alpha_numeric'));
    $gump->filter_rules(array('device' => 'trim|sanitize_string'));
    $validated = $gump->run($post);
    if ($validated === false) {
        $result["parse_errors"] = $gump->get_readable_errors(true);
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $gump->get_readable_errors(true);
    } else {
        $dev = $storage->prepare('SELECT * FROM oauth_devices WHERE device  = :device');
        $dev->execute(array('device' => trim($device)));
        $rowdev = $dev->fetch(PDO::FETCH_ASSOC);
        if ($rowdev) {
            $org = $rowdev["organisation"];
        } else {
            $result["result"]["error"] = ExceptionMessages::DeviceNotExist . " , " . ExceptionCodes::DeviceNotExist;
        }
        //check if org name exists
        $orgexists = "no";
        $stmtorg = $storage->prepare('SELECT * FROM oauth_organisations WHERE organisation = :org');
        $stmtorg->execute(array('org' => trim($org)));
        $roworg = $stmtorg->fetch(PDO::FETCH_ASSOC);
        if ($roworg) {
            $orgexists = "yes";
            //$result["result"]["error"] =  ExceptionMessages::OrgExist." , ". ExceptionCodes::OrgExist;
            $orgadmin = "no";
            $orgowner = "no";
            $userscopes = explode(' ', trim($userscope));
            $orgscope = $org . "_admin";
            for ($i = 0; $i <= count($userscopes); $i++) {
                if (trim($userscopes[$i]) == $orgscope) {
                    $orgadmin = "yes";
                }
            }
            if ($orgadmin == "no") {
                //check if org name exists and client_id
                $stmtorg1 = $storage->prepare('SELECT * FROM oauth_organisations WHERE organisation = :org and client_id = :client_id');
                $stmtorg1->execute(array('org' => trim($org), 'client_id' => $client_id));
                $roworg1 = $stmtorg1->fetch(PDO::FETCH_ASSOC);
                if (!$roworg1) {
                    $result["result"]["error"] = ExceptionMessages::OrgOwner . " , " . ExceptionCodes::OrgOwner;
                } else {
                    $orgowner = "yes";
                }
            }
        } else {
            $result["result"]["error"] = ExceptionMessages::OrgNotExist . " , " . ExceptionCodes::OrgNotExist;
        }
        //check if device name exists
        $orgdeviceexists = "no";
        $stmt = $storage->prepare('SELECT client_id  FROM oauth_clients WHERE client_id = :device');
        $stmt->execute(array('device' => trim($device)));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            //$result["result"]["error"] =  ExceptionMessages::DeviceExist." , ". ExceptionCodes::DeviceExist;
            $orgdeviceexists = "yes";
        } else {
            $result["result"]["error"] = ExceptionMessages::DeviceNotExist . " , " . ExceptionCodes::DeviceNotExist;
            $orgdeviceexists = "no";
        }
        if ($orgexists == "yes" && ($orgowner == "yes" || $orgadmin == "yes") && $orgdeviceexists == "yes") {
            //}else{
            try {
                // oauth_public_keys table
                $encryption_algorithm = "RS256";
                $stmt5 = $storage->prepare('DELETE from oauth_public_keys where client_id = :client_id');
                $stmt5->execute(array('client_id' => $device));
                $stmt1 = $storage->prepare('SELECT * from oauth_clients where client_id = :client_id');
                $stmt1->execute(array('client_id' => $device));
                $row1 = $stmt1->fetch(PDO::FETCH_ASSOC);
                if ($row1) {
                    $dataport = $row1["dataport"];
                    $apiport = $row1["apiport"];
                    // oauth_users table
                    $user_id = $row1["user_id"];
                    $stmt = $storage->prepare('DELETE from oauth_users where user_id = :user_id');
                    $stmt->execute(array('user_id' => $user_id));
                    // oauth_ports table
                    $stmt2 = $storage->prepare('DELETE from oauth_ports where port = :port');
                    $stmt2->execute(array('port' => $dataport));
                    $stmt2 = $storage->prepare('DELETE from oauth_ports where port = :port');
                    $stmt2->execute(array('port' => $apiport));
                    // oauth_clients table
                    $stmt1 = $storage->prepare('DELETE from oauth_clients where client_id = :client_id');
                    $stmt1->execute(array('client_id' => $device));
                    // oauth_devices table
                    $stmt11 = $storage->prepare('DELETE from oauth_devices where device = :device');
                    $stmt11->execute(array('device' => $device));
                }
                //result_messages===============================================================
                $result["result"]["result"] = $post;
                $result["result"]["session"] = $session;
                $result["error"] = $error;
                $result["status"] = "200";
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
            } catch (Exception $e) {
                $result["status"] = $e->getCode();
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
            }
        }
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
Exemple #3
0
function diy_diyexec($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    $params = loadParameters();
    $device = OAuth2\Request::createFromGlobals()->request["device"];
    $exec = OAuth2\Request::createFromGlobals()->request["exec"];
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    $diy_error["post"]["device"] = $device;
    $post["device"] = $device;
    //organisation                                  oauth_devices
    $post["exec"] = $exec;
    //organisation                                  oauth_devices
    $gump = new GUMP();
    $gump->validation_rules(array('device' => 'required|alpha_numeric', 'exec' => 'required|alpha_numeric'));
    $gump->filter_rules(array('device' => 'trim|sanitize_string', 'exec' => 'trim|sanitize_string'));
    $validated = $gump->run($post);
    if ($validated === false) {
        $result["parse_errors"] = $gump->get_readable_errors(true);
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $gump->get_readable_errors(true);
    } else {
        try {
            $stmt2 = $storage->prepare('SELECT * FROM oauth_devices WHERE device = :device');
            $stmt2->execute(array('device' => trim($device)));
            $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
            if ($row2["organisation"]) {
                $org = trim($row2["organisation"]);
            }
            if ($row2["mode"]) {
                $mode = trim($row2["mode"]);
            }
            if ($row2["status"]) {
                $status = trim($row2["status"]);
            }
            if ($row2["client_id"]) {
                $devclient_id = trim($row2["client_id"]);
            }
            $orgscopeadmin = "no";
            $orgscopedevel = "no";
            if ($status == "org") {
                $userscopes = explode(' ', trim($userscope));
                $adminscope = $org . "_admin";
                $develscope = $org . "_admin";
                // o user aniki sto scope
                for ($i = 0; $i <= count($userscopes); $i++) {
                    if (trim($userscopes[$i]) == $adminscope) {
                        $orgscopeadmin = "yes";
                    }
                    if (trim($userscopes[$i]) == $develscope) {
                        $orgscopedevel = "yes";
                    }
                }
                // einai o owner
                if ($devclient_id == $client_id) {
                    $orgscopeadmin = "yes";
                }
            }
            // einmai o owner
            if ($status == "private" && $devclient_id == $client_id) {
                $orgscopeadmin = "yes";
            }
            if ($orgscopeadmin == "yes" || $orgscopedevel == "yes") {
                try {
                    $stmt2 = $storage->prepare('SELECT * FROM oauth_clients WHERE client_id = :device');
                    $stmt2->execute(array('device' => trim($device)));
                    $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
                    if ($row2["apiport"]) {
                        $stmt3 = $storage->prepare('SELECT * FROM oauth_diyexec WHERE exec = :exec');
                        $stmt3->execute(array('exec' => trim($exec)));
                        $row3 = $stmt3->fetch(PDO::FETCH_ASSOC);
                        if ($row3["exec"]) {
                            $apiport = trim($row2["apiport"]);
                            $diyexec = trim($row3["diyexec"]);
                            $diyexecurl = base64_encode($diyexec);
                            $data1 = 'exec=' . $diyexecurl;
                            //$result["result1"]=  $diyexec;
                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, "http://127.0.0.1:{$apiport}/api/diyexec");
                            curl_setopt($ch, CURLOPT_TIMEOUT, 20);
                            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
                            curl_setopt($ch, CURLOPT_POST, 1);
                            $r = curl_exec($ch);
                            var_dump($r);
                            $result["DEV"] = $r;
                        }
                    }
                } catch (Exception $e) {
                    $diy_error["db"] = $e->getCode();
                    $result["status"] = $e->getCode();
                    $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
                }
            }
        } catch (Exception $e) {
            $diy_error["db"] = $e->getCode();
            $result["status"] = $e->getCode();
            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
        }
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
function diy_adddevice($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    //$params = loadParameters();
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    $userscope = $up->scope;
    $org = OAuth2\Request::createFromGlobals()->request["org"];
    $device = OAuth2\Request::createFromGlobals()->request["device"];
    $client_secret = OAuth2\Request::createFromGlobals()->request["passwd"];
    $device_desc = OAuth2\Request::createFromGlobals()->request["device_desc"];
    $diy_error["post"]["org"] = $org;
    $diy_error["post"]["device"] = $device;
    $diy_error["post"]["client_secret"] = $client_secret;
    $diy_error["post"]["device_desc"] = $device_desc;
    $post["org"] = $org;
    //organisation					oauth_devices
    $post["device"] = $device;
    // to client_id tou device			oauth_devices	oauth_clients	oauth_public_keys
    $post["client_secret"] = $client_secret;
    //mia perigrafi oti thelei o christis		oauth_devices
    $post["device_desc"] = $device_desc;
    //mia perigrafi oti thelei o christis		oauth_devices
    //$result["result"]["up"] =  $up;
    $gump = new GUMP();
    $gump->validation_rules(array('org' => 'required|alpha_numeric', 'device' => 'required|alpha_numeric', 'client_secret' => 'required|max_len,100|min_len,6', 'device_desc' => 'required|max_len,100'));
    $gump->filter_rules(array('org' => 'trim|sanitize_string', 'device' => 'trim|sanitize_string', 'client_secret' => 'trim', 'device_desc' => 'trim|sanitize_string'));
    $validated = $gump->run($post);
    if ($validated === false) {
        $result["parse_errors"] = $gump->get_readable_errors(true);
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $gump->get_readable_errors(true);
    } else {
        //check if org name exists
        $orgexists = "no";
        $stmtorg = $storage->prepare('SELECT * FROM oauth_organisations WHERE organisation = :org');
        $stmtorg->execute(array('org' => trim($org)));
        $roworg = $stmtorg->fetch(PDO::FETCH_ASSOC);
        if ($roworg) {
            $orgexists = "yes";
            //$result["result"]["error"] =  ExceptionMessages::OrgExist." , ". ExceptionCodes::OrgExist;
            $orgadmin = "no";
            $orgowner = "no";
            $userscopes = explode(' ', trim($userscope));
            $orgscope = $org . "_admin";
            for ($i = 0; $i <= count($userscopes); $i++) {
                if (trim($userscopes[$i]) == $orgscope) {
                    $orgadmin = "yes";
                }
            }
            if ($orgadmin == "no") {
                //check if org name exists and client_id
                $stmtorg1 = $storage->prepare('SELECT * FROM oauth_organisations WHERE organisation = :org and client_id = :client_id');
                $stmtorg1->execute(array('org' => trim($org), 'client_id' => $client_id));
                $roworg1 = $stmtorg1->fetch(PDO::FETCH_ASSOC);
                if (!$roworg1) {
                    $result["result"]["error"] = ExceptionMessages::OrgOwner . " , " . ExceptionCodes::OrgOwner;
                } else {
                    $orgowner = "yes";
                }
            }
        } else {
            $result["result"]["error"] = ExceptionMessages::OrgNotExist . " , " . ExceptionCodes::OrgNotExist;
        }
        //check if device name exists
        $orgdeviceexists = "no";
        $stmt = $storage->prepare('SELECT client_id  FROM oauth_clients WHERE client_id = :device');
        $stmt->execute(array('device' => trim($device)));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            $result["result"]["error"] = ExceptionMessages::DeviceExist . " , " . ExceptionCodes::DeviceExist;
            $orgdeviceexists = "yes";
        }
        if ($orgexists == "yes" && ($orgowner == "yes" || $orgadmin == "yes") && $orgdeviceexists == "no") {
            //}else{
            try {
                $tempfile = tempnam('tmp/', '');
                if (file_exists($tempfile)) {
                    unlink($tempfile);
                }
                mkdir($tempfile);
                if (is_dir($tempfile)) {
                    exec("openssl genrsa -out {$tempfile}/{$client_id}-privkey.pem 2048");
                    exec("openssl rsa -in {$tempfile}/{$client_id}-privkey.pem -pubout -out {$tempfile}/{$client_id}-pubkey.pem");
                    $publicKey = file_get_contents("{$tempfile}/{$client_id}-pubkey.pem");
                    $privateKey = file_get_contents("{$tempfile}/{$client_id}-privkey.pem");
                    // oauth_public_keys table
                    $encryption_algorithm = "RS256";
                    $stmt5 = $storage->prepare('INSERT INTO oauth_public_keys (client_id, public_key, private_key, encryption_algorithm) VALUES (:client_id, :public_key, :private_key, :encryption_algorithm)');
                    $stmt5->execute(array('client_id' => $device, 'public_key' => $publicKey, 'private_key' => $privateKey, ':encryption_algorithm' => $encryption_algorithm));
                    unlink("{$tempfile}/{$client_id}-pubkey.pem");
                    unlink("{$tempfile}/{$client_id}-privkey.pem");
                    // na ftiaxo to key me tis portes na einai etoimo
                    // tha to kano messo cron
                    // o pinakas ta echei ola oauth_clients
                }
                // user_id for dev
                $lastkey = $storage->query('SELECT user_id FROM oauth_users ORDER BY user_id DESC LIMIT 1');
                foreach ($lastkey as $curRow) {
                    $lastkey = intval($curRow[0]);
                }
                $lastkey++;
                // oauth_users table
                $stmt = $storage->prepare('INSERT INTO oauth_users (user_id,email_verified) VALUES (:user_id,"1")');
                $stmt->execute(array('user_id' => $lastkey));
                $scope = $org . "_dev";
                $scope .= ' ' . $org . "_dpri";
                $apiport = $storage->query('SELECT apiport FROM oauth_clients ORDER BY apiport DESC LIMIT 1');
                foreach ($apiport as $curRow) {
                    $apiport = intval($curRow[0]);
                }
                $dataport = $apiport + 1;
                $apiport = $apiport + 2;
                $apihost = diyConfig::read('api.host');
                $sshhost = diyConfig::read('ssh.host');
                $sshport = diyConfig::read('ssh.port');
                // oauth_ports table
                $stmt2 = $storage->prepare('INSERT INTO oauth_ports (port, client_id) VALUES (:port, :client_id)');
                $stmt2->execute(array('client_id' => $device, 'port' => $dataport));
                $stmt2 = $storage->prepare('INSERT INTO oauth_ports (port, client_id) VALUES (:port, :client_id)');
                $stmt2->execute(array('client_id' => $device, 'port' => $apiport));
                // oauth_clients table
                $tty = "/dev/ttyACM0";
                $baud = "115200";
                $stmt1 = $storage->prepare('INSERT INTO oauth_clients (client_id, client_secret, user_id, scope, dataport, apiport, apihost, sshhost, sshport, tty, baud) VALUES (:client_id, :client_secret, :user_id, :scope, :dataport, :apiport, :apihost, :sshhost, :sshport, :tty, :baud)');
                $stmt1->execute(array('user_id' => $lastkey, 'client_id' => $device, 'client_secret' => $client_secret, 'scope' => $scope, 'dataport' => $dataport, 'apiport' => $apiport, 'apihost' => $apihost, 'sshhost' => $sshhost, 'sshport' => $sshport, 'tty' => $tty, 'baud' => $baud));
                // oauth_devices table
                $public_key_active = "yes";
                $status = "private";
                $mode = "devel";
                $stmt11 = $storage->prepare('INSERT INTO oauth_devices (device, device_desc, organisation, client_id, public_key_active, status, mode) VALUES (:device, :device_desc, :organisation, :client_id, :public_key_active, :status, :mode)');
                $stmt11->execute(array('device' => $device, 'client_id' => $client_id, 'device_desc' => $device_desc, 'organisation' => $org, 'public_key_active' => $public_key_active, 'status' => $status, 'mode' => $mode));
                $post["status"] = $status;
                $post["mode"] = $mode;
                //result_messages===============================================================
                $result["result"]["result"] = $post;
                $result["result"]["session"] = $session;
                $result["error"] = $error;
                $result["status"] = "200";
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
            } catch (Exception $e) {
                $result["status"] = $e->getCode();
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
            }
        }
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
Exemple #5
0
function diy_addorg($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    //$params = loadParameters();
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    $org = OAuth2\Request::createFromGlobals()->request["org"];
    $org_desc = OAuth2\Request::createFromGlobals()->request["org_desc"];
    $diy_error["post"]["org"] = $org;
    $diy_error["post"]["org_desc"] = $org_desc;
    $post["org"] = $org;
    //organisation					oauth_devices
    $post["org_desc"] = $org_desc;
    //mia perigrafi oti thelei o christis		oauth_devices
    $gump = new GUMP();
    $gump->validation_rules(array('org' => 'required|alpha_numeric', 'org_desc' => 'required|max_len,100'));
    $gump->filter_rules(array('org' => 'trim|sanitize_string', 'org_desc' => 'trim|sanitize_string'));
    $validated = $gump->run($post);
    if ($validated === false) {
        $result["parse_errors"] = $gump->get_readable_errors(true);
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $gump->get_readable_errors(true);
    } else {
        //check if device name exists
        $stmt = $storage->prepare('SELECT * FROM oauth_organisations WHERE organisation = :org');
        $stmt->execute(array('org' => trim($org)));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            $result["result"]["error"] = ExceptionMessages::OrgExist . " , " . ExceptionCodes::OrgExist;
        } else {
            try {
                // oauth_organisation table
                $stmt2 = $storage->prepare('INSERT INTO oauth_organisations (organisation, client_id, desc) VALUES (:org, :client_id, :desc)');
                $stmt2->execute(array('client_id' => $client_id, 'org' => $org, 'desc' => $org_desc));
                // scopes gia devices
                $scope = $org;
                $is_default = 0;
                $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)');
                $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default));
                $scope = $org . "_dev";
                $is_default = 0;
                $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)');
                $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default));
                $scope = $org . "_dpri";
                $is_default = 0;
                $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)');
                $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default));
                $scope = $org . "_org";
                $is_default = 0;
                $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)');
                $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default));
                $scope = $org . "_dpub";
                $is_default = 0;
                $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)');
                $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default));
                // scopes gia users
                $scope = $org . "_view";
                $is_default = 0;
                $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)');
                $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default));
                $scope = $org . "_devel";
                $is_default = 0;
                $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)');
                $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default));
                $scope = $org . "_admin";
                $is_default = 0;
                $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)');
                $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default));
                $stmt6 = $storage->prepare('SELECT * FROM oauth_clients WHERE client_id = :client_id');
                $stmt6->execute(array('client_id' => trim($client_id)));
                $row6 = $stmt6->fetch(PDO::FETCH_ASSOC);
                if ($row6) {
                    $scope6 = $row6["scope"];
                    $scope6 .= " " . $org . "_admin";
                    $scope6 .= " " . $org . "_view";
                    $stmt5 = $storage->prepare('UPDATE oauth_clients  set scope = :scope6 where client_id = :client_id');
                    $stmt5->execute(array('scope6' => $scope6, 'client_id' => $client_id));
                }
                //result_messages===============================================================
                $result["result"]["result"] = $post;
                $result["result"]["session"] = $session;
                $result["error"] = $error;
                $result["status"] = "200";
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
            } catch (Exception $e) {
                $result["status"] = $e->getCode();
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
            }
        }
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
#!/usr/bin/php
<?php 
include "full path for core.php";
$dbfile = 'full path oauth.sqlite';
$home = diyConfig::read('ssh.home');
$_keys = diyConfig::read('ssh.keys');
$db = new PDO(sprintf('sqlite:%s', $dbfile));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare('SELECT * FROM oauth_clients');
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo $row["apiport"] . "\n";
    if ($row["apiport"]) {
        $devuser = trim($row["client_id"]);
        $apiport = trim($row["apiport"]);
        $dataport = trim($row["dataport"]);
        $sshhome = $home . "/{$devuser}/{$_keys}";
        echo $sshhome;
        if (file_exists($sshhome)) {
            //echo "The file $sshhome exists";
        } else {
            $tmp = "/tmp/diy-{$devuser}.pem";
            $output = shell_exec("echo -e  'y\n' | ssh-keygen -q -N '' -f {$tmp}");
            $devkey1 = file_get_contents("{$tmp}.pub");
            $devkey1 = trim($devkey1);
            $devkey2 = file_get_contents("{$tmp}");
            $auth_settings = 'no-pty,no-X11-forwarding,permitopen="localhost:' . $dataport . '",permitopen="localhost:' . $apiport . '",command="/bin/echo do-not-send-commands" ' . $devkey1;
            mkdir("{$home}/{$devuser}");
            file_put_contents("{$home}/{$devuser}/{$_keys}", $auth_settings);
            exec("adduser -U {$devuser} -s /bin/true");
            exec("chmod 700  {$home}/{$devuser}");
function diy_wssdeviceAccess($payload, $storage, $exceptions)
{
    global $app;
    $post["session"] = OAuth2\Request::createFromGlobals()->query["session"];
    $post["wss_user"] = OAuth2\Request::createFromGlobals()->query["wss_user"];
    $post["device"] = OAuth2\Request::createFromGlobals()->query["device"];
    $gump = new GUMP();
    $gump->validation_rules(array('wss_user' => 'required|alpha_numeric', 'device' => 'required|alpha_numeric', 'session' => 'required|alpha_numeric'));
    $gump->filter_rules(array('wss_user' => 'trim|sanitize_string', 'device' => 'trim|sanitize_string', 'session' => 'trim|sanitize_string'));
    //$result["gump2"] = $validated; // validation successful
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    $params = loadParameters();
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    $result["result"]["view"] = 0;
    $validated = $gump->run($post);
    if ($validated === false) {
        $result["parse_errors"] = $gump->get_readable_errors(true);
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $gump->get_readable_errors(true);
    } else {
        try {
            $stmt = $storage->prepare('SELECT * FROM oauth_devices WHERE device = :device');
            $stmt->execute(array('device' => $post["device"]));
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($row["organisation"]) {
                $organisation = trim($row["organisation"]);
                //$organisation=$row["scope"];
                // o user einai sto scope
                try {
                    $stmt1 = $storage->prepare('SELECT * FROM oauth_https_wss WHERE wss_user = :wss_user and session = :session');
                    $stmt1->execute(array('wss_user' => trim($post["wss_user"]), 'session' => trim($post["session"])));
                    $row1 = $stmt1->fetch(PDO::FETCH_ASSOC);
                    if ($row1["client_id"]) {
                        $client_user = $row1["client_id"];
                        if ($row["status"] == "org") {
                            try {
                                $stmt2 = $storage->prepare('SELECT * FROM oauth_clients WHERE client_id = :client_user');
                                $stmt2->execute(array('client_user' => trim($client_user)));
                                $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
                                if ($row2["scope"]) {
                                    $devview = $organisation . "_view";
                                    if (strpos(trim($row2["scope"]), $devview) !== false) {
                                        $result["result"]["view"] = 1;
                                    } else {
                                        $diy_error["errors"] = ExceptionMessages::ScopeNotFound . " , " . ExceptionCodes::ScopeNotFound;
                                    }
                                }
                            } catch (Exception $e) {
                                echo "error " . $e->getCode();
                                $diy_error["db"] = $e->getCode();
                            }
                        } elseif ($row["status"] == "public") {
                            $result["result"]["view"] = 1;
                        } elseif ($row["status"] == "private" && $row["client_id"] == $client_user) {
                            $result["result"]["view"] = 1;
                        } elseif ($row["status"] == "private" && $row["client_id"] != $client_user) {
                            $result["result"]["view"] = 0;
                        }
                    } else {
                        $diy_error["errors"] = ExceptionMessages::UserNotFound . " , " . ExceptionCodes::UserNotFound;
                        //$result["errors"]["select"] = exceptions::MethodNotFound;
                    }
                } catch (Exception $e) {
                    echo "error " . $e->getCode();
                    $diy_error["db"] = $e->getCode();
                }
            }
            //result_messages===============================================================
            $result["status"] = "200";
            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
        } catch (Exception $e) {
            $result["status"] = $e->getCode();
            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
            echo "error " . $e->getCode();
            $diy_error["db"] = $e->getCode();
        }
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
function diy_movedevice($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    //$params = loadParameters();
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    $userscope = $up->scope;
    $device = OAuth2\Request::createFromGlobals()->query["device"];
    $orgto = OAuth2\Request::createFromGlobals()->query["orgto"];
    $diy_error["post"]["device"] = $device;
    $diy_error["post"]["orgto"] = $orgto;
    $post["device"] = $device;
    // to client_id tou device			oauth_devices	oauth_clients	oauth_public_keys
    $post["orgto"] = $orgto;
    // to client_id tou device			oauth_devices	oauth_clients	oauth_public_keys
    //$result["result"]["up"] =  $up;
    $gump = new GUMP();
    $gump->validation_rules(array('device' => 'required|alpha_numeric', 'orgto' => 'required|alpha_numeric'));
    $gump->filter_rules(array('device' => 'trim|sanitize_string', 'orgto' => 'trim|sanitize_string'));
    $validated = $gump->run($post);
    if ($validated === false) {
        $result["parse_errors"] = $gump->get_readable_errors(true);
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $gump->get_readable_errors(true);
    } else {
        $movedevice = "no";
        $dev = $storage->prepare('SELECT * FROM oauth_devices WHERE device  = :device');
        $dev->execute(array('device' => trim($device)));
        $rowdev = $dev->fetch(PDO::FETCH_ASSOC);
        if ($rowdev) {
            $org = $rowdev["organisation"];
        } else {
            $result["result"]["error"] = ExceptionMessages::DeviceNotExist . " , " . ExceptionCodes::DeviceNotExist;
        }
        function check($storage, $userscopes, $org, $client_id, $device)
        {
            //check if org name exists
            $orgexists = "no";
            $stmtorg = $storage->prepare('SELECT * FROM oauth_organisations WHERE organisation = :org');
            $stmtorg->execute(array('org' => trim($org)));
            $roworg = $stmtorg->fetch(PDO::FETCH_ASSOC);
            if ($roworg) {
                $orgexists = "yes";
                //$result["result"]["error"] =  ExceptionMessages::OrgExist." , ". ExceptionCodes::OrgExist;
                $orgadmin = "no";
                $orgowner = "no";
                $userscopes = explode(' ', trim($userscope));
                $orgscope = $org . "_admin";
                for ($i = 0; $i <= count($userscopes); $i++) {
                    if (trim($userscopes[$i]) == $orgscope) {
                        $orgadmin = "yes";
                    }
                }
                if ($orgadmin == "no") {
                    //check if org name exists and client_id
                    $stmtorg1 = $storage->prepare('SELECT * FROM oauth_organisations WHERE organisation = :org and client_id = :client_id');
                    $stmtorg1->execute(array('org' => trim($org), 'client_id' => $client_id));
                    $roworg1 = $stmtorg1->fetch(PDO::FETCH_ASSOC);
                    if (!$roworg1) {
                        $result["result"]["error"] = ExceptionMessages::OrgOwner . " , " . ExceptionCodes::OrgOwner;
                    } else {
                        $orgowner = "yes";
                    }
                }
            } else {
                $result["result"]["error"] = ExceptionMessages::OrgNotExist . " , " . ExceptionCodes::OrgNotExist;
            }
            //check if device name exists
            $orgdeviceexists = "no";
            $stmt = $storage->prepare('SELECT client_id  FROM oauth_clients WHERE client_id = :device');
            $stmt->execute(array('device' => trim($device)));
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($row) {
                //$result["result"]["error"] =  ExceptionMessages::DeviceExist." , ". ExceptionCodes::DeviceExist;
                $orgdeviceexists = "yes";
            } else {
                $result["result"]["error"] = ExceptionMessages::DeviceNotExist . " , " . ExceptionCodes::DeviceNotExist;
                $orgdeviceexists = "no";
            }
            if ($orgexists == "yes" && ($orgowner == "yes" || $orgadmin == "yes") && $orgdeviceexists == "yes") {
                $result["result"]["check"] = "ok";
                return $result;
            } else {
                $result["result"]["check"] = "no";
                return $result;
            }
        }
        $diy_error["error"]["check"] = check($storage, $userscopes, $org, $client_id, $device);
        // check if user owned the devices or have admin scope in orgfrom
        $checkr = check($storage, $userscopes, $org, $client_id, $device);
        if ($checkr["result"]["check"] == "ok") {
            $diy_error["error"]["orgfrom"] = "ok";
            // check if user owned the devices or have admin scope in orgto
            $checkr1 = check($storage, $userscopes, $orgto, $client_id, $device);
            if ($checkr1["result"]["check"] == "ok") {
                $diy_error["error"]["orgto"] = "ok";
                $movedevice = "yes";
            }
        }
        //if( ($orgexists == "yes" && ($orgowner == "yes" || $orgadmin == "yes")) && $orgdeviceexists == "yes"){
        if ($movedevice == "yes") {
            //}else{
            try {
                $stmt1 = $storage->prepare('SELECT * from oauth_clients where client_id = :client_id');
                $stmt1->execute(array('client_id' => $device));
                $row1 = $stmt1->fetch(PDO::FETCH_ASSOC);
                if ($row1) {
                    $scopedevt = $row1["scope"];
                    $orgt = $org . "_";
                    $orgtot = $orgto . "_";
                    $scopedev = str_replace($orgt, $orgtot, $scopedevt);
                    // oauth_clients table
                    $stmt1 = $storage->prepare('UPDATE oauth_clients set scope = :scopedev where client_id = :client_id');
                    $stmt1->execute(array('client_id' => $device, 'scopedev' => $scopedev));
                    // oauth_devices table
                    $stmt11 = $storage->prepare('UPDATE oauth_devices set organisation = :orgto  where device = :device');
                    $stmt11->execute(array('device' => $device, 'orgto' => $orgto));
                }
                //result_messages===============================================================
                $result["result"]["result"] = $post;
                $result["result"]["session"] = $session;
                $result["error"] = $error;
                $result["status"] = "200";
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
            } catch (Exception $e) {
                $result["status"] = $e->getCode();
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
            }
        }
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
function diy_register()
{
    global $app, $diy_storage;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $client_id = $params["client_id"];
    $client_secret = $params["client_secret"];
    $firstname = $params["first_name"];
    $lastname = $params["last_name"];
    $email = $params["email"];
    $post["client_id"] = $client_id;
    $post["client_secret"] = $client_secret;
    $post["firstname"] = $firstname;
    $post["lastname"] = $lastname;
    $post["email"] = $email;
    foreach ($post as $curKey => $curValue) {
        $diy_error["post"][$curKey] = $curValue;
    }
    $gump = new GUMP();
    $gump->validation_rules(array('client_id' => 'required|alpha_numeric', 'client_secret' => 'required|alpha_numeric', 'firstname' => 'required|alpha_numeric', 'lastname' => 'required|alpha_numeric', 'email' => 'required|valid_email'));
    $gump->filter_rules(array('client_id' => 'trim|sanitize_string', 'client_secret' => 'trim|sanitize_string', 'firstname' => 'trim|sanitize_string', 'lastname' => 'trim|sanitize_string', 'email' => 'trim|sanitize_string'));
    $validated = $gump->run($post);
    if ($validated === false) {
        $result["parse_errors"] = $gump->get_readable_errors(true);
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $gump->get_readable_errors(true);
    }
    try {
        if (count($result["parse_errors"]) <= 0) {
            $storage = $diy_storage();
            $lastkey = $storage->query('SELECT user_id FROM oauth_users ORDER BY user_id DESC LIMIT 1');
            foreach ($lastkey as $curRow) {
                $lastkey = intval($curRow[0]);
            }
            $code = md5($post["firstname"] . $post["lastname"] . $post["email"]);
            // Create user
            $storage->query('INSERT INTO oauth_users (user_id, first_name, last_name, email, email_verified, email_ver_code)
        VALUES (' . ($lastkey + 1) . ', "' . $post["firstname"] . '", "' . $post["lastname"] . '", "' . $post["email"] . '", 0, "' . $code . '")');
            $user_id = $storage->lastInsertId();
            // Create client
            $publicKey = file_get_contents('../../ssh/CLIENT_ID1_pubkey.pem');
            $privateKey = file_get_contents('../../ssh/CLIENT_ID1_privkey.pem');
            $storage->query('INSERT INTO oauth_clients (client_id, client_secret, scope, user_id) VALUES ("' . $post["client_id"] . '", "' . $post["client_secret"] . '", "main", ' . $user_id . ')');
            $client_id = $storage->lastInsertId();
            $storage->query('INSERT INTO oauth_public_keys (client_id, public_key, private_key, encryption_algorithm) VALUES ("' . $post["client_id"] . '", "' . $publicKey . '", "' . $privateKey . '", "RS256")');
            // Send email
            $mailserver = diyConfig::read('mail.smtpserver');
            $mailserverport = diyConfig::read('mail.smtpport');
            $mailfrom = diyConfig::read('mail.fromuser');
            $link = 'https://' . $_SERVER['HTTP_HOST'] . '/api/activate/' . $code;
            $transport = Swift_SmtpTransport::newInstance($mailserver, $mailserverport);
            $mailer = Swift_Mailer::newInstance($transport);
            $message = Swift_Message::newInstance('Wonderful Subject')->setFrom(array($mailfrom => 'Diyiot'))->setTo(array($post["email"]))->setSubject('Welcome to diyiot')->setBody('Hi ' . $post["firstname"] . ',<BR /><BR />To active your account please click the following link <a href="' . $link . '">' . $link . '</a>.', 'text/html', 'UTF-8');
            $mailer->send($message);
        }
        //result_messages===============================================================
        $result["result"]["user_id"] = $user_id;
        $result["error"] = $error;
        $result["status"] = "200";
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
    } catch (Exception $e) {
        $result["status"] = $e->getCode();
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
        if (isset($user_id)) {
            $storage->query('DELETE FROM oauth_users WHERE user_id = ' . $user_id);
        }
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
function diy_seletc($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    $params = loadParameters();
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    try {
        $m = new MongoClient("mongodb://localhost:27017");
        $db = $m->selectDB("diyiot_sensorsData");
        $collection = $db->mycol;
        switch ((int) $params["operation_id"]) {
            case 1:
                $mongoResult = iterator_to_array($collection->find(array("Map.mapName" => $params["map_name"])));
                break;
            case 2:
                $mongoResult = iterator_to_array($collection->find(array("Date&Time.year" => $params["date_year"], "Date&Time.month" => $params["date_month"], "Date&Time.day" => $params["date_day"])));
                break;
            case 3:
                $mongoResult = iterator_to_array($collection->find(array("Date&Time.year" => $params["date_year"], "Date&Time.month" => $params["date_month"], "Date&Time.day" => $params["date_day"], "Map.mapName" => $params["map_name"])));
                break;
            default:
                $mongoResult = "Wrong number of arguments";
        }
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
        $result["status"] = "200";
        $result["result"] = $mongoResult;
    } catch (Exception $e) {
        $diy_error["db"] = $e->getCode();
        $result["status"] = $e->getCode();
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
Exemple #11
0
    $_dsn = diyConfig::read('db.dsn');
    $_username = diyConfig::read('db.username');
    $_password = diyConfig::read('db.password');
    $storage = new PdoStorageWithEmailVerification(array('dsn' => $_dsn, 'username' => $_username, 'password' => $_password));
    //$storage = new OAuth2\Storage\Pdo(array('dsn' => $_dsn, 'username' => $_username, 'password' => $_password));
    $server = new OAuth2\Server($storage);
    $server->addGrantType(new OAuth2\GrantType\ClientCredentials($storage), array('allow_credentials_in_request_body => true'));
    $cryptoStorage = new OAuth2\Storage\CryptoToken($storage);
    $server->addStorage($cryptoStorage, "access_token");
    $cryptoResponseType = new OAuth2\ResponseType\CryptoToken($storage);
    $server->addResponseType($cryptoResponseType);
    return $server;
};
$diy_storage = function () {
    //global $conOptions;
    $_dbfile = diyConfig::read('db.file');
    $db = new PDO(sprintf('sqlite:%s', $_dbfile));
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    return $db;
};
$diy_exception = function () {
    $exception = new CustomException();
    return $exception;
};
//=========================  POST ==================================
/**
*
* @SWG\Resource(
*   apiVersion="0.1",
*   swaggerVersion="2.0",
function diy_getdevices($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    $params = loadParameters();
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    try {
        $stmt2 = $storage->prepare('SELECT * FROM oauth_clients WHERE client_id = :client_id');
        $stmt2->execute(array('client_id' => trim($client_id)));
        $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
        if ($row2["scope"]) {
            $scopes = explode(' ', trim($row2["scope"]));
            $diy_error["scopescount"] = count($scopes);
            $devview = "view";
            $nr = 0;
            for ($i = 0; $i <= count($scopes); $i++) {
                $diy_error["scopes"] = $scopes[$i];
                $view = explode('_', $scopes[$i]);
                if (trim($view[1]) == $devview) {
                    $org = trim($view[0]);
                    $diy_error["org"] = $org;
                    try {
                        $stmt = $storage->prepare('SELECT * FROM oauth_devices WHERE organisation = :org');
                        $stmt->execute(array('org' => $org));
                        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                            if ($row["status"] == "private" && $row["client_id"] == "{$client_id}") {
                                $devices["dev"][$nr]["device"] = $row["device"];
                                $devices["dev"][$nr]["device_desc"] = $row["device_desc"];
                                $devices["dev"][$nr]["organisation"] = $row["organisation"];
                                $devices["dev"][$nr]["status"] = $row["status"];
                                $devices["dev"][$nr]["mode"] = $row["mode"];
                                $nr++;
                            } elseif ($row["status"] == "org" || $row["status"] == "public") {
                                $diy_error["dev"][$nr] = $row["device"];
                                $devices["dev"][$nr]["device"] = $row["device"];
                                $devices["dev"][$nr]["device_desc"] = $row["device_desc"];
                                $devices["dev"][$nr]["organisation"] = $row["organisation"];
                                $devices["dev"][$nr]["status"] = $row["status"];
                                $devices["dev"][$nr]["mode"] = $row["mode"];
                                $nr++;
                            }
                        }
                    } catch (Exception $e) {
                        $diy_error["db"] = $e->getCode();
                        $result["status"] = $e->getCode();
                        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
                    }
                }
            }
            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
            $result["status"] = "200";
            $result["result"] = $devices;
        }
    } catch (Exception $e) {
        $diy_error["db"] = $e->getCode();
        $result["status"] = $e->getCode();
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
Exemple #13
0
    public static function write($name, $value)
    {
        self::$confArray[$name] = $value;
    }
}
//debug
diyConfig::write('debug', 1);
// 1 = on 0 = off
//compiler
diyConfig::write('compiler.host', $_comphost);
diyConfig::write('compiler.port', $_compport);
//api
diyConfig::write('api.host', $_apihost);
//ssh
diyConfig::write('ssh.host', $_sshhost);
diyConfig::write('ssh.port', $_sshport);
// db
diyConfig::write('db.file', sprintf($_dbfile));
diyConfig::write('db.dsn', sprintf('sqlite:%s', $_dbfile));
diyConfig::write('db.port', '');
diyConfig::write('db.basename', '');
diyConfig::write('db.username', 'root');
diyConfig::write('db.password', '');
//ssh
diyConfig::write('ssh.home', $sshhome);
diyConfig::write('ssh.keys', $sshhomekeys);
// e-mail server settings
diyConfig::write('mail.fromuser', $fromuser);
diyConfig::write('mail.smtpserver', $smtpserver);
diyConfig::write('mail.smtpport', $smtpport);