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;
}
Esempio n. 2
0
function diy_deverror($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 {
        $date = date('Y-m-d H:i:s');
        $error = OAuth2\Request::createFromGlobals()->request["deverror"];
        $action = OAuth2\Request::createFromGlobals()->request["action"];
        $stmt = $storage->prepare('INSERT INTO error_clients (client_id, error, date, action) VALUES (:client_id, :error, :date, :action)');
        $stmt->execute(array('client_id' => $client_id, 'error' => $error, 'date' => $date, 'action' => $action));
        //result_messages===============================================================
        $result["result"] = "ok";
        $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();
    }
    return $result;
}
Esempio n. 3
0
 /**
  * Awesomeness for 3rd party support
  * 
  * Filter; determine_current_user
  * Other Filter: check_authentication
  *
  * This creates a hook in the determine_current_user filter that can check for a valid access_token 
  * and user services like WP JSON API and WP REST API.
  * @param  [type] $user_id User ID to
  *
  * @author Mauro Constantinescu Modified slightly but still a contribution to the project.
  */
 public function _wo_authenicate_bypass($user_id)
 {
     if ($user_id && $user_id > 0) {
         return (int) $user_id;
     }
     /** Extra code but if the user is already logged in, there is no need to re query the DB */
     $o = get_option('wo_options');
     if ($o['enabled'] == 0) {
         return (int) $user_id;
     }
     require_once dirname(WPOAUTH_FILE) . '/library/OAuth2/Autoloader.php';
     OAuth2\Autoloader::register();
     $server = new OAuth2\Server(new OAuth2\Storage\Wordpressdb());
     $request = OAuth2\Request::createFromGlobals();
     if ($server->verifyResourceRequest($request)) {
         $token = $server->getAccessTokenData($request);
         if (isset($token['user_id']) && $token['user_id'] > 0) {
             return (int) $token['user_id'];
             // If the token key is there but the ID is either 0 or empty
             // we will assume it is a valid client access token and will need to investigate the
             // request further.
         } elseif (isset($token['user_id']) && $token['user_id'] === 0) {
         }
     }
 }
Esempio n. 4
0
 function actionAuth()
 {
     $oRequest = OAuth2\Request::createFromGlobals();
     $oResponse = new OAuth2\Response();
     // validate the authorize request
     if (!$this->_oServer->validateAuthorizeRequest($oRequest, $oResponse)) {
         require_once BX_DIRECTORY_PATH_INC . 'design.inc.php';
         $o = json_decode($oResponse->getResponseBody());
         $this->_oTemplate->getPage(false, MsgBox($o->error_description));
     }
     if (!isLogged()) {
         require_once BX_DIRECTORY_PATH_INC . 'design.inc.php';
         $sForceRelocate = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'auth/?client_id=' . bx_get('client_id') . '&response_type=' . bx_get('response_type') . '&state=' . bx_get('state') . '&redirect_uri=' . bx_get('redirect_uri');
         bx_login_form(false, false, $sForceRelocate);
         return;
     }
     $aProfiles = BxDolAccount::getInstance()->getProfiles();
     if (!($iProfileId = $this->_oDb->getSavedProfile($aProfiles)) && empty($_POST)) {
         $oPage = BxDolPage::getObjectInstanceByURI('oauth-authorization');
         $this->_oTemplate->getPage(false, $oPage->getCode());
         return;
     }
     if (!$iProfileId) {
         $iProfileId = bx_get('profile_id');
     }
     $this->_oServer->handleAuthorizeRequest($oRequest, $oResponse, (bool) $iProfileId, $iProfileId);
     $oResponse->send();
 }
 /**
  * @Get("/auth")
  */
 public function authAction()
 {
     $storage = new OAuth2\Storage\Mongo(DI::getDefault()->getMongo());
     $server = new \OAuth2\Server($storage);
     $server->addGrantType(new OAuth2\GrantType\AuthorizationCode($storage));
     $server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send();
 }
 /**
  * Create an OAuth2 Request Object
  *
  */
 public function createRequest()
 {
     $request = OAuth2\Request::createFromGlobals();
     if (!$request instanceof OAuth2\Request) {
         $this->modx->log(modX::LOG_LEVEL_ERROR, '[OAuth2Server] could not create a valid request object!');
         return null;
     }
     return $request;
 }
 function __construct($config = array())
 {
     require_once __DIR__ . '/../config/database.php';
     //database config
     require_once __DIR__ . '/../third_party/Oauth2/src/OAuth2/Autoloader.php';
     //oauth library
     $config = $db['oauth'];
     OAuth2\Autoloader::register();
     $this->storage = new OAuth2\Storage\Pdo(array('dsn' => $config["dsn"], 'username' => $config["username"], 'password' => $config["password"]));
     $this->server = new OAuth2\Server($this->storage, array('allow_implicit' => true));
     $this->request = OAuth2\Request::createFromGlobals();
     $this->response = new OAuth2\Response();
 }
