Exemplo n.º 1
0
 /**
  * Handle a request for temporary OAuth credentials
  *
  * Make sure the request is kosher, then emit a set of temporary
  * credentials -- AKA an unauthorized request token.
  *
  * @param array $args array of arguments
  *
  * @return void
  */
 function handle($args)
 {
     parent::handle($args);
     $datastore = new ApiStatusNetOAuthDataStore();
     $server = new OAuthServer($datastore);
     $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
     $server->add_signature_method($hmac_method);
     try {
         $req = OAuthRequest::from_request();
         // verify callback
         if (!$this->verifyCallback($req->get_parameter('oauth_callback'))) {
             throw new OAuthException("You must provide a valid URL or 'oob' in oauth_callback.", 400);
         }
         // check signature and issue a new request token
         $token = $server->fetch_request_token($req);
         common_log(LOG_INFO, sprintf("API OAuth - Issued request token %s for consumer %s with oauth_callback %s", $token->key, $req->get_parameter('oauth_consumer_key'), "'" . $req->get_parameter('oauth_callback') . "'"));
         // return token to the client
         $this->showRequestToken($token);
     } catch (OAuthException $e) {
         common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
         // Return 401 for for bad credentials or signature problems,
         // and 400 for missing or unsupported parameters
         $code = $e->getCode();
         $this->clientError($e->getMessage(), empty($code) ? 401 : $code, 'text');
     }
 }
Exemplo n.º 2
0
 /**
  * @param GetResponseEvent $event
  * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
  * @return bool
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     if (strpos($event->getRequest()->attributes->get('_controller'), 'Api\\Resource') !== false) {
         header('Access-Control-Allow-Origin: *');
         $controller = explode('::', $event->getRequest()->attributes->get('_controller'));
         $reflection = new \ReflectionMethod($controller[0], $controller[1]);
         $scopeAnnotation = $this->reader->getMethodAnnotation($reflection, 'Etu\\Core\\ApiBundle\\Framework\\Annotation\\Scope');
         if ($scopeAnnotation) {
             $requiredScope = $scopeAnnotation->value;
         } else {
             $requiredScope = null;
         }
         if (!$requiredScope) {
             $requiredScope = 'public';
         }
         $request = $event->getRequest();
         $token = $request->query->get('access_token');
         $access = $this->server->checkAccess($token, $requiredScope);
         if (!$access->isGranted()) {
             $event->setResponse($this->formatter->format($event->getRequest(), ['error' => $access->getError(), 'error_message' => $access->getErrorMessage()], 403));
         } else {
             $event->getRequest()->attributes->set('_oauth_token', $access->getToken());
         }
     }
 }
 /**
  * Class handler.
  *
  * @param array $args array of arguments
  *
  * @return void
  */
 function handle($args)
 {
     parent::handle($args);
     $datastore = new ApiStatusNetOAuthDataStore();
     $server = new OAuthServer($datastore);
     $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
     $server->add_signature_method($hmac_method);
     $atok = $app = null;
     // XXX: Insist that oauth_token and oauth_verifier be populated?
     // Spec doesn't say they MUST be.
     try {
         $req = OAuthRequest::from_request();
         $this->reqToken = $req->get_parameter('oauth_token');
         $this->verifier = $req->get_parameter('oauth_verifier');
         $app = $datastore->getAppByRequestToken($this->reqToken);
         $atok = $server->fetch_access_token($req);
     } catch (Exception $e) {
         common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
         common_debug(var_export($req, true));
         $code = $e->getCode();
         $this->clientError($e->getMessage(), empty($code) ? 401 : $code, 'text');
         return;
     }
     if (empty($atok)) {
         // Token exchange failed -- log it
         $msg = sprintf('API OAuth - Failure exchanging OAuth request token for access token, ' . 'request token = %s, verifier = %s', $this->reqToken, $this->verifier);
         common_log(LOG_WARNING, $msg);
         // TRANS: Client error given from the OAuth API when the request token or verifier is invalid.
         $this->clientError(_('Invalid request token or verifier.'), 400, 'text');
     } else {
         common_log(LOG_INFO, sprintf("Issued access token '%s' for application %d (%s).", $atok->key, $app->id, $app->name));
         $this->showAccessToken($atok);
     }
 }
