Skip to content

Commit

Permalink
fixed issues #38, #39, #40
Browse files Browse the repository at this point in the history
updated tools/oauth2demo for 1.6.0. refactoring
  • Loading branch information
Hufschmidt committed Nov 11, 2016
1 parent 2e5163f commit 99af4fb
Show file tree
Hide file tree
Showing 11 changed files with 65 additions and 67 deletions.
10 changes: 2 additions & 8 deletions RESTController/RESTController.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,16 +90,10 @@ public static function registerAutoloader() {
* $iliasRoot <String> - Absolute path to ILIAS directory
* $userSettings <Array[Mixed]> - Associative array of application settings
*/
public function __construct($iliasRoot, array $userSettings = array()) {
public function __construct(array $userSettings = array()) {
// Call parent (SLIM) constructor
parent::__construct($userSettings);

// Fetch environment and remeber base-directory (just in case)
$env = $this->environment();
$env['ilias_root'] = $iliasRoot;
$env['ctl_root'] = __DIR__;
// Alternatively set as hard-coded path: "$root/Customizing/global/plugins/Services/UIComponent/UserInterfaceHook/REST/RESTController"

// Add Content-Type middleware (support for JSON/XML requests)
$contentType = new libs\Middleware\ContentTypes();
$this->add($contentType);
Expand All @@ -123,7 +117,7 @@ public function __construct($iliasRoot, array $userSettings = array()) {

// Set default template base-directory
// DoIt: Extract using ILIAS (or keep constant)
$this->view()->setTemplatesDirectory($appDirectory);
$this->view()->setTemplatesDirectory(__DIR__);

// Set default 404 template
$this->notFound(function () {
Expand Down
6 changes: 2 additions & 4 deletions RESTController/core/oauth2_v2/models/Authorize.php
Original file line number Diff line number Diff line change
Expand Up @@ -331,17 +331,15 @@ public static function ShowWebsite($app, $param) {
// fetch absolute dirictory of view folder
$plugin = Libs\RESTilias::getPlugin();
$pluginDir = str_replace('./', '', $plugin->getDirectory());
$pluginDir = $pluginDir . '/RESTController/core/oauth2_v2/views/';


$viewDir = $pluginDir . '/RESTController/core/oauth2_v2/views/';

// Content and further logic is managed by the template
$app->response()->setFormat('HTML');
$app->render(
'core/oauth2_v2/views/index.php',
array(
'baseURL' => ILIAS_HTTP_PATH,
'viewURL' => ILIAS_HTTP_PATH . '/' . $pluginDir,
'viewURL' => ILIAS_HTTP_PATH . '/' . $viewDir,
'endpoint' => ILIAS_HTTP_PATH . '/' . $pluginDir . '/api.php' . $routeURL,
'client' => CLIENT_ID,
'parameters' => $param,
Expand Down
2 changes: 1 addition & 1 deletion RESTController/core/oauth2_v2/views/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
<div class="card">
<img class="logo" src="<?php echo $viewURL; ?>img/logo.png">

<h1>Anmeldung</h1>
<h1>OAuth2</h1>
<h2>Anwendungs-Zugriff</h2><br>

<?php
Expand Down
6 changes: 3 additions & 3 deletions RESTController/database/RESTclient.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ public static function fromApiKey($apiKey) {
* Function: getKey($key)
* @See RESTDatabase->getKey(...)
*/
public function getKey($key) {
public function getKey($key, $read = false) {
// Fetch internal value from parent
$value = parent::getKey($key);
$value = parent::getKey($key, $read);

// Convert internal value when publshing
// Note: Make sure to 'revert' those changes in setKey(...)!
Expand Down Expand Up @@ -329,7 +329,7 @@ public function isScopeAllowed($scope) {
return Libs\RESTLib::CheckComplexRestriction($allowed, $scopes, ' ');
}


/**
* Function: isBridgeAllowed($direction)
* Checks if the ILIAS <-> oAuth2 bridge is allowed for this client in the requested direction.
Expand Down
6 changes: 4 additions & 2 deletions RESTController/libs/RESTDatabase.php
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,8 @@ public static function fromWhere($where = null, $limit = false, $offset = false,

// Build a simple where-based query
$table = static::getTableName();
$class = end(explode('\\', get_called_class()));
$array = explode('\\', get_called_class());
$class = end($array);
$sql = sprintf('SELECT %s.* FROM %s AS %s %s %s %s %s', $class, $table, $class, $joinSQL, $whereSQL, $limitSQL, $offsetSQL);

// Generate ilDB query-object
Expand Down Expand Up @@ -1175,7 +1176,8 @@ public static function getTableKeys() {
* <String> - Short name of current class name (late static binding)
*/
public static function getName() {
return end(explode('\\', get_called_class()));
$array = explode('\\', get_called_class());
return end($array);
}


Expand Down
4 changes: 4 additions & 0 deletions RESTController/libs/RESTRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,10 @@ public function getToken($name = 'access', $stringOnly = false) {
if (isset($this->tokens[$name]))
return $this->tokens[$name];

// Prevent undefined variables
$tokenString = null;

// Extract token
switch ($name) {
// Fetch access-token
default:
Expand Down
9 changes: 8 additions & 1 deletion RESTController/libs/RESTResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,15 @@ public function __construct($body = '', $status = 200, $headers = array()) {
* @See \Slim\Http\Response->write(...) for more details
*/
public function write($body, $replace = false) {
// Keep normal mode of operation for HTML/RAW
switch ($this->format) {
case 'HTML':
case 'RAW':
return parent::write($body, $replace);
}

// Merged new body with old content
if ($replace === false) {
if ($replace !== true) {
// Decode old content
$oldBody = $this->decode($this->getBody());

Expand Down
2 changes: 1 addition & 1 deletion api.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@
chdir($directory);

// Instantate and run the RESTController application
$restCTL = new \RESTController\RESTController($directory);
$restCTL = new \RESTController\RESTController();
$restCTL->run();
6 changes: 3 additions & 3 deletions tools/oauth2demo/config.ini.php.default
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?php
$api_key = "apollon"; // API-Key to be used
$api_secret = "S3Tjw0N4t8"; // only needed for grant type "Clients Credentials"
$subFolder = "/dev/ilias"; // need to be specified if your ILIAS installation is not located at the document root
$api_key = "appollon"; // API-Key to be used
$api_secret = ""; // only needed for grant type "Clients Credentials"
$ilias_url = "http://ilias.localhost"; // need to be specified if your ILIAS installation is not located at the document root
44 changes: 20 additions & 24 deletions tools/oauth2demo/endpoints/authcode_endpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,33 +18,20 @@
// Exchange OAuth 2 authorization code for bearer token
if (isset($_GET['code'])){
if (isset($_GET['make_curl_call'])) {
// Protocol used for curl call
if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off') {
$protocol = 'http://';
} else {
$protocol = 'https://';
}

// Redirection URL (but into body)
$redirect_uri = $protocol . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'];
if ($_SERVER["SERVER_PORT"] != "80") {
$redirect_uri = $protocol . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER['PHP_SELF'];
}
$apiDir = $ilias_url . "/Customizing/global/plugins/Services/UIComponent/UserInterfaceHook/REST";
$tokenUrl = $apiDir . "/api.php/v2/oauth2/token";

// Build the body for curl call
$post = array(
'grant_type' => 'authorization_code',
'code' => $_GET['code'],
'api_key' => $api_key,
'api_secret' => $api_secret,
'redirect_uri' => $redirect_uri
'redirect_uri' => $_SERVER['PHP_SELF']
);

// Endpoint (url) used for curl call
$url = $subFolder. "/v2/oauth2/token";

//
$ch = curl_init($url);
$ch = curl_init($tokenUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
Expand All @@ -61,18 +48,27 @@
// Convert to array
$decoded = json_decode($body, true);

?>
<h3>OAuth2 Token via Authorization Code Workflow Retrieved!</h3>
<pre>Access-Token: <?php echo (isset($decoded["access_token"])) ? $decoded["access_token"] : "[ No Data ]"; ?></pre>
<pre>Refresh-Token: <?php echo (isset($decoded["refresh_token"])) ? $decoded["refresh_token"] : "[ No Data ]"; ?></pre>
<h4> The client can continue now making further API requests with the obtained bearer token.</h4>
<?php
if (isset($decoded["access_token"])) {
?>
<h3>OAuth2 Token via Authorization Code Workflow Retrieved!</h3>
<pre>Access-Token: <?php echo (isset($decoded["access_token"])) ? $decoded["access_token"] : "[ No Data ]"; ?></pre>
<pre>Refresh-Token: <?php echo (isset($decoded["refresh_token"])) ? $decoded["refresh_token"] : "[ No Data ]"; ?></pre>
<h4> The client can continue now making further API requests with the obtained bearer token.</h4>
<?php
}
else {
?>
<h3>Error when requesting OAuth2 Token:</h3>
<pre><?php var_dump($body); ?></pre>
<?php
}
}
else {
$call = $_SERVER['REQUEST_URI'] . '&make_curl_call=1';
?>
<h3>The Server has authenticated your request and generated an authentication code that can be traded for a bearer token.</h3>
<pre>Authorization Code: <?php echo $_GET['code']; ?></pre>
<a href='<?php echo $_SERVER['REQUEST_URI']; ?>&make_curl_call=1'>Trade authentication code for bearer token</a><br><br>
<a href='<?php echo $call; ?>'>Trade authentication code for bearer token</a><br><br>
<?php
}
}
Expand Down
37 changes: 17 additions & 20 deletions tools/oauth2demo/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,18 @@
// Include settings
require_once('config.ini.php');

// Generate GET/POST URLs
if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off') {
$protocol = 'http://';
} else {
$protocol = 'https://';
}
$base_url = $protocol . $_SERVER['SERVER_NAME'] . dirname($_SERVER['PHP_SELF']);
if ($_SERVER["SERVER_PORT"] != "80") {
$base_url = $protocol . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"] . dirname($_SERVER['PHP_SELF']);
}
$loginUrl = $subFolder. "/v2/oauth2/authorize?api_key=".urlencode($api_key);
$self = dirname($_SERVER['PHP_SELF']);

// This will be the redirect targets for generating bearer tokens via GET (POST contains this info in the header)
$authGrantUrl = $loginUrl."&redirect_uri=".urlencode($base_url."/endpoints/authcode_endpoint.php")."&response_type=code";
$implicitGrantUrl = $loginUrl."&redirect_uri=".urlencode($base_url."/endpoints/implicitgrant_endpoint.php")."&response_type=token";
$apiDir = $ilias_url . "/Customizing/global/plugins/Services/UIComponent/UserInterfaceHook/REST";
$authUrl = $apiDir . "/api.php/v2/oauth2/authorize";
$tokenUrl = $apiDir . "/api.php/v2/oauth2/token";

$authGrantRedirect = $self . "/endpoints/authcode_endpoint.php";
$implicitGrantRedirect = $self . "/endpoints/implicitgrant_endpoint.php";

$loginUrl = $authUrl . "?api_key=" . urlencode($api_key);
$authGrantUrl = $loginUrl . "&response_type=code&redirect_uri=" . urlencode($authGrantRedirect);
$implicitGrantUrl = $loginUrl . "&response_type=token&redirect_uri=" . urlencode($implicitGrantRedirect);
?>
<h3>Initiating one of the following OAuth2 Grant Mechanism via a GET Request:</h3>
<ul>
Expand All @@ -33,23 +30,23 @@
<h3>Initiating one of the following OAuth2 Grant Mechanism via a POST Request:</h3>
<ul>
<li>
<form method="POST" action="<?php echo $subFolder;?>/v2/oauth2/authorize">
<form method="POST" action="<?php echo $authUrl; ?>">
<input type="hidden" name="api_key" value="<?php echo $api_key; ?>" />
<input type="hidden" name="response_type" value="code" />
<input type="hidden" name="redirect_uri" value="<?php echo $base_url."/endpoints/authcode_endpoint.php";?>" />
<input type="hidden" name="redirect_uri" value="<?php echo $authGrantRedirect; ?>" />
<input type="submit" value="Authorization Code Grant" />
</form>
</li>
<li>
<form method="POST" action="<?php echo $subFolder;?>/v2/oauth2/authorize">
<form method="POST" action="<?php echo $authUrl; ?>">
<input type="hidden" name="api_key" value="<?php echo $api_key; ?>" />
<input type="hidden" name="response_type" value="token" />
<input type="hidden" name="redirect_uri" value="<?php echo $base_url."/endpoints/implicitgrant_endpoint.php"; ?>" />
<input type="hidden" name="redirect_uri" value="<?php echo $implicitGrantRedirect; ?>" />
<input type="submit" value="Implicit Grant" />
</form>
</li>
<li>
<form method="POST" action="<?php echo $subFolder;?>/v2/oauth2/token">
<form method="POST" action="<?php echo $tokenUrl; ?>">
<input type="hidden" name="grant_type" value="client_credentials" />
<input type="hidden" name="scope" value="" />
<input type="hidden" name="api_key" value="<?php echo $api_key; ?>" />
Expand All @@ -58,7 +55,7 @@
</form>
</li>
<li>
<form method="POST" action="<?php echo $subFolder;?>/v2/oauth2/token">
<form method="POST" action="<?php echo $tokenUrl;?>">
<div>
<input type="hidden" name="grant_type" value="password" />
<input type="hidden" name="scope" value="" />
Expand Down

0 comments on commit 99af4fb

Please sign in to comment.