Esempio n. 8
0
/**
 * Returns an OAuth2 access token to the client
 *
 * PHP version 5
 *
 * @category   PHP
 * @package    Restyaboard
 * @subpackage Core
 * @author     Restya <*****@*****.**>
 * @copyright  2014 Restya
 * @license    http://restya.com/ Restya Licence
 * @link       http://restya.com/
 */
function getToken($post)
{
    $old_server_method = $_SERVER['REQUEST_METHOD'];
    $old_content_type = $_SERVER['CONTENT_TYPE'];
    $_SERVER['REQUEST_METHOD'] = 'POST';
    $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
    $_POST = $post;
    require_once 'server.php';
    $response = $server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send('return');
    $_SERVER['REQUEST_METHOD'] = $old_server_method;
    $_SERVER['CONTENT_TYPE'] = $old_content_type;
    return json_decode($response, true);
}
Esempio n. 9
0
 /**
  * @param Route $route
  * @throws \Slim\Exception\Stop
  */
 private function checkAuth(Route $route)
 {
     $request = OAuth2\Request::createFromGlobals();
     $scopeRequired = [];
     if ($route->isSecure()) {
         $scopeRequired = 'admin';
     }
     if (!$this->oauth->verifyResourceRequest($request, NULL, $scopeRequired)) {
         $response = $this->oauth->getResponse();
         $this->app->response()->status($response->getStatusCode());
         $response->send();
         $this->app->stop();
     }
 }
Esempio n. 10
0
function diy_wssaddsession($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;
    $session = OAuth2\Request::createFromGlobals()->request["session"];
    $wss_user = OAuth2\Request::createFromGlobals()->request["wss_user"];
    //$device = OAuth2\Request::createFromGlobals()->request["device"];
    try {
        $stmt1 = $storage->prepare('SELECT * FROM oauth_https_wss WHERE client_id = :client_id');
        $stmt1->execute(array('client_id' => trim($client_id)));
        $row = $stmt1->fetch(\PDO::FETCH_ASSOC);
        if ($row) {
            try {
                $stmt3 = $storage->prepare('UPDATE  oauth_https_wss set client_id = :client_id, wss_user = :wss_user, session = :session WHERE client_id = :client_id');
                $stmt3->execute(array('client_id' => $client_id, 'wss_user' => $wss_user, 'session' => $session));
            } catch (Exception $e) {
                echo "error 3" . $e->getMessage();
            }
        } else {
            try {
                $stmt2 = $storage->prepare('INSERT INTO oauth_https_wss (client_id, wss_user, session) VALUES  (:client_id, :wss_user,  :session)');
                $stmt2->execute(array('client_id' => trim($client_id), 'wss_user' => $wss_user, 'session' => $session));
            } catch (Exception $e) {
                echo "error 2" . $e->getCode();
            }
        }
        //result_messages===============================================================
        $result["result"]["session"] = $session;
        $result["result"]["client_id"] = $client_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();
    }
    return $result;
}
Esempio n. 11
0
function pleiobox_is_authorized()
{
    // only enable for development purposes as this occurs in a XSS vulnerability in production.
    // if (elgg_is_logged_in()) {
    //     return true;
    // }
    $oauth = new PleioboxOAuth2();
    $server = $oauth->getServer();
    if (!$server->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
        http_response_code(403);
        return false;
    }
    $token = $server->getAccessTokenData(OAuth2\Request::createFromGlobals());
    $user = get_user($token['user_id']);
    if ($user) {
        login($user);
        return true;
    }
    return false;
}
Esempio n. 12
0
 function actionAuth()
 {
     $oRequest = OAuth2\Request::createFromGlobals();
     $oResponse = new OAuth2\Response();
     // validate the authorize request
     if (!$this->_oServer->validateAuthorizeRequest($oRequest, $oResponse)) {
         $o = json_decode($oResponse->getResponseBody());
         $this->_oTemplate->pageError($o->error_description);
     }
     if (!isLogged()) {
         $_REQUEST['relocate'] = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'auth/?client_id=' . bx_get('client_id') . '&response_type=' . bx_get('response_type') . '&state=' . bx_get('state') . '&redirect_uri=' . bx_get('redirect_uri');
         login_form('', 0, false, 'disable_external_auth no_join_text');
         return;
     }
     if (empty($_POST)) {
         $this->_oTemplate->pageAuth($this->_oDb->getClientTitle(bx_get('client_id')));
     }
     $this->_oServer->handleAuthorizeRequest($oRequest, $oResponse, (bool) bx_get('confirm'), getLoggedId());
     $oResponse->send();
 }