Exemplo n.º 4
0
function omb_oauth_server()
{
    static $server = null;
    if (is_null($server)) {
        $server = new OAuthServer(omb_oauth_datastore());
        $server->add_signature_method(omb_hmac_sha1());
    }
    return $server;
}
Exemplo n.º 5
0
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;
}
Exemplo n.º 6
0
 public function genSign($key, $secret, $token, $tokenSecret, $httpMethod, $endpoint)
 {
     $authServer = new OAuthServer(new MockOAuthDataStore());
     $hmac_method = new OAuthSignatureMethodHmacSha1();
     $authServer->add_signature_method($hmac_method);
     $sig_method = $hmac_method;
     $authConsumer = new OAuthConsumer($key, $secret, NULL);
     $authToken = NULL;
     $authToken = new OAuthToken($token, $tokenSecret);
     //$params is the query param array which is required only in the httpMethod is "GET"
     $params = array();
     //TODO: set the Query parameters to $params if httpMethod is "GET"
     $acc_req = OAuthRequest::from_consumer_and_token($authConsumer, $authToken, $httpMethod, $endpoint, $params);
     $acc_req->sign_request($sig_method, $authConsumer, $authToken);
     return OAuthutil::parseQueryString($acc_req);
 }
Exemplo n.º 7
0
 public function __construct($data_store)
 {
     parent::__construct($data_store);
     $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
     $this->add_signature_method($hmac_method);
     $this->timestamp_threshold = 300;
     // a token (in requestToken) expires before 300 secondes
 }
Exemplo n.º 8
0
 public function access_token($params)
 {
     try {
         $server = new OAuthServer($this->oauthDataStore);
         $server->add_signature_method(new OAuthSignatureMethod_HMAC_SHA1());
         $server->add_signature_method(new OAuthSignatureMethod_PLAINTEXT());
         $request = OAuthRequest::from_request();
         $token = $server->fetch_access_token($request);
         if ($token) {
             echo $token->to_string();
         }
     } catch (OAuthException $e) {
         $this->sendServerError(401, $e->getMessage());
     } catch (Exception $e) {
         $this->sendServerError(400, $e->getMessage());
     }
 }
 /**
  * Class handler.
  *
  * @param array $args array of arguments
  *
  * @return void
  */
 function handle($args)
 {
     parent::handle($args);
     $datastore = new ApiStatusNetOAuthDataStore();
     $server = new OAuthServer($datastore);
     $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
     $server->add_signature_method($hmac_method);
     try {
         $req = OAuthRequest::from_request();
         $token = $server->fetch_request_token($req);
         print $token;
     } catch (OAuthException $e) {
         common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
         header('HTTP/1.1 401 Unauthorized');
         header('Content-Type: text/html; charset=utf-8');
         print $e->getMessage() . "\n";
     }
 }
Exemplo n.º 10
0
 function __construct($consumer_key, $nonce, $timestamp, $signature_method, $signature, $token)
 {
     $this->setParam('oauth_token', $token, true);
     $this->setParam('oauth_consumer_key', $consumer_key, true);
     $this->setParam('oauth_nonce', $nonce, true);
     $this->setParam('oauth_timestamp', $timestamp, true);
     $this->setParam('oauth_signature_method', $signature_method, true);
     $this->setParam('oauth_signature', $signature, true);
     parent::__construct();
 }
Exemplo n.º 11
0
 /**
  * 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;
 }
Exemplo n.º 12
0
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;
}
Exemplo n.º 13
0
 public function authorizeAction()
 {
     $auth = Zend_Auth::getInstance();
     $store = OAuthStore::instance();
     $registry = Zend_Registry::getInstance();
     $router = Zend_Controller_Front::getInstance()->getRouter();
     $request = $this->getRequest();
     if (!$auth->hasIdentity()) {
         Zend_Controller_Front::getInstance()->registerPlugin(new Ml_Plugins_LoginRedirect());
     }
     $this->_helper->loadOauthstore->preloadServer();
     $server = new OAuthServer();
     $form = Ml_Model_Api::authorizeForm();
     // Check if there is a valid request token in the current request
     // Returns an array with the
     //consumer key, consumer secret, token, token secret and token type.
     $rs = $server->authorizeVerify();
     $consumer = $store->getConsumer($rs['consumer_key'], $auth->getIdentity());
     $this->view->consumerInfo = $consumer;
     if ($request->isPost() && $form->isValid($request->getPost())) {
         $values = $form->getValues();
         if (isset($values['allow'])) {
             $authorized = true;
         } else {
             if (isset($values['deny'])) {
                 $authorized = false;
             }
         }
         if (isset($authorized)) {
             $server->authorizeFinish($authorized, $auth->getIdentity());
             //If no oauth_callback, the user is redirected to
             $this->_redirect($router->assemble(array(), "accountapps") . "?new_addition", array("exit"));
         }
     }
     $this->view->authorizeForm = $form;
 }
 /**
  * Class handler.
  *
  * @param array $args array of arguments
  *
  * @return void
  */
 function handle($args)
 {
     parent::handle($args);
     $datastore = new ApiStatusNetOAuthDataStore();
     $server = new OAuthServer($datastore);
     $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
     $server->add_signature_method($hmac_method);
     $atok = null;
     try {
         $req = OAuthRequest::from_request();
         $atok = $server->fetch_access_token($req);
     } catch (OAuthException $e) {
         common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
         common_debug(var_export($req, true));
         $this->outputError($e->getMessage());
         return;
     }
     if (empty($atok)) {
         common_debug('couldn\'t get access token.');
         print "Token exchange failed. Has the request token been authorized?\n";
     } else {
         print $atok;
     }
 }
