/**
  * Build signature
  *
  * @param String $baseString - base string
  * @param OAuthConsumer $consumer - consumer
  * @param OAuthToken $token - token
  * @return String
  */
 public function build($baseString, $consumer, $token)
 {
     $keyParts = array($consumer->getSecret(), $token ? $token->getSecret() : '');
     $keyParts = OAuthUtils::urlEncodeRfc3986($keyParts);
     $key = implode('&', $keyParts);
     return base64_encode(hash_hmac('sha1', $baseString, $key, true));
 }
Exemplo n.º 2
0
 public function testSerialize()
 {
     $token = new OAuthToken('token', 'secret');
     $this->assertEquals('oauth_token=token&oauth_token_secret=secret', $token->to_string());
     $token = new OAuthToken('token&', 'secret%');
     $this->assertEquals('oauth_token=token%26&oauth_token_secret=secret%25', $token->to_string());
 }
Exemplo n.º 3
0
 public function dashboard()
 {
     if (User::isLoggedIn()) {
         $bots = User::$me->getActiveBots();
         $this->set('bots', $bots->getAll());
         $this->set('bot_count', $bots->count());
         $on_deck = User::$me->getJobs('available', 'user_sort', 'ASC');
         $this->set('on_deck', $on_deck->getRange(0, 5));
         $this->set('on_deck_count', $on_deck->count());
         $finished = User::$me->getJobs('complete', 'verified_time', 'DESC');
         $this->set('finished', $finished->getRange(0, 5));
         $this->set('finished_count', $finished->count());
         //what style to show?
         if ($this->args('dashboard_style')) {
             User::$me->set('dashboard_style', $this->args('dashboard_style'));
             User::$me->save();
         }
         //do we need to set a default?
         if (!User::$me->get('dashboard_style')) {
             User::$me->set('dashboard_style', 'large_thumbnails');
             User::$me->save();
         }
         //are there any apps requesting access?
         $this->set('request_tokens', OAuthToken::getRequestTokensByIP()->getAll());
         //okay, pull in our dashboard style.
         $this->set('dashboard_style', User::$me->get('dashboard_style'));
     } else {
         die('You must be logged in to view this page.');
     }
 }
Exemplo n.º 4
0
 public function token($api, $args)
 {
     $validVersion = $this->isSupportedClientVersion($api, $args);
     if (!$validVersion) {
         throw new SugarApiExceptionClientOutdated();
     }
     $oauth2Server = $this->getOAuth2Server($args);
     try {
         $GLOBALS['logic_hook']->call_custom_logic('Users', 'before_login');
         $authData = $oauth2Server->grantAccessToken($args);
         // if we're here, the login was OK
         if (!empty($GLOBALS['current_user'])) {
             //Update password expired since user's essentially logged in at this point
             require_once 'modules/Users/password_utils.php';
             $GLOBALS['current_user']->call_custom_logic('after_login');
         }
         $cleanupChance = isset($GLOBALS['sugar_config']['token_cleanup_probability']) ? (int) $GLOBALS['sugar_config']['token_cleanup_probability'] : 10;
         if (mt_rand() % $cleanupChance == 0) {
             // cleanup based on probability
             OAuthToken::cleanup();
         }
     } catch (OAuth2ServerException $e) {
         // failed to get token - something went wrong - list as failed login
         $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
         throw $e;
     } catch (SugarApiExceptionNeedLogin $e) {
         $GLOBALS['logic_hook']->call_custom_logic('Users', 'login_failed');
         // have API throw login exception wil full data
         $api->needLogin($e);
     }
     $loginStatus = apiCheckLoginStatus();
     if ($loginStatus !== true && $loginStatus['level'] != 'warning') {
         if (($loginStatus['level'] == 'admin_only' || $loginStatus['level'] == 'maintenance') && $GLOBALS['current_user']->isAdmin()) {
             // Let them through
         } else {
             // This is no good, they shouldn't be allowed in.
             $e = new SugarApiExceptionMaintenance($loginStatus['message'], null, null, 0, $loginStatus['level']);
             if (!empty($loginStatus['url'])) {
                 $e->setExtraData("url", $loginStatus['url']);
             }
             $api->needLogin($e);
             return;
         }
     }
     $platform = 'base';
     if (!empty($args['platform'])) {
         $platform = $args['platform'];
     }
     // Adding the setcookie() here instead of calling $api->setHeader() because
     // manually adding a cookie header will break 3rd party apps that use cookies
     setcookie(RestService::DOWNLOAD_COOKIE . '_' . $platform, $authData['download_token'], time() + $authData['refresh_expires_in'], ini_get('session.cookie_path'), ini_get('session.cookie_domain'), ini_get('session.cookie_secure'), true);
     // For reauth requests we need to send back the session cookie as well to
     // keep the client in sync if there was a session cookie to begin with
     if (isset($_COOKIE[session_name()]) && !empty($args['grant_type']) && $args['grant_type'] == 'refresh_token' && !empty($args['refresh'])) {
         $this->sendSessionCookie();
     }
     return $authData;
 }