Esempio n. 13
0
 /**
  * Awesomeness for 3rd party support
  * 
  * Filter; determine_current_user
  * Other Filter: check_authentication
  *
  * This creates a hook in the determine_current_user filter that can check for a valid access_token and 
  * user services like WP JSON API and WP REST API.
  * @param  [type] $o [description]
  * @return [type]    [description]
  *
  * @author Mauro Constantinescu Modified slightly but still a contribution to the project.
  */
 public function _wo_authenicate_bypass($user_id)
 {
     if ($user_id && $user_id > 0) {
         return (int) $user_id;
     }
     /** Extra code but if the user is already logged in, there is no need to re query the DB */
     $o = get_option('wo_options');
     if ($o['enabled'] == 0) {
         return (int) $user_id;
     }
     require_once dirname(WPOAUTH_FILE) . '/library/OAuth2/Autoloader.php';
     OAuth2\Autoloader::register();
     $server = new OAuth2\Server(new OAuth2\Storage\Wordpressdb());
     $request = OAuth2\Request::createFromGlobals();
     if ($server->verifyResourceRequest($request)) {
         $token = $server->getAccessTokenData($request);
         if (isset($token['user_id']) && $token['user_id'] > 0) {
             return (int) $token['user_id'];
         }
     }
 }
Esempio n. 14
0
/**
 * Returns an OAuth2 access token to the client
 *
 * @param array $post Post data
 *
 * @return mixed
 */
function getToken($post)
{
    $old_server_method = $_SERVER['REQUEST_METHOD'];
    if (!empty($_SERVER['CONTENT_TYPE'])) {
        $old_content_type = $_SERVER['CONTENT_TYPE'];
    }
    $_SERVER['REQUEST_METHOD'] = 'POST';
    $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
    $_POST = $post;
    OAuth2\Autoloader::register();
    $oauth_config = array('user_table' => 'users');
    $val_array = array('dsn' => 'pgsql:host=' . R_DB_HOST . ';dbname=' . R_DB_NAME . ';port=' . R_DB_PORT, 'username' => R_DB_USER, 'password' => R_DB_PASSWORD);
    $storage = new OAuth2\Storage\Pdo($val_array, $oauth_config);
    $server = new OAuth2\Server($storage);
    if (isset($_POST['grant_type']) && $_POST['grant_type'] == 'password') {
        $val_array = array('password' => $_POST['password']);
        $users = array($_POST['username'] => $val_array);
        $user_credentials = array('user_credentials' => $users);
        $storage = new OAuth2\Storage\Memory($user_credentials);
        $server->addGrantType(new OAuth2\GrantType\UserCredentials($storage));
    } elseif (isset($_POST['grant_type']) && $_POST['grant_type'] == 'refresh_token') {
        $always_issue_new_refresh_token = array('always_issue_new_refresh_token' => true);
        $server->addGrantType(new OAuth2\GrantType\RefreshToken($storage, $always_issue_new_refresh_token));
    } elseif (isset($_POST['grant_type']) && $_POST['grant_type'] == 'authorization_code') {
        $server->addGrantType(new OAuth2\GrantType\AuthorizationCode($storage));
    } else {
        $val_array = array('client_secret' => OAUTH_CLIENT_SECRET);
        $clients = array(OAUTH_CLIENTID => $val_array);
        $credentials = array('client_credentials' => $clients);
        $storage = new OAuth2\Storage\Memory($credentials);
        $server->addGrantType(new OAuth2\GrantType\ClientCredentials($storage));
    }
    $response = $server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send('return');
    $_SERVER['REQUEST_METHOD'] = $old_server_method;
    if (!empty($old_content_type)) {
        $_SERVER['CONTENT_TYPE'] = $old_content_type;
    }
    return json_decode($response, true);
}
Esempio n. 15
0
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;
}
Esempio n. 16
0
<?php