Exemplo n.º 15
0
 public function actionAuthorize()
 {
     //登陆用户
     $user_id = Yii::app()->user->id;
     $model = new LoginForm();
     $errmsg = '';
     // 取得 oauth store 和 oauth server 对象
     $server = new OAuthServer();
     try {
         // 检查当前请求中是否包含一个合法的请求token
         // 返回一个数组, 包含consumer key, consumer secret, token, token secret 和 token type.
         $rs = $server->authorizeVerify($user_id);
         // 没有登录时不允许跳转
         if (!empty($user_id)) {
             //当application_type 为 system 时,可以不须经过用户授权
             if ($rs['application_type'] == 'system') {
                 $authorized = True;
                 $server->authorizeFinish($authorized, $user_id);
             }
             if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                 // 判断用户是否点击了 "allow" 按钮(或者你可以自定义为其他标识)
                 $authorized = True;
                 // 设置token的认证状态(已经被认证或者尚未认证)
                 // 如果存在 oauth_callback 参数, 重定向到客户(消费方)地址
                 $verifier = $server->authorizeFinish($authorized, $user_id);
                 // 如果没有 oauth_callback 参数, 显示认证结果
                 // ** 你的代码 **
                 echo $verifier;
                 die;
             } else {
                 #echo 'Error';
             }
         } else {
             // if it is ajax validation request
             if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
                 echo EActiveForm::validate($model);
                 Yii::app()->end();
             }
             // collect user input data
             if (isset($_POST['LoginForm'])) {
                 $model->attributes = $_POST['LoginForm'];
                 // validate user input and redirect to the previous page if valid
                 if ($model->validate() && $model->login()) {
                     $this->refresh();
                 }
             }
         }
     } catch (OAuthException $e) {
         $errmsg = $e->getMessage();
         throw new CHttpException(401, $errmsg);
         // 请求中没有包含token, 显示一个使用户可以输入token以进行验证的页面
         // ** 你的代码 **
     } catch (OAuthException2 $e) {
         $errmsg = $e->getMessage();
         // 请求了一个错误的token
         // ** 你的代码 **
         throw new CHttpException(401, $errmsg);
     }
     $data = array('rs' => $rs, 'model' => $model, 'errmsg' => $errmsg);
     $this->render('Authorize', $data);
 }
Exemplo n.º 16
0
 /**
  * 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);
     }
 }
Exemplo n.º 17
0
 /**
  * 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;
     }
 }
Exemplo n.º 18
0
<?php

$server = new OAuthServer(new DataApi_OAuthDataStore());
$server->add_signature_method(new OAuthSignatureMethod_HMAC_SHA1());
$request = OAuthRequest::from_request();
try {
    if ($server->verify_request($request)) {
        echo json_encode(true);
    }
} catch (Exception $e) {
    echo json_encode("Exception: " . $e->getMessage());
}
class DataApi_OAuthDataStore extends OAuthDataStore
{
    function lookup_consumer($consumer_key)
    {
        $consumer_secrets = array('thisisakey' => 'thisisasecret', 'anotherkey' => 'f3ac5b093f3eab260520d8e3049561e6');
        if (isset($consumer_secrets[$consumer_key])) {
            return new OAuthConsumer($consumer_key, $consumer_secrets[$consumer_key], NULL);
        } else {
            return false;
        }
    }
    function lookup_token($consumer, $token_type, $token)
    {
        // we are not using tokens, so return empty token
        return new OAuthToken("", "");
    }
    function lookup_nonce($consumer, $token, $nonce, $timestamp)
    {
        // @todo lookup nonce and make sure it hasn't been used before (perhaps in combination with timestamp?)
Exemplo n.º 19
0
 /**
  *
  **/
 public function access_token_action()
 {
     $server = new OAuthServer();
     $server->accessToken();
     $this->render_nothing();
 }