Exemplo n.º 5
0
 public function api_accesstoken()
 {
     //pull in our interface class.
     $provider = $this->get('provider');
     $token = OAuthToken::findByKey($provider->oauth->token);
     $token->changeToAccessToken();
     $data['oauth_token'] = $token->get('token');
     $data['oauth_token_secret'] = $token->get('token_secret');
     return $data;
 }
Exemplo n.º 6
0
 public function display()
 {
     if (!SugarOAuthServer::enabled()) {
         sugar_die($GLOBALS['mod_strings']['LBL_OAUTH_DISABLED']);
     }
     global $current_user;
     if (!isset($_REQUEST['token']) && isset($_REQUEST['oauth_token'])) {
         $_REQUEST['token'] = $_REQUEST['oauth_token'];
     }
     $sugar_smarty = new Sugar_Smarty();
     $sugar_smarty->assign('APP', $GLOBALS['app_strings']);
     $sugar_smarty->assign('MOD', $GLOBALS['mod_strings']);
     $sugar_smarty->assign('token', $_REQUEST['token']);
     $sugar_smarty->assign('sid', session_id());
     $token = OAuthToken::load($_REQUEST['token']);
     if (empty($token) || empty($token->consumer) || $token->tstate != OAuthToken::REQUEST || empty($token->consumer_obj)) {
         sugar_die('Invalid token');
     }
     if (empty($_REQUEST['confirm'])) {
         $sugar_smarty->assign('consumer', sprintf($GLOBALS['mod_strings']['LBL_OAUTH_CONSUMERREQ'], $token->consumer_obj->name));
         // SM: roles disabled for now
         //            $roles = array('' => '');
         //            $allroles = ACLRole::getAllRoles();
         //            foreach($allroles as $role) {
         //                $roles[$role->id] = $role->name;
         //            }
         //            $sugar_smarty->assign('roles', $roles);
         $hash = md5(rand());
         $_SESSION['oauth_hash'] = $hash;
         $sugar_smarty->assign('hash', $hash);
         echo $sugar_smarty->fetch('modules/OAuthTokens/tpl/authorize.tpl');
     } else {
         if ($_REQUEST['sid'] != session_id() || $_SESSION['oauth_hash'] != $_REQUEST['hash']) {
             sugar_die('Invalid request');
         }
         $verify = $token->authorize(array("user" => $current_user->id));
         if (!empty($token->callback_url)) {
             $redirect_url = $token->callback_url;
             if (strchr($redirect_url, "?") !== false) {
                 $redirect_url .= '&';
             } else {
                 $redirect_url .= '?';
             }
             $redirect_url .= "oauth_verifier=" . $verify . '&oauth_token=' . $_REQUEST['token'];
             SugarApplication::redirect($redirect_url);
         }
         $sugar_smarty->assign('VERIFY', $verify);
         $sugar_smarty->assign('token', '');
         echo $sugar_smarty->fetch('modules/OAuthTokens/tpl/authorized.tpl');
     }
 }
Exemplo n.º 7
0
 /**
  * Generate access token string - must have validated request token
  * @return string
  */
 public function accessToken()
 {
     $GLOBALS['log']->debug("OAUTH: accessToken");
     if (empty($this->token) || $this->token->tstate != OAuthToken::REQUEST) {
         return null;
     }
     $this->token->invalidate();
     $token = OAuthToken::generate();
     $token->setState(OAuthToken::ACCESS);
     $token->setConsumer($this->consumer);
     // transfer user data from request token
     $token->copyAuthData($this->token);
     $token->save();
     return $token->queryString();
 }