/**
 * Returns an OAuth2 access token to the client
 *
 * PHP version 5
 *
 * @category   PHP
 * @package    Restyaboard
 * @subpackage Core
 * @author     Restya <*****@*****.**>
 * @copyright  2014 Restya
 * @license    http://www.restya.com/ Restya Licence
 * @link       http://www.restya.com
 */
require_once 'server.php';
$server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send();
Esempio n. 17
0
header("Content-Type: text/html; charset=utf-8");
//api/get/diy_getinfoconfig.php
// get info for client (device)
// the device request config info for device settings not the owner
// this is for devices configuration and sync
$app->get('/devinfo', function () use($authenticateForRole, $diy_storage) {
    global $app;
    $params = loadParameters();
    $server = $authenticateForRole();
    $dbstorage = $diy_storage();
    if (!$server->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
        echo 'Unable to verify access token: ' . "\n";
        $server->getResponse()->send();
        die;
    } else {
        $crypto_token = OAuth2\Request::createFromGlobals()->query["access_token"];
        $separator = '.';
        list($header, $payload, $signature) = explode($separator, $crypto_token);
        //echo base64_decode($payload);
        $params["payload"] = $payload;
        $params["storage"] = $dbstorage;
        $result = diy_getinfoconfig($params["payload"], $params["storage"], $params["test"]);
        PrepareResponse();
        $app->response()->setBody(toGreek(json_encode($result)));
    }
});
function diy_getinfoconfig($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
Esempio n. 18
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;
}
Esempio n. 19
0
        $server->getResponse()->send();
        die;
    }
    $api = new \Aums\API('username', 'password');
    $info = $api->login();
    echo json_encode(['success' => true, 'data' => ['roll_no' => $info['roll_no'], 'first_name' => $info['first_name'], 'last_name' => $info['last_name'], 'email' => $info['email'], 'image_filename' => $info['image_filename']]]);
});
$app->post('/oauth/resource/extra', function () use($server) {
    $request = OAuth2\Request::createFromGlobals();
    $response = new OAuth2\Response();
    $scopeRequired = 'extras';
    if (!$server->verifyResourceRequest($request, $response, $scopeRequired)) {
        $server->getResponse()->send();
        die;
    }
    $api = new \Aums\API('username', 'password');
    $info = $api->login();
    echo json_encode(['success' => true, 'data' => ['roll_no' => $info['roll_no'], 'first_name' => $info['first_name'], 'last_name' => $info['last_name'], 'email' => $info['email'], 'degree_program' => $info['degree_program'], 'branch' => $info['branch'], 'semester' => $info['semester'], 'image_filename' => $info['image_filename']]]);
});
$app->post('/oauth/resource/picture/:filename', function ($filename) use($app, $server) {
    $request = OAuth2\Request::createFromGlobals();
    $response = new OAuth2\Response();
    $scopeRequired = 'profile_pic';
    if (!$server->verifyResourceRequest($request, $response, $scopeRequired)) {
        $server->getResponse()->send();
        die;
    }
    $app->response->headers->set('Content-Type', 'image/jpg');
    echo file_get_contents(__DIR__ . '/../storage/images/' . $filename);
});
$app->run();
Esempio n. 20
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;
}
 /**
  * Authentication for resources
  * http://bshaffer.github.io/oauth2-server-php-docs/controllers/resource/
  *
  * @param string $format Data format
  */
 function authentication_resource($format)
 {
     if (!$this->server->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
         $response = $this->server->getResponse();
         $response->setParameters(array('message' => 'Requires authentication'));
         $response->send($format);
         exit;
     }
 }
Esempio n. 22
0
<?php

/**
 *
 * @author: XuYi
 * @date: 2015-07-23
 * @version: $Id$
 */
// include our OAuth2 Server object
require_once __DIR__ . '/server.php';
// Handle a request to a resource and authenticate the access token
if (!$server->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
    $server->getResponse()->send();
    die;
}
echo json_encode(array('success' => true, 'message' => 'You accessed my APIs!'));
Esempio n. 23
0
 public function doUserInfo()
 {
     $request = OAuth2\Request::createFromGlobals();
     $response = new OAuth2\Response();
     if (!$this->server->verifyResourceRequest($request)) {
         return $this->server->getResponse();
     } else {
         $api_response = array('friends' => array('john', 'matt', 'jane'));
         echo json_encode($api_response);
         //          $token = $this->server->getAccessTokenData($request);
         //          var_dump($token);
         //          echo json_encode(array("userid"=>"123"));
         // echo "User ID associated with this token is {$token['user_id']}";
     }
 }