Exemplo n.º 20
0
 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;
     }
 }
Exemplo n.º 21
0
 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;
     }
 }
Exemplo n.º 22
0
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
require_once '../core/init.php';
$server = new OAuthServer();
switch ($_SERVER['PATH_INFO']) {
    case '/request_token':
        $server->requestToken();
        exit;
    case '/access_token':
        $server->accessToken();
        exit;
    case '/authorize':
        # logon
        assert_logged_in();
        try {
            $server->authorizeVerify();
            $server->authorizeFinish(true, 1);
        } catch (OAuthException $e) {
            header('HTTP/1.1 400 Bad Request');
Exemplo n.º 23
0
/***********************************************************************/
/* ATutor															   */
/***********************************************************************/
/* Copyright (c) 2002-2010                                             */
/* Inclusive Design Institute	                                       */
/* http://atutor.ca													   */
/*																	   */
/* This program is free software. You can redistribute it and/or	   */
/* modify it under the terms of the GNU General Public License		   */
/* as published by the Free Software Foundation.					   */
/***********************************************************************/
// $Id$
require_once 'OAuth.php';
require_once '../Shindig/ATutorOAuthDataStore.php';
$oauthDataStore = new ATutorOAuthDataStore();
try {
    $server = new OAuthServer($oauthDataStore);
    $server->add_signature_method(new OAuthSignatureMethod_HMAC_SHA1());
    $server->add_signature_method(new OAuthSignatureMethod_PLAINTEXT());
    $request = OAuthRequest::from_request();
    $token = $server->fetch_access_token($request);
    if ($token) {
        echo $token->to_string();
    }
    echo $token;
} catch (OAuthException $e) {
    echo $e->getMessage();
} catch (Exception $e) {
    echo $e->getMessage();
}
Exemplo n.º 24
0
 /**
  * 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;
     }
 }
Exemplo n.º 25
0
 function __construct()
 {
     parent::__construct(new FKOAuthDataStore());
     $this->add_signature_method(new OAuthSignatureMethod_PLAINTEXT());
     $this->add_signature_method(new OAuthSignatureMethod_HMAC_SHA1());
 }
Exemplo n.º 26
0
if (!is_https()) {
    header("HTTP/1.0 403 Forbidden - HTTPS must be used");
    die;
}
/*
 * Always announce XRDS OAuth discovery
 */
header('X-XRDS-Location: ' . get_config('wwwroot') . 'webservice/oauthv1/services.xrds');
/*
 * Initialize OAuth store
 */
require_once get_config('docroot') . 'webservice/libs/oauth-php/OAuthServer.php';
require_once get_config('docroot') . 'webservice/libs/oauth-php/OAuthStore.php';
OAuthStore::instance('Mahara');
global $server;
$server = new OAuthServer();
!isset($_SERVER['PATH_INFO']) && ($_SERVER['PATH_INFO'] = null);
// Now - what kind of OAuth interaction are we handling?
if ($_SERVER['PATH_INFO'] == '/request_token') {
    $server->requestToken();
    exit;
} else {
    if ($_SERVER['PATH_INFO'] == '/access_token') {
        $server->accessToken();
        exit;
    } else {
        if ($_SERVER['PATH_INFO'] == '/authorize') {
            # logon
            require_once 'pieforms/pieform.php';
            if (!$USER->is_logged_in()) {
                $form = new Pieform(auth_get_login_form());
Exemplo n.º 27
0
    if ( $hashsig != $signature ) {
        doError("Invalid sourcedid");
    }

    // Check the OAuth Signature 
    $oauth_consumer_key = $basiclti_tool_row['resourcekey'];
    $oauth_secret = $basiclti_tool_row['password'];

    if ( ! isset($oauth_secret) ) doError("Not permitted");
    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" ) {
Exemplo n.º 28
0
 /**
  * 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;
 }
Exemplo n.º 30
0
 /**
  * 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;
 }