function handleOAuthBodyPOST($oauth_consumer_key, $oauth_consumer_secret) { $request_headers = OAuthUtil::get_headers(); // print_r($request_headers); // Must reject application/x-www-form-urlencoded if ($request_headers['Content-type'] == 'application/x-www-form-urlencoded' ) { throw new Exception("OAuth request body signing must not use application/x-www-form-urlencoded"); } if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") { $header_parameters = OAuthUtil::split_header($request_headers['Authorization']); // echo("HEADER PARMS=\n"); // print_r($header_parameters); $oauth_body_hash = $header_parameters['oauth_body_hash']; // echo("OBH=".$oauth_body_hash."\n"); } if ( ! isset($oauth_body_hash) ) { throw new Exception("OAuth request body signing requires oauth_body_hash body"); } // Verify the message signature $store = new TrivialOAuthDataStore(); $store->add_consumer($oauth_consumer_key, $oauth_consumer_secret); $server = new OAuthServer($store); $method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($method); $request = OAuthRequest::from_request(); global $LastOAuthBodyBaseString; $LastOAuthBodyBaseString = $request->get_signature_base_string(); // echo($LastOAuthBodyBaseString."\n"); try { $server->verify_request($request); } catch (Exception $e) { $message = $e->getMessage(); throw new Exception("OAuth signature failed: " . $message); } $postdata = file_get_contents('php://input'); // echo($postdata); $hash = base64_encode(sha1($postdata, TRUE)); if ( $hash != $oauth_body_hash ) { throw new Exception("OAuth oauth_body_hash mismatch"); } return $postdata; }
/** * Create new Basic LTI access object * * @param string $key * @param string $secret * * @throws \Exception */ public function __construct($key, $secret) { $request = \OAuthRequest::from_request(); $oauth_consumer_key = $request->get_parameter("oauth_consumer_key"); // ensure the key in the request matches the locally supplied one if ($oauth_consumer_key == null) { throw new \Exception("Missing oauth_consumer_key in request"); } if ($oauth_consumer_key != $key) { throw new \Exception("oauth_consumer_key doesn't match supplied key"); } // verify the message signature $store = new TrivialOAuthDataStore($oauth_consumer_key, $secret); $server = new \OAuthServer($store); $method = new \OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($method); $server->verify_request($request); $this->request = $request; }
function handle_oauth_body_post($oauthconsumerkey, $oauthconsumersecret, $body, $requestheaders = null) { if ($requestheaders == null) { $requestheaders = OAuthUtil::get_headers(); } // Must reject application/x-www-form-urlencoded. if (isset($requestheaders['Content-type'])) { if ($requestheaders['Content-type'] == 'application/x-www-form-urlencoded') { throw new OAuthException("OAuth request body signing must not use application/x-www-form-urlencoded"); } } if (@substr($requestheaders['Authorization'], 0, 6) == "OAuth ") { $headerparameters = OAuthUtil::split_header($requestheaders['Authorization']); $oauthbodyhash = $headerparameters['oauth_body_hash']; } if (!isset($oauthbodyhash)) { throw new OAuthException("OAuth request body signing requires oauth_body_hash body"); } // Verify the message signature. $store = new TrivialOAuthDataStore(); $store->add_consumer($oauthconsumerkey, $oauthconsumersecret); $server = new OAuthServer($store); $method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($method); $request = OAuthRequest::from_request(); try { $server->verify_request($request); } catch (\Exception $e) { $message = $e->getMessage(); throw new OAuthException("OAuth signature failed: " . $message); } $postdata = $body; $hash = base64_encode(sha1($postdata, true)); if ($hash != $oauthbodyhash) { throw new OAuthException("OAuth oauth_body_hash mismatch"); } return $postdata; }
function __construct($parm = false, $usesession = true, $doredirect = true) { global $link; $this->message = "blti loaded"; // If this request is not an LTI Launch, either // give up or try to retrieve the context from session if (!is_basic_lti_request()) { if ($usesession === false) { return; } if (strlen(session_id()) > 0) { $row = $_SESSION['_basiclti_lti_row']; if (isset($row)) { $this->row = $row; } $context_id = $_SESSION['_basiclti_lti_context_id']; if (isset($context_id)) { $this->context_id = $context_id; } $info = $_SESSION['_basic_lti_context']; if (isset($info)) { $this->info = $info; $this->valid = true; return; } $this->message = "Could not find context in session"; return; } $this->message = "Session not available"; return; } // Insure we have a valid launch if (empty($_REQUEST["oauth_consumer_key"])) { $this->message = "Missing oauth_consumer_key in request"; return; } $oauth_consumer_key = $_REQUEST["oauth_consumer_key"]; // Find the secret - either from the parameter as a string or // look it up in a database from parameters we are given $secret = false; $row = false; if (is_string($parm)) { $secret = $parm; } else { if (!is_array($parm)) { $this->message = "Constructor requires a secret or database information."; return; } else { //changelog: parms -> parm (typo) throughout $sql = 'SELECT * FROM ' . $parm['table'] . ' WHERE ' . ($parm['key_column'] ? $parm['key_column'] : 'oauth_consumer_key') . '=' . "'" . mysqli_real_escape_string($link, $oauth_consumer_key) . "'"; $result = mysqli_query($link, $sql); //echo $sql; $num_rows = mysqli_num_rows($result); if ($num_rows != 1) { $this->message = "Your consumer is not authorized oauth_consumer_key=" . $oauth_consumer_key . " " . $sql; return; } else { while ($row = mysqli_fetch_assoc($result)) { $secret = $row[$parm['secret_column'] ? $parm['secret_column'] : 'secret']; $context_id = $row[$parm['context_column'] ? $parm['context_column'] : 'context_id']; if ($context_id) { $this->context_id = $context_id; } //changelog: look for token. probably get rid of this at some point, since I've separated the key/secret table from tokens //if($row['token'] !="")$token = $_SESSION['token']=$row['token']; //setcookie("ttable",$parm['table']);//use this to update bad tokens in get_token_domain $this->row = $row; break; } if (!is_string($secret)) { $this->message = "Could not retrieve secret oauth_consumer_key=" . $oauth_consumer_key; return; } } } } // Verify the message signature $store = new TrivialOAuthDataStore(); $store->add_consumer($oauth_consumer_key, $secret); $server = new OAuthServer($store); $method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($method); $request = OAuthRequest::from_request(); $this->basestring = $request->get_signature_base_string(); try { $server->verify_request($request); $this->valid = true; } catch (Exception $e) { $this->message = $e->getMessage(); return; } // Store the launch information in the session for later $newinfo = array(); foreach ($_POST as $key => $value) { if ($key == "basiclti_submit") { continue; } if (strpos($key, "oauth_") === false) { $newinfo[$key] = $value; continue; } if ($key == "oauth_consumer_key") { $newinfo[$key] = $value; continue; } } $this->info = $newinfo; if ($usesession == true and strlen(session_id()) > 0) { $_SESSION['_basic_lti_context'] = $this->info; unset($_SESSION['_basiclti_lti_row']); unset($_SESSION['_basiclti_lti_context_id']); if ($this->row) { $_SESSION['_basiclti_lti_row'] = $this->row; } if ($this->context_id) { $_SESSION['_basiclti_lti_context_id'] = $this->context_id; } } if ($this->valid && $doredirect) { $this->redirect(); $this->complete = true; } }
/** * Function to initilise the lti class * @param bool $usesession * @param bool $doredirect * @return */ public function init_lti($usesession = true, $doredirect = false) { if (!isset($_REQUEST["lti_message_type"])) { $_REQUEST["lti_message_type"] = ''; } if (!isset($_REQUEST["lti_version"])) { $_REQUEST["lti_version"] = ''; } if (!isset($_REQUEST["resource_link_id"])) { $_REQUEST["resource_link_id"] = ''; } // If this request is not an LTI Launch, either // give up or try to retrieve the context from session if (!is_lti_request()) { if ($usesession === false) { return; } if (strlen(session_id()) > 0) { if (isset($_SESSION['_lti_row'])) { $row = $_SESSION['_lti_row']; } if (isset($row)) { $this->row = $row; } if (isset($_SESSION['_lti_context_id'])) { $context_id = $_SESSION['_lti_context_id']; } if (isset($context_id)) { $this->context_id = $context_id; } if (isset($_SESSION['_lti_context'])) { $info = $_SESSION['_lti_context']; } if (isset($info)) { $this->info = $info; $this->valid = true; return; } $this->message = "Could not find context in session"; return; } $this->message = "Session not available"; return; } // Insure we have a valid launch if (empty($_REQUEST["oauth_consumer_key"])) { $this->message = "Missing oauth_consumer_key in request"; return; } $oauth_consumer_key = $_REQUEST["oauth_consumer_key"]; // Find the secret - either form the parameter as a string or // look it up in a database from parameters we are given $secret = false; $row = false; if (is_string($this->parm)) { $secret = $this->parm; } else { if (!is_array($this->parm)) { $this->message = "Constructor requires a secret or database information."; return; } else { if ($this->parm['dbtype'] == 'mysql') { $sql = 'SELECT * FROM ' . ($this->parm['table'] ? $this->parm['table'] : 'lti_keys') . ' WHERE ' . ($this->parm['key_column'] ? $this->parm['key_column'] : 'oauth_consumer_key') . '=' . "'" . mysql_real_escape_string($oauth_consumer_key) . "'"; $result = mysql_query($sql); $num_rows = mysql_num_rows($result); if ($num_rows != 1) { $this->message = "Your consumer is not authorized oauth_consumer_key=" . $oauth_consumer_key; return; } else { while ($row = mysql_fetch_assoc($result)) { $secret = $row[$this->parms['secret_column'] ? $this->parms['secret_column'] : 'secret']; $context_id = $row[$this->parms['context_column'] ? $this->parms['context_column'] : 'context_id']; if ($context_id) { $this->context_id = $context_id; } $this->row = $row; break; } if (!is_string($secret)) { $this->message = "Could not retrieve secret oauth_consumer_key=" . $oauth_consumer_key; return; } } } elseif ($this->parm['dbtype'] == 'mysqli') { if ($this->db->error) { try { throw new Exception("0MySQL error {$mysqli->error} <br> Query:<br> {$query}", $msqli->errno); } catch (Exception $e) { echo "Error No: " . $e->getCode() . " - " . $e->getMessage() . "<br >"; echo nl2br($e->getTraceAsString()); } } $stmt = $this->db->prepare("SELECT secret,context_id,name FROM " . $this->parm['table_prefix'] . "lti_keys WHERE oauth_consumer_key=? AND `deleted` IS NULL"); $db = $this->db; if ($db->error) { try { throw new Exception("0MySQL error {$db->error} <br> Query:<br> ", $db->errno); } catch (Exception $e) { echo "Error No: " . $e->getCode() . " - " . $e->getMessage() . "<br >"; echo nl2br($e->getTraceAsString()); exit; } } $stmt->bind_param('s', $oauth_consumer_key); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($rsecret, $rcontext_id, $rname); $stmt->fetch(); $secret = $rsecret; $name = $rname; if (isset($rcontext_id)) { $this->context_id = $rcontext_id; } $stmt->close(); if (!is_string($secret)) { $this->message = "Could not retrieve secret oauth_consumer_key=" . $oauth_consumer_key; return; } } } } // Verify the message signature $store = new TrivialOAuthDataStore(); $store->add_consumer($oauth_consumer_key, $secret); $server = new OAuthServer($store); $method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($method); $request = OAuthRequest::from_request(); $this->basestring = $request->get_signature_base_string(); try { $server->verify_request($request); $this->valid = true; } catch (Exception $e) { $this->message = $e->getMessage(); return; } // Store the launch information in the session for later $newinfo = array(); foreach ($_POST as $key => $value) { if ($key == "basiclti_submit") { continue; } if (strpos($key, "oauth_") === false) { $newinfo[$key] = $value; continue; } if ($key == "oauth_consumer_key") { $newinfo[$key] = $value; continue; } } $newinfo['oauth_consumer_secret'] = $secret; $this->info = $newinfo; if ($usesession == true and strlen(session_id()) > 0) { $_SESSION['_lti_context'] = $this->info; unset($_SESSION['_lti_row']); unset($_SESSION['_lti_context_id']); if ($this->row) { $_SESSION['_lti_row'] = $this->row; } if ($this->context_id) { $_SESSION['_lti_context_id'] = $this->context_id; } } if ($this->valid && $doredirect) { $this->redirect(); $this->complete = true; } }
/** * Check the authenticity of the LTI launch request. * * The consumer, resource link and user objects will be initialised if the request is valid. * * @return boolean True if the request has been successfully validated. */ protected function _authenticate() { if (!$this->Provider->isOK) { return false; } try { $this->loadModel('Lti.OAuthStore'); $store = new OAuthStore($this->Provider, $this->Consumer); $server = new OAuthServer($this->OAuthStore); $method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($method); $request = OAuthRequest::from_request(); $res = $server->verify_request($request); } catch (Exception $e) { $this->Provider->isOK = FALSE; if (empty($this->Provider->reason)) { if ($this->Provider->debugMode) { $oconsumer = new OAuthConsumer($this->Consumer->consumer_key, $this->Consumer->secret); $signature = $request->build_signature($method, $oconsumer, FALSE); $this->Provider->reason = $e->getMessage(); if (empty($this->Provider->reason)) { $this->Provider->reason = 'OAuth exception'; } $this->Provider->details[] = 'Timestamp: ' . time(); $this->Provider->details[] = "Signature: {$signature}"; $this->Provider->details[] = "Base string: {$request->base_string}]"; } else { $this->Provider->reason = 'OAuth signature check failed - perhaps an incorrect secret or timestamp.'; } } return false; } return true; }
/** * The 'clasic' 3 legged OAuth, where the user went through the OAuth dance and granted the remote app * access to his/her data. */ private function verify3LeggedOAuth($oauthRequest, $userId, $appUrl, $dataStore) { $server = new OAuthServer($dataStore); $server->add_signature_method(new OAuthSignatureMethod_HMAC_SHA1()); $server->add_signature_method(new OAuthSignatureMethod_PLAINTEXT()); list($consumer, $token) = $server->verify_request($oauthRequest); $oauthUserId = $dataStore->get_user_id($token); if ($userId && $oauthUserId && $oauthUserId != $userId) { return null; // xoauth_requestor_id was provided, but does not match oauth token -> fail } else { $userId = $oauthUserId; // use userId from oauth token return new OAuthSecurityToken($userId, $appUrl, 0, "partuza"); } }
if ( ! isset($oauth_consumer_key) ) doError("Not permitted"); // Verify the message signature $store = new TrivialOAuthDataStore(); $store->add_consumer($oauth_consumer_key, $oauth_secret); $server = new OAuthServer($store); $method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($method); $request = OAuthRequest::from_request(); $basestring = $request->get_signature_base_string(); try { $server->verify_request($request); } catch (Exception $e) { doError($e->getMessage()); } // Beginning of actual grade processing if ( $message_type == "basicoutcome" ) { if ( ! isset( $basiclti_content_row['gradebook_test_id'] ) ) { doError("Not permitted"); } // TODO: Greg - Is this appropriate? It would be nice to allow this. if ( $atutor_course_membership_row['role'] == 'Instructor' ) { doError('Grades not supported for instructors'); }
/** * Verifies the OAuth request signature, sets the auth user * and access type (read-only or read-write) * * @param OAuthRequest $request the OAuth Request * * @return nothing */ function checkOAuthRequest($request) { $datastore = new ApiStatusNetOAuthDataStore(); $server = new OAuthServer($datastore); $hmac_method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($hmac_method); try { $server->verify_request($request); $consumer = $request->get_parameter('oauth_consumer_key'); $access_token = $request->get_parameter('oauth_token'); $app = Oauth_application::getByConsumerKey($consumer); if (empty($app)) { common_log(LOG_WARNING, 'Couldn\'t find the OAuth app for consumer key: ' . $consumer); throw new OAuthException('No application for that consumer key.'); } // set the source attr $this->source = $app->name; $appUser = Oauth_application_user::staticGet('token', $access_token); if (!empty($appUser)) { // If access_type == 0 we have either a request token // or a bad / revoked access token if ($appUser->access_type != 0) { // Set the access level for the api call $this->access = $appUser->access_type & Oauth_application::$writeAccess ? self::READ_WRITE : self::READ_ONLY; // Set the auth user if (Event::handle('StartSetApiUser', array(&$user))) { $this->auth_user = User::staticGet('id', $appUser->profile_id); Event::handle('EndSetApiUser', array($user)); } $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " . "application '%s' (id: %d) with %s access."; common_log(LOG_INFO, sprintf($msg, $this->auth_user->nickname, $this->auth_user->id, $app->name, $app->id, ($this->access = self::READ_WRITE) ? 'read-write' : 'read-only')); } else { throw new OAuthException('Bad access token.'); } } else { // Also should not happen throw new OAuthException('No user for that token.'); } } catch (OAuthException $e) { common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage()); $this->clientError($e->getMessage(), 401, $this->format); exit; } }
echo "BasicLTI not enabled"; exit; } //check OAuth Signature! require_once '../includes/OAuth.php'; require_once '../includes/ltioauthstore.php'; //set up OAuth $LTImode = "consumer"; $store = new IMathASLTIOAuthDataStore(); $server = new OAuthServer($store); $method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($method); $request = OAuthRequest::from_request(); $base = $request->get_signature_base_string(); try { $requestinfo = $server->verify_request($request); } catch (Exception $e) { echo 'Invalid credentials'; //fwrite($fp, "Invalid credentials\n"); exit; } $store->mark_nonce_used($request); //signature checks out. Proceed $xml = file_get_contents('php://input'); //fwrite($fp, "sig OK. XML: ".$xml."\n"); preg_match('/<imsx_messageIdentifier>\\s*(.*?)\\s*<\\/imsx_messageIdentifier>/is', $xml, $matches); $msgid = $matches[1]; if (strpos($xml, 'replaceResultRequest') !== false) { preg_match('/<sourcedId>\\s*(.*?)\\s*<\\/sourcedId>.*?<textString>\\s*(.*?)<\\/textString>/is', $xml, $matches); list($sig, $rlid, $userid) = explode('::', $matches[1]); if (!is_numeric($matches[2])) {
/** * Validates the signature of the current request * * @access protected * @author Joel Bout, <*****@*****.**> * @param common_http_Request request * @throws common_Exception exception thrown if validation fails */ public function validate(common_http_Request $request, common_http_Credentials $credentials = null) { $server = new OAuthServer(new tao_models_classes_oauth_DataStore()); $method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($method); try { $oauthRequest = $this->getOauthRequest($request); $server->verify_request($oauthRequest); } catch (OAuthException $e) { throw new common_http_InvalidSignatureException('Validation failed: ' . $e->getMessage()); } }
/** * Check the authenticity of the LTI launch request. * * The consumer, resource link and user objects will be initialised if the request is valid. * * @return boolean True if the request has been successfully validated. */ private function authenticate() { # ### Get the consumer # $doSaveConsumer = FALSE; // Check all required launch parameters $this->isOK = isset($_POST['lti_message_type']) && array_key_exists($_POST['lti_message_type'], $this->messageTypes); if (!$this->isOK) { $this->reason = 'Invalid or missing lti_message_type parameter.'; } if ($this->isOK) { $this->isOK = isset($_POST['lti_version']) && in_array($_POST['lti_version'], $this->LTI_VERSIONS); if (!$this->isOK) { $this->reason = 'Invalid or missing lti_version parameter.'; } } if ($this->isOK) { if ($_POST['lti_message_type'] == 'basic-lti-launch-request' || $_POST['lti_message_type'] == 'DashboardRequest') { $this->isOK = isset($_POST['resource_link_id']) && strlen(trim($_POST['resource_link_id'])) > 0; if (!$this->isOK) { $this->reason = 'Missing resource link ID.'; } } else { if ($_POST['lti_message_type'] == 'ContentItemSelectionRequest') { if (isset($_POST['accept_media_types']) && strlen(trim($_POST['accept_media_types'])) > 0) { $mediaTypes = array_filter(explode(',', str_replace(' ', '', $_POST['accept_media_types'])), 'strlen'); $mediaTypes = array_unique($mediaTypes); $this->isOK = count($mediaTypes) > 0; if (!$this->isOK) { $this->reason = 'No accept_media_types found.'; } else { $this->mediaTypes = $mediaTypes; } } else { $this->isOK = FALSE; } if ($this->isOK && isset($_POST['accept_presentation_document_targets']) && strlen(trim($_POST['accept_presentation_document_targets'])) > 0) { $documentTargets = array_filter(explode(',', str_replace(' ', '', $_POST['accept_presentation_document_targets'])), 'strlen'); $documentTargets = array_unique($documentTargets); $this->isOK = count($documentTargets) > 0; if (!$this->isOK) { $this->reason = 'Missing or empty accept_presentation_document_targets parameter.'; } else { foreach ($documentTargets as $documentTarget) { $this->isOK = $this->checkValue($documentTarget, array('embed', 'frame', 'iframe', 'window', 'popup', 'overlay', 'none'), 'Invalid value in accept_presentation_document_targets parameter: %s.'); if (!$this->isOK) { break; } } if ($this->isOK) { $this->documentTargets = $documentTargets; } } } else { $this->isOK = FALSE; } if ($this->isOK) { $this->isOK = isset($_POST['content_item_return_url']) && strlen(trim($_POST['content_item_return_url'])) > 0; if (!$this->isOK) { $this->reason = 'Missing content_item_return_url parameter.'; } } } } } // Check consumer key if ($this->isOK) { $this->isOK = isset($_POST['oauth_consumer_key']); if (!$this->isOK) { $this->reason = 'Missing consumer key.'; } } if ($this->isOK) { $this->consumer = new LTI_Tool_Consumer($_POST['oauth_consumer_key'], $this->data_connector); $this->isOK = !is_null($this->consumer->created); if (!$this->isOK) { $this->reason = 'Invalid consumer key.'; } } $now = time(); if ($this->isOK) { $today = date('Y-m-d', $now); if (is_null($this->consumer->last_access)) { $doSaveConsumer = TRUE; } else { $last = date('Y-m-d', $this->consumer->last_access); $doSaveConsumer = $doSaveConsumer || $last != $today; } $this->consumer->last_access = $now; try { $store = new LTI_OAuthDataStore($this); $server = new OAuthServer($store); $method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($method); $request = OAuthRequest::from_request(); $res = $server->verify_request($request); } catch (Exception $e) { $this->isOK = FALSE; if (empty($this->reason)) { if ($this->debugMode) { $consumer = new OAuthConsumer($this->consumer->getKey(), $this->consumer->secret); $signature = $request->build_signature($method, $consumer, FALSE); $this->reason = $e->getMessage(); if (empty($this->reason)) { $this->reason = 'OAuth exception'; } $this->details[] = 'Timestamp: ' . time(); $this->details[] = "Signature: {$signature}"; $this->details[] = "Base string: {$request->base_string}]"; } else { $this->reason = 'OAuth signature check failed - perhaps an incorrect secret or timestamp.'; } } } } if ($this->isOK && $this->consumer->protected) { if (!is_null($this->consumer->consumer_guid)) { $this->isOK = isset($_POST['tool_consumer_instance_guid']) && !empty($_POST['tool_consumer_instance_guid']) && $this->consumer->consumer_guid == $_POST['tool_consumer_instance_guid']; if (!$this->isOK) { $this->reason = 'Request is from an invalid tool consumer.'; } } else { $this->isOK = isset($_POST['tool_consumer_instance_guid']); if (!$this->isOK) { $this->reason = 'A tool consumer GUID must be included in the launch request.'; } } } if ($this->isOK) { $this->isOK = $this->consumer->enabled; if (!$this->isOK) { $this->reason = 'Tool consumer has not been enabled by the tool provider.'; } } if ($this->isOK) { $this->isOK = is_null($this->consumer->enable_from) || $this->consumer->enable_from <= $now; if ($this->isOK) { $this->isOK = is_null($this->consumer->enable_until) || $this->consumer->enable_until > $now; if (!$this->isOK) { $this->reason = 'Tool consumer access has expired.'; } } else { $this->reason = 'Tool consumer access is not yet available.'; } } # ### Validate other message parameter values # if ($this->isOK) { if ($_POST['lti_message_type'] != 'ContentItemSelectionRequest') { if (isset($_POST['launch_presentation_document_target'])) { $this->isOK = $this->checkValue($_POST['launch_presentation_document_target'], array('embed', 'frame', 'iframe', 'window', 'popup', 'overlay'), 'Invalid value for launch_presentation_document_target parameter: %s.'); } } else { if (isset($_POST['accept_unsigned'])) { $this->isOK = $this->checkValue($_POST['accept_unsigned'], array('true', 'false'), 'Invalid value for accept_unsigned parameter: %s.'); } if ($this->isOK && isset($_POST['accept_multiple'])) { $this->isOK = $this->checkValue($_POST['accept_multiple'], array('true', 'false'), 'Invalid value for accept_multiple parameter: %s.'); } if ($this->isOK && isset($_POST['accept_copy_advice'])) { $this->isOK = $this->checkValue($_POST['accept_copy_advice'], array('true', 'false'), 'Invalid value for accept_copy_advice parameter: %s.'); } if ($this->isOK && isset($_POST['auto_create'])) { $this->isOK = $this->checkValue($_POST['auto_create'], array('true', 'false'), 'Invalid value for auto_create parameter: %s.'); } if ($this->isOK && isset($_POST['can_confirm'])) { $this->isOK = $this->checkValue($_POST['can_confirm'], array('true', 'false'), 'Invalid value for can_confirm parameter: %s.'); } } } # ### Validate message parameter constraints # if ($this->isOK) { $invalid_parameters = array(); foreach ($this->constraints as $name => $constraint) { if (empty($constraint['messages']) || in_array($_POST['lti_message_type'], $constraint['messages'])) { $ok = TRUE; if ($constraint['required']) { if (!isset($_POST[$name]) || strlen(trim($_POST[$name])) <= 0) { $invalid_parameters[] = "{$name} (missing)"; $ok = FALSE; } } if ($ok && !is_null($constraint['max_length']) && isset($_POST[$name])) { if (strlen(trim($_POST[$name])) > $constraint['max_length']) { $invalid_parameters[] = "{$name} (too long)"; } } } } if (count($invalid_parameters) > 0) { $this->isOK = FALSE; if (empty($this->reason)) { $this->reason = 'Invalid parameter(s): ' . implode(', ', $invalid_parameters) . '.'; } } } if ($this->isOK) { # ### Set the request context/resource link # if (isset($_POST['resource_link_id'])) { $content_item_id = ''; if (isset($_POST['custom_content_item_id'])) { $content_item_id = $_POST['custom_content_item_id']; } $this->resource_link = new LTI_Resource_Link($this->consumer, trim($_POST['resource_link_id']), $content_item_id); if (isset($_POST['context_id'])) { $this->resource_link->lti_context_id = trim($_POST['context_id']); } $this->resource_link->lti_resource_id = trim($_POST['resource_link_id']); $title = ''; if (isset($_POST['context_title'])) { $title = trim($_POST['context_title']); } if (isset($_POST['resource_link_title']) && strlen(trim($_POST['resource_link_title'])) > 0) { if (!empty($title)) { $title .= ': '; } $title .= trim($_POST['resource_link_title']); } if (empty($title)) { $title = "Course {$this->resource_link->getId()}"; } $this->resource_link->title = $title; // Save LTI parameters foreach ($this->lti_settings_names as $name) { if (isset($_POST[$name])) { $this->resource_link->setSetting($name, $_POST[$name]); } else { $this->resource_link->setSetting($name, NULL); } } // Delete any existing custom parameters foreach ($this->resource_link->getSettings() as $name => $value) { if (strpos($name, 'custom_') === 0) { $this->resource_link->setSetting($name); } } // Save custom parameters foreach ($_POST as $name => $value) { if (strpos($name, 'custom_') === 0) { $this->resource_link->setSetting($name, $value); } } } # ### Set the user instance # $user_id = ''; if (isset($_POST['user_id'])) { $user_id = trim($_POST['user_id']); } $this->user = new LTI_User($this->resource_link, $user_id); # ### Set the user name # $firstname = isset($_POST['lis_person_name_given']) ? $_POST['lis_person_name_given'] : ''; $lastname = isset($_POST['lis_person_name_family']) ? $_POST['lis_person_name_family'] : ''; $fullname = isset($_POST['lis_person_name_full']) ? $_POST['lis_person_name_full'] : ''; $this->user->setNames($firstname, $lastname, $fullname); # ### Set the user email # $email = isset($_POST['lis_person_contact_email_primary']) ? $_POST['lis_person_contact_email_primary'] : ''; $this->user->setEmail($email, $this->defaultEmail); # ### Set the user roles # if (isset($_POST['roles'])) { $this->user->roles = LTI_Tool_Provider::parseRoles($_POST['roles']); } # ### Save the user instance # if (isset($_POST['lis_result_sourcedid'])) { if ($this->user->lti_result_sourcedid != $_POST['lis_result_sourcedid']) { $this->user->lti_result_sourcedid = $_POST['lis_result_sourcedid']; $this->user->save(); } } else { if (!empty($this->user->lti_result_sourcedid)) { $this->user->delete(); } } # ### Initialise the consumer and check for changes # $this->consumer->defaultEmail = $this->defaultEmail; if ($this->consumer->lti_version != $_POST['lti_version']) { $this->consumer->lti_version = $_POST['lti_version']; $doSaveConsumer = TRUE; } if (isset($_POST['tool_consumer_instance_name'])) { if ($this->consumer->consumer_name != $_POST['tool_consumer_instance_name']) { $this->consumer->consumer_name = $_POST['tool_consumer_instance_name']; $doSaveConsumer = TRUE; } } if (isset($_POST['tool_consumer_info_product_family_code'])) { $version = $_POST['tool_consumer_info_product_family_code']; if (isset($_POST['tool_consumer_info_version'])) { $version .= "-{$_POST['tool_consumer_info_version']}"; } // do not delete any existing consumer version if none is passed if ($this->consumer->consumer_version != $version) { $this->consumer->consumer_version = $version; $doSaveConsumer = TRUE; } } else { if (isset($_POST['ext_lms']) && $this->consumer->consumer_name != $_POST['ext_lms']) { $this->consumer->consumer_version = $_POST['ext_lms']; $doSaveConsumer = TRUE; } } if (isset($_POST['tool_consumer_instance_guid'])) { if (is_null($this->consumer->consumer_guid)) { $this->consumer->consumer_guid = $_POST['tool_consumer_instance_guid']; $doSaveConsumer = TRUE; } else { if (!$this->consumer->protected) { $doSaveConsumer = $this->consumer->consumer_guid != $_POST['tool_consumer_instance_guid']; if ($doSaveConsumer) { $this->consumer->consumer_guid = $_POST['tool_consumer_instance_guid']; } } } } if (isset($_POST['launch_presentation_css_url'])) { if ($this->consumer->css_path != $_POST['launch_presentation_css_url']) { $this->consumer->css_path = $_POST['launch_presentation_css_url']; $doSaveConsumer = TRUE; } } else { if (isset($_POST['ext_launch_presentation_css_url']) && $this->consumer->css_path != $_POST['ext_launch_presentation_css_url']) { $this->consumer->css_path = $_POST['ext_launch_presentation_css_url']; $doSaveConsumer = TRUE; } else { if (!empty($this->consumer->css_path)) { $this->consumer->css_path = NULL; $doSaveConsumer = TRUE; } } } } # ### Persist changes to consumer # if ($doSaveConsumer) { $this->consumer->save(); } if ($this->isOK && isset($this->resource_link)) { # ### Check if a share arrangement is in place for this resource link # $this->isOK = $this->checkForShare(); # ### Persist changes to resource link # $this->resource_link->save(); } return $this->isOK; }
/** * Check the reqest signature * @return mixed Exception or true */ private function checkSignature($a_key, $a_secret) { require_once $this->plugin_path . '/lib/OAuth.php'; require_once $this->plugin_path . '/lib/TrivialOAuthDataStore.php'; $store = new TrivialOAuthDataStore(); $store->add_consumer($this->fields['KEY'], $this->fields['SECRET']); $server = new OAuthServer($store); $method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($method); $request = OAuthRequest::from_request(); try { $server->verify_request($request); } catch (Exception $e) { return $e; } return true; }
function __construct($consumer = false, $shared_secret = false, $usesession = true, $doredirect = true) { // If this request is not an LTI Launch, either // give up or try to retrieve the context from session $myKeys[$consumer] = $shared_secret; if (!is_basic_lti_request()) { if ($usesession === false) { return; } if (strlen(session_id()) > 0) { $row = $_SESSION['_basiclti_lti_row']; if (isset($row)) { $this->row = $row; } $context_id = $_SESSION['_basiclti_lti_context_id']; if (isset($context_id)) { $this->context_id = $context_id; } $info = $_SESSION['_basic_lti_context']; if (isset($info)) { $this->info = $info; $this->valid = true; return; } $this->message = "Could not find context in session"; return; } $this->message = "Session not available"; return; } // Insure we have a valid launch if (empty($_REQUEST["oauth_consumer_key"])) { $this->message = "Missing oauth_consumer_key in request"; return; } $oauth_consumer_key = $_REQUEST["oauth_consumer_key"]; // Find the secret - either form the parameter as a string or // look it up in a database from parameters we are given $secret = false; $row = false; if (is_string($consumer)) { $secret = $consumer; } else { $secret = $keys['secret']; // echo "SECRET: " . $secret; } $secret = $myKeys[$oauth_consumer_key]; // echo "SECRET: " . $secret; // Verify the message signature $store = new TrivialOAuthDataStore(); $store->add_consumer($oauth_consumer_key, $secret); $server = new OAuthServer($store); $method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($method); $request = OAuthRequest::from_request(); $this->basestring = $request->get_signature_base_string(); //echo $this->basestring; try { $server->verify_request($request); $this->valid = true; } catch (Exception $e) { $this->message = $e->getMessage(); return; } // Store the launch information in the session for later $newinfo = array(); foreach ($_POST as $key => $value) { if ($key == "basiclti_submit") { continue; } if (strpos($key, "oauth_") === false) { $newinfo[$key] = $value; continue; } if ($key == "oauth_consumer_key") { $newinfo[$key] = $value; continue; } } $this->info = $newinfo; if ($usesession == true and strlen(session_id()) > 0) { $_SESSION['_basic_lti_context'] = $this->info; unset($_SESSION['_basiclti_lti_row']); unset($_SESSION['_basiclti_lti_context_id']); if ($this->row) { $_SESSION['_basiclti_lti_row'] = $this->row; } if ($this->context_id) { $_SESSION['_basiclti_lti_context_id'] = $this->context_id; } } if ($this->valid && $doredirect) { $this->redirect(); $this->complete = true; } }
/** * Tries to authenticate the LTI launch request based on the provided launch parameters. * * @return bool True if authenticated, otherwise false. */ public function isAuthenticated() { // Check if a consumer key was provided. If not, we have nothing to authenticate and therefore return false. if (!empty($this->launchParams["oauth_consumer_key"])) { // Check if a data store of consumer secrets has been set. If not, authentication has been disabled. if (!isset($this->consumerSecrets)) { return true; } // Perform OAuth verification on the launch parameters. $server = new OAuthServer($this->consumerSecrets); $server->add_signature_method(new OAuthSignatureMethod_HMAC_SHA1()); $request = OAuthRequest::from_request(null, null, $_REQUEST); try { $server->verify_request($request); return true; } catch (Exception $ex) { if (Config::get("debug")) { exit($ex); } return false; } } return false; }
private function authenticate() { # ### Set debug mode # $this->debugMode = isset($_REQUEST['custom_debug']); # ### Get the consumer instance # $this->isOK = isset($_REQUEST['oauth_consumer_key']); if ($this->isOK) { $this->consumer_instance = new LTI_Tool_Consumer_Instance($_REQUEST['oauth_consumer_key'], $this->dbTableNamePrefix); $this->isOK = $this->consumer_instance->isEnabled(); if ($this->debugMode && !$this->isOK) { $this->reason = 'Tool consumer instance has not been enabled by the tool provider.'; } } if ($this->isOK) { try { $store = new LTI_OAuthDataStore($this); $server = new OAuthServer($store); $method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($method); $request = OAuthRequest::from_request(); $res = $server->verify_request($request); } catch (Exception $e) { $this->isOK = FALSE; if (empty($this->reason)) { $this->reason = 'OAuth signature check failed - perhaps an incorrect secret.'; } } } if ($this->isOK) { $this->consumer_instance->defaultEmail = $this->defaultEmail; # ### Set the request context # if (isset($_REQUEST['resource_link_id'])) { $id = trim($_REQUEST['resource_link_id']); } else { $id = trim($_REQUEST['context_id']); } $this->context = new LTI_Context($this->consumer_instance, $id); if (isset($_REQUEST['context_id'])) { $this->context->lti_context_id = trim($_REQUEST['context_id']); } if (isset($_REQUEST['resource_link_id'])) { $this->context->lti_resource_id = trim($_REQUEST['resource_link_id']); } $title = ''; if (isset($_REQUEST['context_title'])) { $title = trim($_REQUEST['context_title']); } if (isset($_REQUEST['resource_link_title']) && strlen(trim($_REQUEST['resource_link_title'])) > 0) { if (!empty($title)) { $title .= ': '; } $title .= trim($_REQUEST['resource_link_title']); } if (empty($title)) { $title = "Course {$this->context->id}"; } $this->context->title = $title; // Save LTI parameters foreach ($this->lti_settings_names as $name) { if (isset($_REQUEST[$name])) { $this->context->setSetting($name, $_REQUEST[$name]); } else { $this->context->setSetting($name, NULL); } } // Delete any existing custom parameters foreach ($this->context->getSettings() as $name => $value) { if (strpos($name, 'custom_') === 0) { $this->context->setSetting($name); } } // Save custom parameters foreach ($_REQUEST as $name => $value) { if (strpos($name, 'custom_') === 0) { $this->context->setSetting($name, $value); } } $this->context->save(); } if ($this->isOK) { # ### Set the user instance # $this->user = new LTI_User($this->context, trim($_REQUEST['user_id'])); # ### Set the user name # $firstname = isset($_REQUEST['lis_person_name_given']) ? $_REQUEST['lis_person_name_given'] : ''; $lastname = isset($_REQUEST['lis_person_name_family']) ? $_REQUEST['lis_person_name_family'] : ''; $fullname = isset($_REQUEST['lis_person_name_full']) ? $_REQUEST['lis_person_name_full'] : ''; $this->user->setNames($firstname, $lastname, $fullname); # ### Set the user email # $email = isset($_REQUEST['lis_person_contact_email_primary']) ? $_REQUEST['lis_person_contact_email_primary'] : ''; $this->user->setEmail($email, $this->defaultEmail); # ### Set the user roles # if (isset($_REQUEST['roles'])) { $this->user->roles = explode(',', $_REQUEST['roles']); } # ### Save the user instance # if (isset($_REQUEST['lis_result_sourcedid'])) { $this->user->lti_result_sourcedid = $_REQUEST['lis_result_sourcedid']; $this->user->save(); } # ### Update the consumer instance # if ($this->consumer_instance->state != $_REQUEST['lti_version']) { $this->consumer_instance->state = $_REQUEST['lti_version']; $this->consumer_instance->save(); } # ### Initialise the consumer and check for changes # $this->consumer = new LTI_Tool_Consumer($_REQUEST['oauth_consumer_key'], $this->dbTableNamePrefix); $doSave = FALSE; // do not delete any existing consumer name if none is passed if (isset($_REQUEST['tool_consumer_info_product_family_code'])) { $name = $_REQUEST['tool_consumer_info_product_family_code']; if (isset($_REQUEST['tool_consumer_info_version'])) { $name .= "-{$_REQUEST['tool_consumer_info_version']}"; } if ($this->consumer->consumer_name != $name) { $this->consumer->consumer_name = $name; $doSave = TRUE; } } else { if (isset($_REQUEST['ext_lms']) && $this->consumer->consumer_name != $_REQUEST['ext_lms']) { $this->consumer->consumer_name = $_REQUEST['ext_lms']; $doSave = TRUE; } } if (isset($_REQUEST['launch_presentation_css_url'])) { if ($this->consumer->css_path != $_REQUEST['launch_presentation_css_url']) { $this->consumer->css_path = $_REQUEST['launch_presentation_css_url']; $doSave = TRUE; } } else { if (isset($_REQUEST['ext_launch_presentation_css_url']) && $this->consumer->css_path != $_REQUEST['ext_launch_presentation_css_url']) { $this->consumer->css_path = $_REQUEST['ext_launch_presentation_css_url']; $doSave = TRUE; } else { if (!empty($this->consumer->css_path)) { $this->consumer->css_path = NULL; $doSave = TRUE; } } } if ($doSave) { $this->consumer->save(); } # ### Check if a share arrangement is in place for this context # $this->isOK = $this->checkForShare(); } return $this->isOK; }
/** * Check the authenticity of the LTI launch request. * * The consumer, resource link and user objects will be initialised if the request is valid. * * @return boolean True if the request has been successfully validated. */ private function authenticate() { // Set debug mode $this->debugMode = isset($_POST['custom_debug']) && strtolower($_POST['custom_debug']) == 'true'; // Get the consumer $doSaveConsumer = FALSE; // Check all required launch parameter constraints $this->isOK = isset($_POST['oauth_consumer_key']); if ($this->isOK) { $this->isOK = isset($_POST['lti_message_type']) && $_POST['lti_message_type'] == 'basic-lti-launch-request'; } if ($this->isOK) { $this->isOK = isset($_POST['lti_version']) && ($_POST['lti_version'] == self::LTI_VERSION || $_POST['lti_version'] == self::LTI_VERSION_ALT); } if ($this->isOK) { $this->isOK = isset($_POST['resource_link_id']) && strlen(trim($_POST['resource_link_id'])) > 0; } // Check consumer key if ($this->isOK) { $this->consumer = new LTI_Tool_Consumer($_POST['oauth_consumer_key'], $this->data_connector); $this->isOK = !is_null($this->consumer->created); if ($this->debugMode && !$this->isOK) { $this->reason = 'Invalid consumer key.'; } } $now = time(); if ($this->isOK) { $today = date('Y-m-d', $now); if (is_null($this->consumer->last_access)) { $doSaveConsumer = TRUE; } else { $last = date('Y-m-d', $this->consumer->last_access); $doSaveConsumer = $doSaveConsumer || $last != $today; } $this->consumer->last_access = $now; try { $store = new LTI_OAuthDataStore($this); $server = new OAuthServer($store); $method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($method); $request = OAuthRequest::from_request(); $res = $server->verify_request($request); } catch (Exception $e) { $this->isOK = FALSE; if (empty($this->reason)) { $this->reason = 'OAuth signature check failed - perhaps an incorrect secret or timestamp.'; } } } if ($this->isOK && $this->consumer->protected) { if (!is_null($this->consumer->consumer_guid)) { $this->isOK = isset($_POST['tool_consumer_instance_guid']) && !empty($_POST['tool_consumer_instance_guid']) && $this->consumer->consumer_guid == $_POST['tool_consumer_instance_guid']; if ($this->debugMode && !$this->isOK) { $this->reason = 'Request is from an invalid tool consumer.'; } } else { $this->isOK = isset($_POST['tool_consumer_instance_guid']); if ($this->debugMode && !$this->isOK) { $this->reason = 'A tool consumer GUID must be included in the launch request.'; } } } if ($this->isOK) { $this->isOK = $this->consumer->enabled; if ($this->debugMode && !$this->isOK) { $this->reason = 'Tool consumer has not been enabled by the tool provider.'; } } if ($this->isOK) { $this->isOK = is_null($this->consumer->enable_from) || $this->consumer->enable_from <= $now; if ($this->isOK) { $this->isOK = is_null($this->consumer->enable_until) || $this->consumer->enable_until > $now; if ($this->debugMode && !$this->isOK) { $this->reason = 'Tool consumer access has expired.'; } } else { if ($this->debugMode) { $this->reason = 'Tool consumer access is not yet available.'; } } } // Validate launch parameters if ($this->isOK) { $invalid_parameters = array(); foreach ($this->constraints as $name => $constraint) { $ok = TRUE; if ($constraint['required']) { if (!isset($_POST[$name]) || strlen(trim($_POST[$name])) <= 0) { $invalid_parameters[] = $name; $ok = FALSE; } } if ($ok && !is_null($constraint['max_length']) && isset($_POST[$name])) { if (strlen(trim($_POST[$name])) > $constraint['max_length']) { $invalid_parameters[] = $name; } } } if (count($invalid_parameters) > 0) { $this->isOK = FALSE; if (empty($this->reason)) { $this->reason = 'Invalid parameter(s): ' . implode(', ', $invalid_parameters) . '.'; } } } if ($this->isOK) { $this->consumer->defaultEmail = $this->defaultEmail; // Set the request context/resource link $this->resource_link = new LTI_Resource_Link($this->consumer, trim($_POST['resource_link_id'])); if (isset($_POST['context_id'])) { $this->resource_link->lti_context_id = trim($_POST['context_id']); } $this->resource_link->lti_resource_id = trim($_POST['resource_link_id']); $title = ''; if (isset($_POST['context_title'])) { $title = trim($_POST['context_title']); } if (isset($_POST['resource_link_title']) && strlen(trim($_POST['resource_link_title'])) > 0) { if (!empty($title)) { $title .= ': '; } $title .= trim($_POST['resource_link_title']); } if (empty($title)) { $title = "Course {$this->resource_link->getId()}"; } $this->resource_link->title = $title; // Save LTI parameters foreach ($this->lti_settings_names as $name) { if (isset($_POST[$name])) { $this->resource_link->setSetting($name, $_POST[$name]); } else { $this->resource_link->setSetting($name, NULL); } } // Delete any existing custom parameters foreach ($this->resource_link->getSettings() as $name => $value) { if (strpos($name, 'custom_') === 0) { $this->resource_link->setSetting($name); } } // Save custom parameters foreach ($_POST as $name => $value) { if (strpos($name, 'custom_') === 0) { $this->resource_link->setSetting($name, $value); } } // Set the user instance $user_id = ''; if (isset($_POST['user_id'])) { $user_id = trim($_POST['user_id']); } $this->user = new LTI_User($this->resource_link, $user_id); // Set the user name $firstname = isset($_POST['lis_person_name_given']) ? $_POST['lis_person_name_given'] : ''; $lastname = isset($_POST['lis_person_name_family']) ? $_POST['lis_person_name_family'] : ''; $fullname = isset($_POST['lis_person_name_full']) ? $_POST['lis_person_name_full'] : ''; $this->user->setNames($firstname, $lastname, $fullname); // Set the user email $email = isset($_POST['lis_person_contact_email_primary']) ? $_POST['lis_person_contact_email_primary'] : ''; $this->user->setEmail($email, $this->defaultEmail); // Set the user roles if (isset($_POST['roles'])) { $this->user->roles = LTI_Tool_Provider::parseRoles($_POST['roles']); } // Save the user instance if (isset($_POST['lis_result_sourcedid'])) { if ($this->user->lti_result_sourcedid != $_POST['lis_result_sourcedid']) { $this->user->lti_result_sourcedid = $_POST['lis_result_sourcedid']; $this->user->save(); } } else { if (!empty($this->user->lti_result_sourcedid)) { $this->user->delete(); } } // Initialise the consumer and check for changes if ($this->consumer->lti_version != $_POST['lti_version']) { $this->consumer->lti_version = $_POST['lti_version']; $doSaveConsumer = TRUE; } if (isset($_POST['tool_consumer_instance_name'])) { if ($this->consumer->consumer_name != $_POST['tool_consumer_instance_name']) { $this->consumer->consumer_name = $_POST['tool_consumer_instance_name']; $doSaveConsumer = TRUE; } } if (isset($_POST['tool_consumer_info_product_family_code'])) { $version = $_POST['tool_consumer_info_product_family_code']; if (isset($_POST['tool_consumer_info_version'])) { $version .= "-{$_POST['tool_consumer_info_version']}"; } // do not delete any existing consumer version if none is passed if ($this->consumer->consumer_version != $version) { $this->consumer->consumer_version = $version; $doSaveConsumer = TRUE; } } else { if (isset($_POST['ext_lms']) && $this->consumer->consumer_name != $_POST['ext_lms']) { $this->consumer->consumer_version = $_POST['ext_lms']; $doSaveConsumer = TRUE; } } if (isset($_POST['tool_consumer_instance_guid'])) { if (is_null($this->consumer->consumer_guid)) { $this->consumer->consumer_guid = $_POST['tool_consumer_instance_guid']; $doSaveConsumer = TRUE; } else { if (!$this->consumer->protected) { $doSaveConsumer = $this->consumer->consumer_guid != $_POST['tool_consumer_instance_guid']; if ($doSaveConsumer) { $this->consumer->consumer_guid = $_POST['tool_consumer_instance_guid']; } } } } if (isset($_POST['launch_presentation_css_url'])) { if ($this->consumer->css_path != $_POST['launch_presentation_css_url']) { $this->consumer->css_path = $_POST['launch_presentation_css_url']; $doSaveConsumer = TRUE; } } else { if (isset($_POST['ext_launch_presentation_css_url']) && $this->consumer->css_path != $_POST['ext_launch_presentation_css_url']) { $this->consumer->css_path = $_POST['ext_launch_presentation_css_url']; $doSaveConsumer = TRUE; } else { if (!empty($this->consumer->css_path)) { $this->consumer->css_path = NULL; $doSaveConsumer = TRUE; } } } } // Persist changes to consumer if ($doSaveConsumer) { $this->consumer->save(); } if ($this->isOK) { // Check if a share arrangement is in place for this resource link $this->isOK = $this->checkForShare(); // Persist changes to resource link $this->resource_link->save(); } return $this->isOK; }
/** * Verifies the OAuth request signature, sets the auth user * and access type (read-only or read-write) * * @param OAuthRequest $request the OAuth Request * * @return nothing */ function checkOAuthRequest($request) { $datastore = new ApiGNUsocialOAuthDataStore(); $server = new OAuthServer($datastore); $hmac_method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($hmac_method); try { $server->verify_request($request); $consumer = $request->get_parameter('oauth_consumer_key'); $access_token = $request->get_parameter('oauth_token'); $app = Oauth_application::getByConsumerKey($consumer); if (empty($app)) { common_log(LOG_WARNING, 'API OAuth - Couldn\'t find the OAuth app for consumer key: ' . $consumer); // TRANS: OAuth exception thrown when no application is found for a given consumer key. throw new OAuthException(_('No application for that consumer key.')); } // set the source attr if ($app->name != 'anonymous') { $this->source = $app->name; } $appUser = Oauth_application_user::getKV('token', $access_token); if (!empty($appUser)) { // If access_type == 0 we have either a request token // or a bad / revoked access token if ($appUser->access_type != 0) { // Set the access level for the api call $this->access = $appUser->access_type & Oauth_application::$writeAccess ? self::READ_WRITE : self::READ_ONLY; // Set the auth user if (Event::handle('StartSetApiUser', array(&$user))) { $user = User::getKV('id', $appUser->profile_id); if (!empty($user)) { if (!$user->hasRight(Right::API)) { // TRANS: Authorization exception thrown when a user without API access tries to access the API. throw new AuthorizationException(_('Not allowed to use API.')); } } $this->auth_user = $user; // FIXME: setting the value returned by common_current_user() // There should probably be a better method for this. common_set_user() // does lots of session stuff. global $_cur; $_cur = $this->auth_user; Event::handle('EndSetApiUser', array($user)); } $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " . "application '%s' (id: %d) with %s access."; common_log(LOG_INFO, sprintf($msg, $this->auth_user->nickname, $this->auth_user->id, $app->name, $app->id, ($this->access = self::READ_WRITE) ? 'read-write' : 'read-only')); } else { // TRANS: OAuth exception given when an incorrect access token was given for a user. throw new OAuthException(_('Bad access token.')); } } else { // Also should not happen. // TRANS: OAuth exception given when no user was found for a given token (no token was found). throw new OAuthException(_('No user for that token.')); } } catch (OAuthException $e) { $this->logAuthFailure($e->getMessage()); common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage()); $this->clientError($e->getMessage(), 401); } }
public function testRejectUnknownSignatureMethod() { // We use a server that only supports HMAC-SHA1, but requests with PLAINTEXT signature $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, 'POST', 'http://example.com'); $request->sign_request($this->plaintext, $this->consumer, $this->access_token); $server = new OAuthServer(new Mock_OAuthDataStore()); $server->add_signature_method($this->hmac_sha1); $this->setExpectedException('OAuthException'); $server->verify_request($request); }
function __construct($parm = false, $usesession = true, $doredirect = true) { // If this request is not an LTI Launch, either // give up or try to retrieve the context from session if (!is_lti_request()) { $this->message = 'Request is missing LTI information'; if ($usesession === false) { return; } if (strlen(session_id()) > 0) { $row = $_SESSION['_lti_row']; if (isset($row)) { $this->row = $row; } $context_id = $_SESSION['_lti_context_id']; if (isset($context_id)) { $this->context_id = $context_id; } $info = $_SESSION['_lti_context']; if (isset($info)) { $this->info = $info; $this->valid = true; return; } $this->message = "Could not find context in session"; return; } $this->message = "Session not available"; return; } // Insure we have a valid launch if (empty($_REQUEST["oauth_consumer_key"])) { $this->message = "Missing oauth_consumer_key in request"; return; } $oauth_consumer_key = $_REQUEST["oauth_consumer_key"]; // Find the secret - either form the parameter as a string or // look it up in a database from parameters we are given $secret = false; $row = false; if (is_string($parm)) { $secret = $parm; } else { if (!is_array($parm)) { $this->message = "Constructor requires a secret or database information."; return; } else { $sql = 'SELECT * FROM ' . $parm['table'] . ' WHERE ' . ($parm['key_column'] ? $parm['key_column'] : 'oauth_consumer_key') . '=' . "'" . mysql_real_escape_string($oauth_consumer_key) . "'"; $result = mysql_query($sql); $num_rows = mysql_num_rows($result); if ($num_rows != 1) { $this->message = "Your consumer is not authorized oauth_consumer_key=" . $oauth_consumer_key; return; } else { while ($row = mysql_fetch_assoc($result)) { $secret = $row[$parms['secret_column'] ? $parms['secret_column'] : 'secret']; $context_id = $row[$parms['context_column'] ? $parms['context_column'] : 'context_id']; if ($context_id) { $this->context_id = $context_id; } $this->row = $row; break; } if (!is_string($secret)) { $this->message = "Could not retrieve secret oauth_consumer_key=" . $oauth_consumer_key; return; } } } } // Verify the message signature $store = new TrivialOAuthDataStore(); $store->add_consumer($oauth_consumer_key, $secret); $server = new OAuthServer($store); $request = OAuthRequest::from_request(); $method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($method); $method = new OAuthSignatureMethod_HMAC_SHA256(); $server->add_signature_method($method); $this->basestring = $request->get_signature_base_string(); try { $server->verify_request($request); $this->valid = true; } catch (Exception $e) { $this->message = $e->getMessage(); return; } // Store the launch information in the session for later $newinfo = array(); foreach ($_POST as $key => $value) { if (get_magic_quotes_gpc()) { $value = stripslashes($value); } if ($key == "basiclti_submit") { continue; } if (strpos($key, "oauth_") === false) { $newinfo[$key] = $value; continue; } if ($key == "oauth_consumer_key") { $newinfo[$key] = $value; continue; } } $this->info = $newinfo; if ($usesession == true and strlen(session_id()) > 0) { $_SESSION['_lti_context'] = $this->info; unset($_SESSION['_lti_row']); unset($_SESSION['_lti_context_id']); if ($this->row) { $_SESSION['_lti_row'] = $this->row; } if ($this->context_id) { $_SESSION['_lti_context_id'] = $this->context_id; } } if ($this->valid && $doredirect) { $this->redirect(); $this->complete = true; } }
function oauth_omb_update(&$vars) { extract($vars); wp_plugin_include(array('wp-oauth')); $store = new OAuthWordpressStore(); $server = new OAuthServer($store); $sha1_method = new OAuthSignatureMethod_HMAC_SHA1(); $plaintext_method = new OAuthSignatureMethod_PLAINTEXT(); $server->add_signature_method($sha1_method); $server->add_signature_method($plaintext_method); $req = OAuthRequest::from_request(); list($consumer, $token) = $server->verify_request($req); $version = $req->get_parameter('omb_version'); if ($version != OMB_VERSION) { trigger_error('invalid omb version', E_USER_ERROR); } $listenee = $req->get_parameter('omb_listenee'); $Identity =& $db->model('Identity'); $sender = $Identity->find_by('profile', $listenee); if (!$sender) { header('HTTP/1.1 403 Forbidden'); exit; } $listenee_params = array('omb_listenee_profile' => 'profile_url', 'omb_listenee_nickname' => 'nickname', 'omb_listenee_license' => 'license', 'omb_listenee_fullname' => 'fullname', 'omb_listenee_homepage' => 'homepage', 'omb_listenee_bio' => 'bio', 'omb_listenee_location' => 'locality', 'omb_listenee_avatar' => 'avatar'); foreach ($listenee_params as $k => $v) { if (isset($_POST[$k])) { $sender->set_value($v, $_POST[$k]); } } $sender->save_changes(); print "omb_version=" . OMB_VERSION; exit; }