Exemplo n.º 8
0
 /**
  * This function checks the token of the client
  * Fails if token not found, or verifier not correct
  * Once again you __HAVE TO__ set the $provider->token_secret to the right value or the signature will fail
  * It's called by OAuthCheckRequest() unless the client is getting a request token
  * @param $provider
  * @return int
  */
 public function checkToken($provider)
 {
     $this->token = OAuthToken::findByKey($provider->token);
     if (!$this->token->isHydrated()) {
         return OAUTH_TOKEN_REJECTED;
     } elseif ($this->token->get('type') == 1 && !$this->token->get('verified')) {
         return OAUTH_VERIFIER_INVALID;
     } else {
         if ($this->token->get('type') == 2) {
             /* if this is an access token we register the user to the provider for use in our api */
             $this->user = $this->token->getUser();
             User::$me = $this->user;
         }
         $provider->token_secret = $this->token->get('token_secret');
         return OAUTH_OK;
     }
 }
Exemplo n.º 9
0
 public function dashboard()
 {
     if (!User::isLoggedIn()) {
         die('You must be logged in to view this page.');
     }
     //do we need to set a default?
     if (!User::$me->get('dashboard_style')) {
         User::$me->set('dashboard_style', 'large_thumbnails');
         User::$me->save();
     }
     //okay, pull in our dashboard style.
     $this->set('dashboard_style', User::$me->get('dashboard_style'));
     //are there any apps requesting access?
     $this->set('request_tokens', OAuthToken::getRequestTokensByIP()->getAll());
     $this->addTemplate('bot_thumbnail_template', Controller::byName('bot')->renderTemplate('thumbnail'));
     $this->addTemplate('bot_list_template', Controller::byName('bot')->renderTemplate('dashboard_list'));
     $this->addTemplate('job_list_template', Controller::byName('job')->renderTemplate('job_list'));
     $this->addScript('initial_data', "var initialData = " . Controller::byName('main')->renderView('dashboard_data'), "text/javascript");
     $this->addScript("js/backbone.js");
 }
Exemplo n.º 10
0
 /**
  * @ticket 62822
  */
 public function testCleanup()
 {
     // create request token
     $tok = OAuthToken::generate();
     $tok->consumer = create_guid();
     $tok->setState(OAuthToken::REQUEST);
     $tok->assigned_user_id = $GLOBALS['current_user']->id;
     $tok->save();
     // create invalid token
     $tok = OAuthToken::generate();
     $tok->consumer = create_guid();
     $tok->setState(OAuthToken::INVALID);
     $tok->assigned_user_id = $GLOBALS['current_user']->id;
     $tok->save();
     $cnt = $GLOBALS['db']->getOne("SELECT count(*) c FROM {$tok->table_name} WHERE assigned_user_id=" . $GLOBALS['db']->quoted($GLOBALS['current_user']->id));
     $this->assertEquals(2, $cnt, "Wrong number of tokens in the table");
     // set time way in the past
     $GLOBALS['db']->query("UPDATE {$tok->table_name} SET token_ts=1 WHERE assigned_user_id=" . $GLOBALS['db']->quoted($GLOBALS['current_user']->id));
     // run cleanup
     OAuthToken::cleanup();
     // ensure tokens are gone
     $cnt = $GLOBALS['db']->getOne("SELECT count(*) c FROM {$tok->table_name} WHERE assigned_user_id=" . $GLOBALS['db']->quoted($GLOBALS['current_user']->id));
     $this->assertEquals(0, $cnt, "Tokens were not deleted");
 }
Exemplo n.º 11
0
 public function revoke_app()
 {
     $this->assertLoggedIn();
     $this->set('area', 'app');
     try {
         $token = new OAuthToken($this->args('id'));
         if (!$token->isHydrated()) {
             throw new Exception("This app does not exist.");
         }
         /** @var User $user */
         $user = new User($token->get('user_id'));
         if ($user->isHydrated() && $user->id != User::$me->id) {
             throw new Exception("You are not authorized to delete this app.");
         }
         $form = new Form();
         $field = WarningField::name('warning');
         if ($token->isVerified()) {
             $this->setTitle('Revoke App Permissions - ' . $token->getName());
             $form->submitText = "Revoke App Permissions";
             $field->value("Are you sure you want to revoke access to this app? Any apps currently using these credentials to print will be broken");
         } else {
             $this->setTitle('Deny App - ' . $token->getName());
             $form->submitText = "Deny App";
             $field->value("Are you sure you want to deny access to this app?");
         }
         $form->add($field);
         $this->set('form', $form);
         if ($form->checkSubmitAndValidate($this->args())) {
             if ($token->isVerified()) {
                 Activity::log("removed the app named " . $token->getLink() . ".");
             } else {
                 Activity::log("denied the app named " . $token->getLink() . ".");
             }
             $token->delete();
             $this->forwardToUrl("/apps");
         }
     } catch (Exception $e) {
         $this->setTitle('Error');
         $this->set('megaerror', $e->getMessage());
     }
 }