Esempio n. 24
0
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;
}
Esempio n. 25
0
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;
}
Esempio n. 26
0
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;
}
<?php

/**
 * CLAROLINE
 *
 * @version 0.1
 *
 * @copyright (c) 2014 Quentin Devos
 *
 * @license http://www.gnu.org/copyleft/gpl.html (GPL) GENERAL PUBLIC LICENSE
 *
 * @package OAUTH
 *
 * @author Quentin Devos <*****@*****.**>
 *
 */
require_once get_module_path('OAUTH') . '/lib/InitServer.php';
// Check that the provided Access Token is valid.
if ($server->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
    // Retrieve informations from the token and log in the corresponding user.
    $token = $server->getAccessTokenData(OAuth2\Request::createFromGlobals());
    $GLOBALS['_uid'] = $token['user_id'];
    $GLOBALS['uidReset'] = true;
    $claro_loginRequested = true;
    $claro_loginSucceeded = true;
} else {
    $GLOBALS['_uid'] = null;
    $claro_loginSucceeded = false;
    $claro_loginRequested = false;
}
Esempio n. 28
0
 function CheckLogin()
 {
     $this->Logger->Write('Starting CheckLogin');
     switch ($this->CallType) {
         case "open":
             //user openregister no need authorization
             if ($this->Code == 'openregisteruser' && $this->Module == 'user') {
                 return true;
             }
             $db_host = $this->Config['db_host'];
             $db_name = $this->Config['db_name'];
             $dsn = "mysql:dbname={$db_name};host={$db_host}";
             $username = $this->Config['db_user'];
             $password = $this->Config['db_pass'];
             $storage = new OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));
             $server = new OAuth2\Server($storage);
             $response = new OAuth2\Response();
             $request = OAuth2\Request::createFromGlobals();
             if (!$server->verifyResourceRequest($request, $response)) {
                 $response->send();
                 exit;
             } else {
                 //get current login id
                 //$this->Logger->Write('Invoke Open API:'.$this->Module.",".$this->Code);
                 $access_token = $request->request['access_token'];
                 if ($access_token && $access_token != '') {
                     $sql = "select token.user_id,u.uname from oauth_access_tokens token left join user u on u.uid=token.user_id where token.access_token='{$access_token}'";
                     $row = $this->DataBaseHandler->FetchFirst($sql);
                     if ($row) {
                         //$this->Logger->Write('Get user id:'.$row['user_id'].' for access token:'.$access_token);
                         $access_uid = $row['user_id'];
                         $this->User['uid'] = $access_uid;
                         $this->User['uname'] = $row['uname'];
                         $this->IsLogin = 1;
                     }
                 } else {
                     $error = array();
                     $error["error"] = "error";
                     $error["error_description"] = "access token is incorrect.";
                     echo json_encode($error);
                     exit;
                 }
             }
             return $this->IsLogin;
             break;
         case "localsite":
             session_start();
             if ($_SESSION['ip_point']) {
                 $this->IPLocation = $_SESSION['ip_point'];
             } else {
                 $this->IPLocation = $this->BaiduMap->GetPointByIP(getIP());
                 $_SESSION['ip_point'] = $this->IPLocation;
             }
             //var_dump($this->IPLocation);
             $auth = $this->CookieHandler->GetVar('authstr');
             $post_auth = $this->Post['cookie_auth'] ? $this->Post['cookie_auth'] : $this->Get['cookie_auth'];
             $login = 0;
             if ($post_auth != '' && (!$auth || $auth == '')) {
                 $pid = 0;
                 $pwd = '';
                 list($pid, $pwd) = explode('*', $post_auth);
                 $user = $this->UserLogic->GetUser($pid);
                 if ($pwd == $user['password']) {
                     $login = 1;
                     $this->User = $user;
                 }
                 return $login;
             }
             if ($auth && $auth != '') {
                 $dauth = authcode($auth, 'DECODE', $this->Config['auth_key']);
                 //$dauth=urldecode($auth);
                 $uid = 0;
                 $password = '';
                 list($uid, $password) = explode('\\~', $dauth);
                 $this->TemplateHandler->AssignValue('auth', $uid . '*' . $password);
                 //need to verify the user id and password are valid in cookie;
                 $u = array();
                 if ($_SESSION['uid'] && $_SESSION['uid'] > 0) {
                     $u['uid'] = $_SESSION['uid'];
                 }
                 if ($_SESSION['uemail'] && $_SESSION['uemail'] != "") {
                     $u['uemail'] = $_SESSION['uemail'];
                 }
                 if ($_SESSION['uname']) {
                     $u['uname'] = $_SESSION['uname'];
                 }
                 if ($_SESSION['face_url']) {
                     $u['face_url'] = $_SESSION['face_url'];
                 }
                 if ($_SESSION['face_url_p']) {
                     $u['face_url_p'] = $_SESSION['face_url_p'];
                 }
                 if (count($u) > 0 && $u['uid'] > 0) {
                     $this->User = $u;
                     $this->SessionUser = $u;
                     $login = 1;
                 } else {
                     $user = $this->UserLogic->GetUser($uid);
                     if ($password == $user['password']) {
                         $this->User = $user;
                         $this->SessionUser = $user;
                         $_SESSION['uid'] = $uid;
                         $_SESSION['uemail'] = $email;
                         $_SESSION['uname'] = $user['uname'];
                         $_SESSION['face_url'] = $user['face_url'];
                         $_SESSION['face_url_p'] = $user['face_url_p'];
                         $login = 1;
                         $this->UserLogic->UpdateLoginInfo($user['uid'], time());
                     }
                 }
                 $name = $user['uname'] == '' ? $user['uemail'] : $user['uname'];
             }
             $this->IsLogin = $login;
             $this->TemplateHandler->AssignValue('login', $login);
             $this->TemplateHandler->AssignValue('user', $this->User);
             if ($_SESSION['open']) {
                 $this->TemplateHandler->AssignValue('open_login', true);
                 $this->Open_login = true;
             } else {
                 $this->TemplateHandler->AssignValue('open_login', false);
                 $this->Open_login = false;
             }
             $this->TemplateHandler->AssignValue('sessionuser', $this->SessionUser);
             $this->Logger->Write('Finished CheckLogin');
             return $login;
             break;
     }
 }