Exemplo n.º 12
0
 /**
  * Create oauth token for the SNIP user
  * @param User $user
  */
 protected function deleteSnipTokens($user)
 {
     $consumer = $this->getSnipConsumer();
     if (!empty($consumer)) {
         OAuthToken::deleteByConsumer($consumer->id);
     }
     OAuthToken::deleteByUser($user->id);
 }
Exemplo n.º 13
0
 public function revoke_app()
 {
     $this->assertLoggedIn();
     try {
         $token = OAuthToken::findByKey($this->args('token'));
         if (!$token->isHydrated()) {
             throw new Exception("This app does not exist.");
         }
         if (!User::$me->isAdmin() && $token->get('user_id') != User::$me->id) {
             throw new Exception("You are not authorized to delete this app.");
         }
         $app = $token->getConsumer();
         $this->setTitle('Revoke App Permissions - ' . $app->getName());
         $this->set('token', $token);
         $this->set('app', $app);
         if ($this->args('submit')) {
             Activity::log("removed the app named " . $app->getLink() . ".");
             $token->delete();
             $this->forwardToUrl("/apps");
         }
     } catch (Exception $e) {
         $this->setTitle('Error');
         $this->set('megaerror', $e->getMessage());
     }
 }
 function __construct($key, $secret, $id = NULL, $uid = NULL)
 {
     $this->id = $id;
     $this->uid = $uid;
     parent::__construct($key, $secret);
 }
Exemplo n.º 15
0
 public function driver_form()
 {
     try {
         //load our bot
         $bot = new Bot($this->args('id'));
         if (!$bot->isHydrated()) {
             throw new Exception("Could not find that bot.");
         }
         if (!$bot->isMine()) {
             throw new Exception("You cannot view that bot.");
         }
         if ($this->args('token_id') == 0) {
             $this->set('nodriver', "No driver was selected");
         } else {
             //load our token
             $token = new OAuthToken($this->args('token_id'));
             if (!$token->isHydrated()) {
                 throw new Exception("Could not find that computer.");
             }
             if (!$token->isMine()) {
                 throw new Exception("This is not your computer.");
             }
             //what driver form to create?
             $driver = $this->args('driver');
             //pass on our info.
             $this->set('bot', $bot);
             $this->set('driver', $driver);
             $this->set('token', $token);
             $devices = json::decode($token->get('device_data'));
             $this->set('devices', $devices);
             //pull in our driver config
             $driver_config = $bot->getDriverConfig();
             //if we're using the same driver, pull in old values...
             if ($driver == $bot->get('driver_name')) {
                 $this->set('driver_config', $driver_config);
                 if (is_object($driver_config)) {
                     $this->set('delay', $driver_config->delay);
                     $this->set('serial_port', $driver_config->port);
                     $this->set('baudrate', $driver_config->baud);
                 }
             } else {
                 if ($driver == "dummy") {
                     $this->set('delay', '0.001');
                 }
             }
             //pull in our old webcam values too.
             if (is_object($driver_config) && !empty($driver_config->webcam)) {
                 $this->set('webcam_id', $driver_config->webcam->id);
                 $this->set('webcam_name', $driver_config->webcam->name);
                 $this->set('webcam_device', $driver_config->webcam->device);
                 $this->set('webcam_brightness', $driver_config->webcam->brightness);
                 $this->set('webcam_contrast', $driver_config->webcam->contrast);
             } else {
                 //some default webcam settings.
                 $this->set('webcam_id', '');
                 $this->set('webcam_name', '');
                 $this->set('webcam_device', '');
                 $this->set('webcam_brightness', 50);
                 $this->set('webcam_contrast', 50);
             }
             $this->set('driver_config', $driver_config);
             $this->set('baudrates', array(250000, 115200, 57600, 38400, 28880, 19200, 14400, 9600));
         }
     } catch (Exception $e) {
         $this->set('megaerror', $e->getMessage());
     }
 }
 public function __construct($key, $secret, $ttl = 3600, $user_id = NULL)
 {
     parent::__construct($key, $secret);
     $this->ttl = $ttl;
     $this->user_id = $user_id;
 }