Esempio n. 29
0
 /**
  * Get the list of employees attached to an entity
  * @param int $id Identifier of the entity
  * @param bool $children If TRUE, we include sub-entities, FALSE otherwise
  * @author Benjamin BALET <*****@*****.**>
  * @since 0.4.3
  */
 public function getListOfEmployeesInEntity($id, $children)
 {
     if (!$this->server->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
         $this->server->getResponse()->send();
     } else {
         $this->load->model('organization_model');
         $children = filter_var($children, FILTER_VALIDATE_BOOLEAN);
         $result = $this->organization_model->allEmployees($id, $children);
         echo json_encode($result);
     }
 }
Esempio n. 30
0
 /**
  * Create a leave request (fields are passed by POST parameters).
  * This function doesn't send e-mails and it is used for imposed leaves
  * Returns the new inserted id.
  * @author Benjamin BALET <*****@*****.**>
  */
 public function createleave()
 {
     if (!$this->server->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
         $this->server->getResponse()->send();
     } else {
         $this->load->model('leaves_model');
         $startdate = $this->input->post('startdate');
         $enddate = $this->input->post('enddate');
         $status = $this->input->post('status');
         $employee = $this->input->post('employee');
         $cause = $this->input->post('cause');
         $startdatetype = $this->input->post('startdatetype');
         $enddatetype = $this->input->post('enddatetype');
         $duration = $this->input->post('duration');
         $type = $this->input->post('type');
         $debug1 = var_export($startdate, true);
         $debug2 = var_export($enddate, true);
         $debug3 = var_export($status, true);
         $debug4 = var_export($employee, true);
         $debug5 = var_export($cause, true);
         $debug6 = var_export($startdatetype, true);
         $debug7 = var_export($enddatetype, true);
         $debug8 = var_export($duration, true);
         $debug9 = var_export($type, true);
         //Prevent misinterpretation of content
         if ($cause == FALSE) {
             $cause = NULL;
         }
         //Check mandatory fields
         if ($startdate == FALSE || $enddate == FALSE || $status === FALSE || $employee === FALSE || $startdatetype == FALSE || $enddatetype == FALSE || $duration === FALSE || $type === FALSE) {
             $this->output->set_header("HTTP/1.1 422 Unprocessable entity");
             log_message('error', 'Mandatory fields are missing.');
         } else {
             $result = $this->leaves_model->add_leaves_api($startdate, $enddate, $status, $employee, $cause, $startdatetype, $enddatetype, $duration, $type);
             echo json_encode($result);
         }
     }
 }