Exemplo n.º 17
0
 public function testOauthServiceAccess()
 {
     global $current_user;
     $request_token_info = $this->oauth->getRequestToken($this->url . "?method=oauth_request_token");
     $token = $request_token_info['oauth_token'];
     $secret = $request_token_info['oauth_token_secret'];
     $c_token = OAuthToken::load($token);
     $verify = $c_token->authorize(array("user" => $current_user->id));
     $this->oauth->setToken($token, $secret);
     $access_token_info = $this->oauth->getAccessToken($this->url . "?method=oauth_access_token&oauth_verifier={$verify}");
     $token = $access_token_info['oauth_token'];
     $secret = $access_token_info['oauth_token_secret'];
     $this->oauth->setToken($token, $secret);
     $res = $this->oauth->fetch($this->url . "?method=oauth_access&input_type=JSON&response_type=JSON");
     $this->assertTrue($res);
     $session = json_decode($this->oauth->getLastResponse(), true);
     $this->assertNotEmpty($session["id"]);
     // test fetch through OAuth
     $res = $this->oauth->fetch($this->url . "?method=get_user_id&input_type=JSON&response_type=JSON");
     $this->assertTrue($res);
     $id = json_decode($this->oauth->getLastResponse(), true);
     $this->assertEquals($current_user->id, $id);
     // test fetch through session initiated by OAuth
     $id2 = $this->_makeRESTCall('get_user_id', array("session" => $session["id"]));
     $this->assertEquals($current_user->id, $id2);
 }
Exemplo n.º 18
0
 function authorize_token($token, $consumer, $userid, $verifier)
 {
     //Implement me
     while ($row = pg_fetch_assoc($result)) {
         $reqUpdate = "Update ...";
         //Implement me
         $tokenTrouve = new OAuthToken($row["token_oauth"], $row["secret_oauth"], 1);
         $tokenTrouve->setIsAuthorized(true);
         return $tokenTrouve;
     }
 }
Exemplo n.º 19
0
 public function testdeleteByUser()
 {
     //execute the method and test if it works and does not throws an exception.
     try {
         OAuthToken::deleteByUser('1');
         $this->assertTrue(true);
     } catch (Exception $e) {
         $this->fail();
     }
 }
Exemplo n.º 20
0
 function new_access_token($token, $consumer, $verifier = null)
 {
     $c = Doctrine::getTable('sfOauthServerConsumer')->findOneByConsumerKey($consumer->key);
     $token = Doctrine::getTable('sfOauthServerRequestToken')->findOneByToken($token->key);
     $key = md5(time());
     $secret = time() + time();
     $accesstoken = new OAuthToken($key, md5(md5($secret)));
     $accesstoken = new sfOauthServerAccessToken();
     $accesstoken->setToken($key);
     $accesstoken->setSecret(md5(md5($secret)));
     $accesstoken->setConsumer($c);
     $accesstoken->setUserId($token->getUserId());
     $accesstoken->setScope($token->getScope());
     $accesstoken->save();
     $accesstoken = new OAuthToken($accesstoken->getToken(), $accesstoken->getSecret());
     return $accesstoken;
 }
 /**
  * Create OAuthRequest from Consumer and Token
  *
  * @param OAuthConsumer $consumer - OAuthConsumer
  * @param OAuthToken $token - OAuthToken
  * @param String $httpMethod - http method
  * @param String $httpURL - http URL
  * @param array|null $parameters - parameters
  * @return OAuthRequest
  */
 public static function createFromConsumerAndToken($consumer, $token, $httpMethod, $httpURL, $parameters = null)
 {
     @$parameters or $parameters = array();
     $nonce = OAuthRequest::generateNonce();
     $timestamp = OAuthRequest::generateTimestamp();
     $default = array('oauth_version' => OAuthRequest::VERSION, 'oauth_nonce' => $nonce, 'oauth_timestamp' => $timestamp, 'oauth_consumer_key' => $consumer->getKey());
     if ($token) {
         $default['oauth_token'] = $token->getKey();
     }
     $parameters = array_merge($default, $parameters);
     $urlParts = parse_url($httpURL);
     if (isset($urlParts['query']) && $urlParts['query']) {
         $params = OAuthUtils::parseParameterFromString($urlParts['query']);
         $parameters = array_merge($params, $parameters);
     }
     return new OAuthRequest($httpMethod, $httpURL, $parameters, $nonce, $timestamp);
 }