getAccessToken() public method

Exchange request token and secret for an access token and secret, to sign API calls.
public getAccessToken ( $oauth_verifier )
Example #1
0
 public function callBack()
 {
     /* If the oauth_token is old redirect to the connect page. */
     //	if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token'])
     if (isset($_REQUEST['oauth_token']) && $this->session->userdata('oauth_token') !== $_REQUEST['oauth_token']) {
         //		$_SESSION['oauth_status'] = 'oldtoken';
         //		header('Location: ./clearsessions.php');
         echo "bad oauth_token";
         return false;
     }
     /* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
     $connection = new TwitterOAuth(_TWITTER_CONSUMER_KEY_, _TWITTER_CONSUMER_SECRET_, $this->session->userdata('oauth_token'), $this->session->userdata('oauth_token_secret'));
     /* Request access tokens from twitter */
     $access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
     /* Save the access tokens. Normally these would be saved in a database for future use. */
     $_SESSION['access_token'] = $access_token;
     $this->db_update("users", $access_token, array("id" => $this->session->userdata('id')));
     //		/* Remove no longer needed request tokens */
     //		unset($_SESSION['oauth_token']);
     //		unset($_SESSION['oauth_token_secret']);
     /* If HTTP response is 200 continue otherwise send to connect page to retry */
     if (200 == $connection->http_code) {
         /* The user has been verified and the access tokens can be saved for future use */
         //			$_SESSION['status'] = 'verified';
         //			header('Location: ./index.php');
         echo "TWITTER OK";
     } else {
         /* Save HTTP status for error dialog on connnect page.*/
         //			header('Location: ./clearsessions.php');
         echo "ERROR";
     }
 }
Example #2
0
 function getUserAccessToken()
 {
     $session_access_token = $this->constructSessionVariableName("access_token");
     $token = NULL;
     if (isset($_SESSION[$session_access_token])) {
         $token = $_SESSION[$session_access_token];
         if (!$token || !isset($token["oauth_token"])) {
             unset($_SESSION[$session_access_token]);
         }
     }
     if (!$token) {
         $session_request_token = $this->constructSessionVariableName("oauth_request_token");
         $session_request_token_secret = $this->constructSessionVariableName("oauth_request_token_secret");
         if (isset($_SESSION[$session_request_token]) && isset($_SESSION[$session_request_token_secret])) {
             $to = new TwitterOAuth($this->getTwitter()->consumer->key, $this->getTwitter()->consumer->secret, $_SESSION[$session_request_token], $_SESSION[$session_request_token_secret]);
             $token = $to->getAccessToken($_REQUEST['oauth_verifier']);
             if (!$token || !isset($token["oauth_token"])) {
                 unset($_SESSION[$session_request_token]);
                 unset($_SESSION[$session_request_token_secret]);
             } else {
                 $session_var_name = $this->constructSessionVariableName("access_token");
                 $_SESSION[$session_var_name] = $token;
             }
         }
     }
     return $token;
 }
Example #3
0
 public static function initComment($api)
 {
     session_start();
     $options = Typecho_Widget::widget('Widget_Options');
     $config = $options->plugin('ConnectToTwitter');
     //发送请求到twitter
     if (isset($api->request->connect_to_twitter)) {
         $to = new TwitterOAuth($config->consumerKey, $config->consumerSecret);
         $tok = $to->getRequestToken();
         Typecho_Cookie::set('oauth_request_token', $tok['oauth_token']);
         Typecho_Cookie::set('oauth_request_token_secret', $tok['oauth_token_secret']);
         /* Build the authorization URL */
         $request_link = $to->getAuthorizeURL($tok['oauth_token']);
         header('Location:' . $request_link);
     }
     //从twitter返回
     if (isset($api->request->oauth_token)) {
         if (Typecho_Cookie::get('oauth_request_token') && Typecho_Cookie::get('oauth_request_token_secret')) {
             $to = new TwitterOAuth($config->consumerKey, $config->consumerSecret, Typecho_Cookie::get('oauth_request_token'), Typecho_Cookie::get('oauth_request_token_secret'));
             $tok = $to->getAccessToken();
             Typecho_Cookie::set('oauth_access_token', $tok['oauth_token'], time() + 60 * 60 * 24 * 30);
             Typecho_Cookie::set('oauth_access_token_secret', $tok['oauth_token_secret'], time() + 60 * 60 * 24 * 30);
             $info_json = $to->OAuthRequest('https://twitter.com/account/verify_credentials.json', array(), 'GET');
             $info = Typecho_Json::decode($info_json, true);
             self::twitterLogin($info, $api);
         }
     }
 }
Example #4
0
 /**
  * Used to add new record to Access Tokens Table
  *
  * @access public
  *
  * @param $oauth_verifier - $_REQUEST['code'] from controller
  * @param $profile_id
  *
  * @return string
  * @throws Exception
  */
 public function add_new_account($oauth_verifier, $profile_id)
 {
     $oauth_token = $this->_ci->session->userdata('oauth_token');
     $oauth_token_secret = $this->_ci->session->userdata('oauth_token_secret');
     $connection = new TwitterOAuth($this->_config['consumer_key'], $this->_config['consumer_secret'], $oauth_token, $oauth_token_secret);
     $token_credentials = $connection->getAccessToken($oauth_verifier);
     $tokens = array('token' => $token_credentials['oauth_token'], 'secret_token' => $token_credentials['oauth_token_secret']);
     try {
         if (empty($this->_user_id)) {
             throw new Exception("There in no active user to connect to twitter.");
         }
         $tokens['username'] = $token_credentials['screen_name'];
         $socialFullInfo = $this->get_user_full_info($tokens['username']);
         if (empty($socialFullInfo->name)) {
             throw new Exception("Invalid twitter's user data. Please try to reconnect.");
         }
         $tokens['name'] = $socialFullInfo->name;
         $tokens['image'] = $socialFullInfo->profile_image_url;
         $access_token = new Access_token();
         $token = $access_token->add_token($tokens, 'twitter', $this->_user_id);
         if (!$token->exists()) {
             throw new Exception("Cant save twitter access data. Please try to reconnect.");
         }
         $social_group = new Social_group($profile_id);
         $social_group->save(array('access_token' => $token));
     } catch (Exception $e) {
         throw $e;
     }
     $redirect_url = site_url('settings/socialmedia');
     return $redirect_url;
 }
 protected function authTwitter($save_name)
 {
     $config = $this->config;
     $conn = new TwitterOAuth($config['consumer_key'], $config['consumer_secret']);
     $request_token = $conn->getRequestToken();
     if ($request_token === false || $conn->lastStatusCode() != 200) {
         throw new RuntimeException("Error fetching Twitter auth token: Status code " . $conn->lastStatusCode() . '; ' . $conn->http_error);
     }
     $url = $conn->getAuthorizeURL($request_token);
     // Automatically send the user to the auth page.
     $ui = new UI();
     $ui->openBrowser($url);
     $pin = $ui->readline("Please visit {$url} then type the pin number: ");
     $conn = new TwitterOAuth($config['consumer_key'], $config['consumer_secret'], $request_token['oauth_token'], $request_token['oauth_token_secret']);
     $access_token = $conn->getAccessToken($pin);
     if ($access_token === false || $conn->lastStatusCode() != 200) {
         throw new RuntimeException("Error fetching Twitter access token: Status code " . $conn->lastStatusCode() . '; ' . $conn->http_error);
     }
     $this->config['oauth_token'] = $access_token['oauth_token'];
     $this->config['oauth_token_secret'] = $access_token['oauth_token_secret'];
     echo "Your Twitter token is " . $access_token['oauth_token'] . "\n";
     echo "Your Twitter token secret is " . $access_token['oauth_token_secret'] . "\n";
     echo "(Written to twitter-{$save_name}.txt)\n";
     if (file_put_contents("twitter-{$save_name}.txt", $access_token['oauth_token'] . "\n" . $access_token['oauth_token_secret'])) {
         return;
     }
     throw new RuntimeException("Failed to save oauth token to twitter-{$save_name}.txt");
 }
Example #6
0
 public static function getToken($oauthToken, $oauthTokenSecret, $oauthVerifier)
 {
     list($consumerKey, $consumerSecret) = bdSocialShare_Option::getTwitterConsumerPair();
     $twitter = new TwitterOAuth($consumerKey, $consumerSecret, $oauthToken, $oauthTokenSecret);
     $token = $twitter->getAccessToken($oauthVerifier);
     return $token;
 }
Example #7
0
 /**
  * Verify credentials and redirect based on response from Twitter.
  */
 public function callback()
 {
     require_once MODPATH . "twitter/vendor/twitteroauth/twitteroauth.php";
     $consumer_key = module::get_var("twitter", "consumer_key");
     $consumer_secret = module::get_var("twitter", "consumer_secret");
     $oauth_token = Session::instance()->get("twitter_oauth_token");
     $oauth_token_secret = Session::instance()->get("twitter_oauth_token_secret");
     $item_url = Session::instance()->get("twitter_item_redirect");
     // If the oauth_token is old redirect to the connect page
     if (isset($_REQUEST['oauth_token']) && $oauth_token !== $_REQUEST['oauth_token']) {
         Session::instance()->set("twitter_oauth_status", "old_token");
         $this->_clear_session();
         url::redirect(url::site("twitter/redirect"));
     }
     // Create TwitteroAuth object with app key/secret and token key/secret from default phase
     $connection = new TwitterOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
     // Request access tokens from twitter
     $access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
     // Save the access tokens
     Session::instance()->set("twitter_access_token", $access_token);
     // Remove no longer needed request tokens
     Session::instance()->delete("twitter_oauth_token");
     Session::instance()->delete("twitter_oauth_token_secret");
     // If HTTP response is 200 continue otherwise send to connect page to retry
     if (200 == $connection->http_code) {
         $this->_save_user($access_token);
         $item = ORM::factory("item", $item_id);
         url::redirect(url::abs_site($item_url));
     } else {
         log::error("content", "Twitter", "Unable to retrieve user access token: " . $connection->http_code);
         $this->_clear_session();
         url::redirect(url::site("twitter/redirect"));
     }
 }
Example #8
0
 /**
  * Return info about login user
  * @param $oauthToken
  * @param $oauthVerifier
  * @return \API|mixed
  * @throws Exception
  */
 public function getMe($oauthToken, $oauthVerifier)
 {
     $sessionSection = $this->session->getSection("twitter");
     if ($oauthToken != "" && $sessionSection->oauth_token !== $oauthToken) {
         //$sessionSection->oauth_status = 'oldtoken';
         throw new Exception("Twitter token is old. Try again login");
     }
     //Create TwitteroAuth object with app key/secret and token key/secret from default phase
     $this->twitterOAuth = new \TwitterOAuth($this->params["consumerKey"], $this->params["consumerSecret"], $sessionSection->oauth_token, $sessionSection->oauth_token_secret);
     //Request access tokens from twitter
     $access_token = $this->twitterOAuth->getAccessToken($oauthVerifier);
     //Save the access tokens
     $sessionSection->access_token = $access_token;
     // Remove no longer needed request tokens
     unset($sessionSection->oauth_token);
     unset($sessionSection->oauth_token_secret);
     if (200 != $this->twitterOAuth->http_code) {
         //Save HTTP status for error dialog on connnect page.
         throw new Exception("Twitter login. Something is wrong");
     }
     //The user has been verified
     //$sessionSection->status = 'verified';
     $user_info = $this->twitterOAuth->get('account/verify_credentials');
     $this->setSocialLoginCookie(self::SOCIAL_NAME);
     return $user_info;
 }
Example #9
0
 public function test()
 {
     $aModel = TuiyoLoader::model("applications", true);
     $aUser = TuiyoAPI::get("user", null);
     $aDocument = TuiyoAPI::get("document", null);
     $aParams = $aModel->getSingleUserPlugin($aUser->id, "twitter");
     if (!is_object($aParams)) {
         $aDocument->enqueMessage(_("Cannot Load the service for this user"), "error");
         return false;
     }
     echo $aParams->get("oauth_verifier");
     /* Build TwitterOAuth object with client credentials. */
     $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
     $view =& $this->getView("twitter", "html");
     /* Get temporary credentials. */
     $access_token = $connection->getAccessToken($aParams->get('oauth_verifier', false));
     /* Create a TwitterOauth object with consumer/user tokens. */
     $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
     /* If method is set change API call made. Test is called by default. */
     $content = $connection->get('account/verify_credentials');
     //print_R($content);
     $user = $connection->get('account/verify_credentials');
     $userPublicFeeds = $connection->get('statuses/public_timeline');
     print_R($userPublicFeeds);
 }
Example #10
0
 public function twitter_login()
 {
     $a = $this->session->userdata('token');
     if ($a) {
         $connection = new TwitterOAuth('NXN5bPRLh6npCLauKil2FMoq5', '4aWzIN9yuV80f16odPxkFKeWftwkvGeVjbBt9sTPYyfCaUb4sf', $this->session->userdata('token'), $this->session->userdata('token_secret'));
         if (!empty($_REQUEST['oauth_verifier'])) {
             $oauth_verifier = $_REQUEST['oauth_verifier'];
         } else {
             redirect('auth/log_out');
         }
         $access_token = $connection->getAccessToken($oauth_verifier);
         $data = array('id' => $access_token['user_id'], 'first_name' => $access_token['screen_name'], 'last_name' => $access_token['screen_name'], 'isLogged' => TRUE, 'role' => 0);
         $this->session->set_userdata($data);
         $twiter_users = $this->users_model->get_record_by_filed(array('id' => $access_token['user_id']));
         if (count($twiter_users) == 0) {
             $last_id = $this->users_model->insert_data($data);
         } else {
             $last_id = $this->users_model->get_record(array('id' => $access_token['user_id']));
             $this->users_model->update_record($last_id->id, $data);
         }
         redirect('frontend/home');
     } else {
         $connection = new TwitterOAuth('NXN5bPRLh6npCLauKil2FMoq5', '4aWzIN9yuV80f16odPxkFKeWftwkvGeVjbBt9sTPYyfCaUb4sf');
         $request_token = $connection->getRequestToken('http://shop.loc/auth/twitter_login');
         $data = array('token' => $request_token['oauth_token'], 'token_secret' => $request_token['oauth_token_secret']);
         $this->session->set_userdata($data);
         if ($connection->http_code == '200') {
             $twitter_url = $connection->getAuthorizeURL($request_token['oauth_token']);
             header('Location: ' . $twitter_url);
         } else {
             die("error connecting to twitter! try again later!");
         }
     }
 }
Example #11
0
 function index()
 {
     require APPPATH . 'modules/twitter/libraries/twitteroauth.php';
     /* If the oauth_token is old redirect to the connect page. */
     if ($this->input->get('oauth_token') && $this->session->userdata('twitter_oauth_token') !== $this->input->get('oauth_token')) {
         return redirect('admincp/twitter');
     }
     /* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
     $connection = new TwitterOAuth(setting('twitter_consumer_key'), setting('twitter_consumer_secret'), $this->session->userdata('twitter_oauth_token'), $this->session->userdata('twitter_oauth_token_secret'));
     /* Request access tokens from twitter */
     $access_token = $connection->getAccessToken($this->input->get('oauth_verifier'));
     /* Save the access tokens. Normally these would be saved in a database for future use. */
     $this->settings_model->update_setting('twitter_oauth_token', $access_token['oauth_token']);
     $this->settings_model->update_setting('twitter_oauth_token_secret', $access_token['oauth_token_secret']);
     /* Remove no longer needed request tokens */
     $this->session->unset_userdata('twitter_oauth_token');
     $this->session->unset_userdata('twitter_oauth_token_secret');
     /* If HTTP response is 200 continue otherwise send to connect page to retry */
     if (200 == $connection->http_code) {
         $this->notices->SetNotice('OAuthorization retrieved successfully.');
         return redirect('admincp/twitter');
     } else {
         $this->notices->SetError('Error making connection in OAuth callback.');
         return redirect('admincp/twitter');
     }
 }
Example #12
0
function twittercallback()
{
    $twitter = new TwitterOAuth(TWITTER_APIKEY, TWITTER_APISECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
    $token = $twitter->getAccessToken($_REQUEST['oauth_verifier']);
    $account = $twitter->get('account/verify_credentials');
    header('Location: ' . BASE_URL . 'connect/add/twitter/' . base64_encode($token['user_id']) . '/' . base64_encode($token['screen_name']) . '/' . base64_encode($token['oauth_token']) . '/' . base64_encode($token['oauth_token_secret']) . '/' . base64_encode($account->profile_image_url_https));
    exit;
}
 public function callbackAction(Request $request)
 {
     /****Check language session*******/
     $session = $request->getSession();
     $this->langsession($session);
     $lan = $session->get('language');
     $request->setLocale($lan);
     $username = $session->get('user');
     $em = $this->getDoctrine()->getManager();
     $appkey = $this->container->get('mytrip_admin.helper.twitter')->getOption('apikey');
     $appsecretkey = $this->container->get('mytrip_admin.helper.twitter')->getOption('apisecretkey');
     $twitteroauth = new \TwitterOAuth($appkey, $appsecretkey, $session->get('oauth_token'), $session->get('oauth_token_secret'));
     //\TwitterOAuth::setAuth($appkey, $appsecretkey,$session->get('oauth_token'), $session->get('oauth_token_secret'));
     $access_token = $twitteroauth->getAccessToken($_REQUEST['oauth_verifier']);
     $content = $twitteroauth->get('account/verify_credentials');
     if (!empty($content)) {
         if (!empty($username)) {
             $uid = $username['userId'];
             $check_social_link = $em->createQuery("SELECT p FROM MytripAdminBundle:UserSocialLink p WHERE p.user='******' AND p.socialLink='Twitter' AND p.id='" . $content->id . "'")->getArrayResult();
             if (empty($check_social_link)) {
                 $social_links = new \Mytrip\AdminBundle\Entity\UserSocialLink();
                 $social_links->setUser($this->getDoctrine()->getRepository('MytripAdminBundle:User')->find($uid));
                 $social_links->setSocialLink('Twitter');
                 $social_links->setId($content->id);
                 $social_links->setImage($content->profile_image_url);
                 $social_links->setCreatedDate(new \DateTime(date('Y-m-d H:i:s')));
                 $em->persist($social_links);
                 $em->flush();
             }
             return $this->redirect($this->generateUrl('mytrip_user_profile'));
         } else {
             $check_social_link = $em->createQuery("SELECT p,IDENTITY(p.user) AS user FROM MytripAdminBundle:UserSocialLink p WHERE p.socialLink='Twitter' AND p.id='" . $content->id . "'")->getArrayResult();
             if (!empty($check_social_link)) {
                 $user = $em->createQuery("SELECT p FROM MytripAdminBundle:User p WHERE p.userId='" . $check_social_link[0]['user'] . "' AND p.status NOT IN ('Trash')")->getArrayResult();
                 if (!empty($user)) {
                     $session->set('user', $user[0]);
                     $session->set('UserLogin', "True");
                     return $this->redirect($this->generateUrl('mytrip_user_profile'));
                 } else {
                     $session->set('twittercontent', $content);
                     $this->get('session')->getFlashBag()->add('twit', '1');
                     return $this->redirect($this->generateUrl('mytrip_user_homepage'));
                 }
             } else {
                 $session->set('twittercontent', $content);
                 $this->get('session')->getFlashBag()->add('twit', '1');
                 return $this->redirect($this->generateUrl('mytrip_user_homepage'));
             }
         }
     } else {
         $this->get('session')->getFlashBag()->add('success', $this->get('translator')->trans('Sorry, Please try again'));
         if (empty($username)) {
             return $this->redirect($this->generateUrl('mytrip_user_homepage'));
         } else {
             return $this->redirect($this->generateUrl('mytrip_user_profile'));
         }
     }
 }
Example #14
0
 /**
  * This method is used to process the second part of authentication workflow, after redirect
  *
  * @return array Array with status and user details
  */
 public function processAuth()
 {
     $ngConnectINI = eZINI::instance('ngconnect.ini');
     $http = eZHTTPTool::instance();
     $consumerKey = trim($ngConnectINI->variable('LoginMethod_twitter', 'AppConsumerKey'));
     $consumerSecret = trim($ngConnectINI->variable('LoginMethod_twitter', 'AppConsumerSecret'));
     if (empty($consumerKey) || empty($consumerSecret)) {
         return array('status' => 'error', 'message' => 'Consumer key or consumer secret undefined.');
     }
     $oAuthToken = trim($http->getVariable('oauth_token', ''));
     $oAuthVerifier = trim($http->getVariable('oauth_verifier', ''));
     $state = trim($http->getVariable('state', ''));
     if (empty($oAuthToken) || empty($oAuthVerifier) || empty($state)) {
         return array('status' => 'error', 'message' => 'oauth_token, oauth_verifier or state GET parameters undefined.');
     }
     if (!$http->hasSessionVariable('NGConnectOAuthState') || $state != $http->sessionVariable('NGConnectOAuthState')) {
         $http->removeSessionVariable('NGConnectOAuthState');
         return array('status' => 'error', 'message' => 'State parameter does not match stored value.');
     } else {
         $http->removeSessionVariable('NGConnectOAuthState');
     }
     if (!$http->hasSessionVariable('NGConnectOAuthToken') || !$http->hasSessionVariable('NGConnectOAuthTokenSecret') || $oAuthToken != $http->sessionVariable('NGConnectOAuthToken')) {
         $http->removeSessionVariable('NGConnectOAuthToken');
         $http->removeSessionVariable('NGConnectOAuthTokenSecret');
         return array('status' => 'error', 'message' => 'Token does not match stored value.');
     } else {
         $oAuthTokenSecret = $http->sessionVariable('NGConnectOAuthTokenSecret');
         $http->removeSessionVariable('NGConnectOAuthToken');
         $http->removeSessionVariable('NGConnectOAuthTokenSecret');
     }
     $connection = new TwitterOAuth($consumerKey, $consumerSecret, $oAuthToken, $oAuthTokenSecret);
     $connection->host = self::TWITTER_API_URI;
     $accessToken = $connection->getAccessToken($oAuthVerifier);
     if (!(isset($accessToken['oauth_token']) && isset($accessToken['oauth_token_secret']))) {
         return array('status' => 'error', 'message' => 'Error while retrieving access token.');
     }
     $connection = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken['oauth_token'], $accessToken['oauth_token_secret']);
     $connection->host = self::TWITTER_API_URI;
     $user = $connection->get(self::TWITTER_USER_API_URI);
     if (!isset($user->id) || empty($user->id)) {
         return array('status' => 'error', 'message' => 'Invalid Twitter user.');
     }
     if (isset($user->profile_image_url) && !empty($user->profile_image_url)) {
         $pictureUri = $user->profile_image_url;
         $imageSize = trim($ngConnectINI->variable('LoginMethod_twitter', 'ImageSize'));
         if ($imageSize == 'original') {
             //Hm... it seems there's no way to get the full size image through API
             //Even https://api.twitter.com/1/users/profile_image/username never returns full version
             //Replacing is not safe, but at least we're replacing last occurrence
             $pictureUri = substr_replace($user->profile_image_url, '', strrpos($user->profile_image_url, '_normal'), 7);
         }
     } else {
         $pictureUri = '';
     }
     $result = array('status' => 'success', 'login_method' => 'twitter', 'id' => $user->id, 'first_name' => isset($user->name) ? $user->name : '', 'last_name' => '', 'email' => '', 'picture' => $pictureUri);
     return $result;
 }
Example #15
0
 public function action_twittercallback()
 {
     if (arr::get($_GET, 'denied', false)) {
         notes::error('Seems like you didn\'t want to log in with Twitter anyway. Feel free to try again if it was a mistake!');
         site::redirect();
     }
     $token = arr::get($_GET, 'oauth_token', false);
     $verifier = arr::get($_GET, 'oauth_verifier', false);
     if (!$token || !$verifier) {
         notes::error('Something went wrong in the process, and we didn\'t get the expected data back from Twitter. Please try again');
         site::redirect();
     }
     $connection = new TwitterOAuth(arr::get($this->creds, 'key'), arr::get($this->creds, 'secret'), Session::instance()->get_once('twitter_oauth_token'), Session::instance()->get_once('twitter_oauth_token_secret'));
     $token = $connection->getAccessToken($verifier);
     $oauth_token = arr::get($token, 'oauth_token', '');
     $oauth_token_secret = arr::get($token, 'oauth_token_secret', '');
     $user_id = arr::get($token, 'user_id', '');
     $screen_name = arr::get($token, 'screen_name', '');
     $oauth = ORM::factory('Oauth')->where('type', '=', 'twitter')->where('token', '=', $oauth_token)->find();
     if ($oauth->loaded()) {
         try {
             $user = $oauth->user;
             user::force_login($user);
         } catch (exception $e) {
             if ($user->loaded()) {
                 if (user::logged()) {
                     // Random error, but user got logged in. We don't care, YOLO!
                 } else {
                     notes::error('Whoops! Something wen\'t wrong and we couldn\'t log you in. Please try again or send us a message if the problem persists.');
                     Kohana::$log->add(Log::ERROR, '1. Couldnt log user in: ' . $e->getMessage());
                 }
             }
         }
         site::redirect('write');
     } else {
         try {
             $user = ORM::factory('User');
             $user->username = $screen_name;
             $user->validation_required(false)->save();
             $user->add_role('login');
             $oauth = ORM::factory('Oauth');
             $oauth->user_id = $user->id;
             $oauth->type = 'twitter';
             $oauth->token = $oauth_token;
             $oauth->token_secret = $oauth_token_secret;
             $oauth->service_id = $user_id;
             $oauth->screen_name = $screen_name;
             $oauth->save();
             user::force_login($user);
         } catch (exception $e) {
             Kohana::$log->add(Log::ERROR, '2. Couldnt create user: '******'Whoops! Something wen\'t wrong and we couldn\'t log you in. Please try again or send us a message if the problem persists.');
         }
         site::redirect('/write');
     }
 }
Example #16
0
    function run()
    {
        parent::run();
        if ($_REQUEST['oauth_token']) {
            $connection = new TwitterOAuth(WRA_CONF::$twiappid, WRA_CONF::$twiappsecret, $_REQUEST['oauth_token'], $_REQUEST['oauth_verifier']);
            $token_credentials = $connection->getAccessToken($_REQUEST['oauth_verifier']);
            $connection = new TwitterOAuth(WRA_CONF::$twiappid, WRA_CONF::$twiappsecret, $token_credentials['oauth_token'], $token_credentials['oauth_token_secret']);
            $account = $connection->get('account/verify_credentials');
            // WRA::debug($ctwe);
            if ($account) {
                // WRA::debug($user);
                $nu = new wra_twu();
                $nu->display_name = htmlspecialchars($account->screen_name, ENT_QUOTES);
                //$user->name;
                $nu->regdate = WRA::getcurtime();
                $nu->twuserid = $account->id;
                // $nu->userid = $usr;
                $nu->username = htmlspecialchars($account->name, ENT_QUOTES);
                $nu->usersurname = htmlspecialchars($user['last_name'], ENT_QUOTES);
                $nu->link = $account->url;
                //$user->link;
                $nu->user_agent = wra_fbu::getbrowser();
                $nu->access_token = $token_credentials['oauth_token'];
                $nu->email = $token_credentials['oauth_token_secret'];
                $nu->photo = $account->profile_image_url;
                if ($account->notifications) {
                    $nu->gender = 0;
                } else {
                    $nu->gender = 1;
                }
                $nu->phone = '';
                if (!empty($nu->twuserid)) {
                    if (!wra_twu::istwexist($nu->twuserid)) {
                        $nu->userid = $this->addUsr($nu->username, $nu->usersurname, $nu->phone, $nu->email, "asdf" . time(), $nu->photo);
                        $nu->add();
                    } else {
                        $nu->loadbytw($nu->twuserid);
                        $nu->update();
                    }
                    wra_twu::twd($nu->twuserid, $nu->userid);
                }
                if (empty($_SESSION['lastpage'])) {
                    WRA::gotopage(WRA::base_url() . '?from=tw&show=no');
                } else {
                    WRA::gotopage(WRA::base_url() . $_SESSION['lastpage']);
                }
                $_SESSION['lastpage'] = '';
            }
        } else {
            ?>
<a href="<?php 
            WRA::e(wra_twitter::loginLink());
            ?>
">login</a><?php 
        }
    }
 public function callbackAction()
 {
     $oauth_token = $this->getRequest()->getParam('oauth_token');
     $oauth_verifier = $this->getRequest()->getParam('oauth_verifier');
     if (!$oauth_token || !$oauth_verifier) {
         return $this->_redirectUrl();
     }
     if ($oauth_token != Mage::getSingleton('core/session')->getData('oauth_token')) {
         return $this->_redirectUrl();
     }
     $connection = new TwitterOAuth(Mage::getStoreConfig('gomage_social/twitter/id'), Mage::getStoreConfig('gomage_social/twitter/secret'), Mage::getSingleton('core/session')->getData('oauth_token'), Mage::getSingleton('core/session')->getData('oauth_token_secret'));
     $access_token = $connection->getAccessToken($oauth_verifier);
     Mage::getSingleton('core/session')->unsetData('oauth_token');
     Mage::getSingleton('core/session')->unsetData('oauth_token_secret');
     $profile = null;
     switch ($connection->http_code) {
         case 200:
             $profile = $connection->get('account/verify_credentials');
             break;
         default:
             $this->getSession()->addError($this->__('Could not connect to Twitter. Refresh the page or try again later.'));
             return $this->_redirectUrl();
     }
     if ($profile) {
         if ($profile->id) {
             $social_collection = Mage::getModel('gomage_social/entity')->getCollection()->addFieldToFilter('social_id', $profile->id)->addFieldToFilter('type_id', GoMage_Social_Model_Type::TWITTER);
             if (Mage::getSingleton('customer/config_share')->isWebsiteScope()) {
                 $social_collection->addFieldToFilter('website_id', Mage::app()->getWebsite()->getId());
             }
             $social = $social_collection->getFirstItem();
             if ($social && $social->getId()) {
                 if ($social->social_id == $profile->id) {
                     $customer = Mage::getModel('customer/customer');
                     if (Mage::getSingleton('customer/config_share')->isWebsiteScope()) {
                         $customer->setWebsiteId(Mage::app()->getWebsite()->getId());
                     }
                     $customer->load($social->getData('customer_id'));
                     if ($customer && $customer->getId()) {
                         if (!$customer->getConfirmation()) {
                             $this->getSession()->loginById($customer->getId());
                         } else {
                             $this->getSession()->addError($this->__('This account is not confirmed.'));
                         }
                     }
                 }
             } else {
                 $profile->url = Mage::getUrl('gomage_social/twitter/checkEmail', array('_secure' => true));
                 $profile->urlEmailClose = Mage::getUrl('gomage_social/twitter/emailClose', array('_secure' => true));
                 $profile->type_id = GoMage_Social_Model_Type::TWITTER;
                 Mage::getSingleton('core/session')->setGsProfile($profile);
             }
         }
     }
     return $this->_redirectUrl();
 }
Example #18
0
 public function actionTwitter()
 {
     $twitterConfig = $this->context->parameters['twitter'];
     $twitterSession = $this->getSession('twitter');
     $twitter = new TwitterOAuth($twitterConfig['consumerKey'], $twitterConfig['consumerSecret'], $twitterSession->oauthToken, $twitterSession->oauthTokenSecret);
     $accessToken = $twitter->getAccessToken();
     $info = $twitter->get('/users/show', array('user_id' => $accessToken['user_id']));
     $authenticator = $this->context->twitterAuthenticator;
     $identity = $authenticator->authenticate($info);
     $this->getUser()->login($identity);
 }
 static function get_access_token()
 {
     /* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
     $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
     /* Request access tokens from twitter */
     $access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
     /* Remove no longer needed request tokens */
     unset($_SESSION['access_token']);
     unset($_SESSION['oauth_token']);
     unset($_SESSION['oauth_token_secret']);
     return $access_token;
 }
 public function authControl()
 {
     if (!$this->is_missing_param) {
         $request_token = $_GET['oauth_token'];
         $request_token_secret = SessionCache::get('oauth_request_token_secret');
         // get oauth values
         $plugin_option_dao = DAOFactory::GetDAO('PluginOptionDAO');
         $options = $plugin_option_dao->getOptionsHash('twitter', true);
         //get cached
         $to = new TwitterOAuth($options['oauth_consumer_key']->option_value, $options['oauth_consumer_secret']->option_value, $request_token, $request_token_secret);
         $tok = $to->getAccessToken();
         if (isset($tok['oauth_token']) && isset($tok['oauth_token_secret'])) {
             $api = new TwitterAPIAccessorOAuth($tok['oauth_token'], $tok['oauth_token_secret'], $options['oauth_consumer_key']->option_value, $options['oauth_consumer_secret']->option_value, $options['num_twitter_errors']->option_value, $options['max_api_calls_per_crawl']->option_value, false);
             $authed_twitter_user = $api->verifyCredentials();
             //                echo "User ID: ". $authed_twitter_user['user_id'];
             //                echo "User name: ". $authed_twitter_user['user_name'];
             $owner_dao = DAOFactory::getDAO('OwnerDAO');
             $owner = $owner_dao->getByEmail($this->getLoggedInUser());
             if ((int) $authed_twitter_user['user_id'] > 0) {
                 $instance_dao = DAOFactory::getDAO('TwitterInstanceDAO');
                 $instance = $instance_dao->getByUsername($authed_twitter_user['user_name'], 'twitter');
                 $owner_instance_dao = DAOFactory::getDAO('OwnerInstanceDAO');
                 if (isset($instance)) {
                     $owner_instance = $owner_instance_dao->get($owner->id, $instance->id);
                     if ($owner_instance != null) {
                         $owner_instance_dao->updateTokens($owner->id, $instance->id, $tok['oauth_token'], $tok['oauth_token_secret']);
                         $this->addSuccessMessage($authed_twitter_user['user_name'] . " on Twitter is already set up in ThinkUp! To add a different Twitter account, " . "log out of Twitter.com in your browser and authorize ThinkUp again.");
                     } else {
                         if ($owner_instance_dao->insert($owner->id, $instance->id, $tok['oauth_token'], $tok['oauth_token_secret'])) {
                             $this->addSuccessMessage("Success! " . $authed_twitter_user['user_name'] . " on Twitter has been added to ThinkUp!");
                         } else {
                             $this->addErrorMessage("Error: Could not create an owner instance.");
                         }
                     }
                 } else {
                     $instance_dao->insert($authed_twitter_user['user_id'], $authed_twitter_user['user_name']);
                     $instance = $instance_dao->getByUsername($authed_twitter_user['user_name']);
                     if ($owner_instance_dao->insert($owner->id, $instance->id, $tok['oauth_token'], $tok['oauth_token_secret'])) {
                         $this->addSuccessMessage("Success! " . $authed_twitter_user['user_name'] . " on Twitter has been added to ThinkUp!");
                     } else {
                         $this->addErrorMessage("Error: Could not create an owner instance.");
                     }
                 }
             }
         } else {
             $msg = "Error: Twitter authorization did not complete successfully. Check if your account already " . " exists. If not, please try again.";
             $this->addErrorMessage($msg);
         }
         $this->view_mgr->clear_all_cache();
     }
     return $this->generateView();
 }
Example #21
0
 function callback()
 {
     $oauth_token = Openbiz::$app->getSessionContext()->getVar('twitter_access_token');
     $Twitter = new TwitterOAuth($this->akey, $this->skey, $oauth_token['oauth_token'], $oauth_token['oauth_token_secret']);
     $access_token = $Twitter->getAccessToken($_REQUEST['oauth_verifier']);
     if (!$access_token) {
         throw new Exception('Unknown facebook AccessToken');
         return false;
     }
     Openbiz::$app->getSessionContext()->setVar($this->type . '_access_token', $access_token);
     $userInfo = $this->userInfo($access_token['oauth_token'], $access_token['oauth_token_secret']);
     $this->check($userInfo);
 }
Example #22
0
 public function callback()
 {
     // 트위터 인증 콜백
     require_once '../tf_app/ext/twitter/twitteroauth.php';
     // twitter connection
     $connection = new TwitterOAuth($this->settings->TWITTER_COMSUMER_KEY, $this->settings->TWITTER_COMSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
     // get token
     $access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
     $token = $access_token["oauth_token"];
     $token_secret = $access_token["oauth_token_secret"];
     // connect with user
     $connection = new TwitterOAuth($this->settings->TWITTER_COMSUMER_KEY, $this->settings->TWITTER_COMSUMER_SECRET, $token, $token_secret);
     // get user profile
     $user = $connection->get('account/verify_credentials');
     $screen_name = $user->screen_name;
     //스크린 네임을 안 가져올 경우
     if ($screen_name) {
         $users_ext = $this->Member_ext->get_by_ids_type($screen_name, Member_ext_model::TWITTER_TYPE);
     }
     print_r($users_ext);
     if (!$users_ext) {
         echo "a";
         if (!$this->Member_ext->get_by_user_id_type($_SESSION["temp"], Member_ext_model::TWITTER_TYPE)) {
             echo "b";
             $_arr["user_id"] = $_SESSION["temp"];
             $_arr["type"] = 2;
             $_arr["ids"] = $user->screen_name;
             $_arr["key"] = $token;
             $_arr["secret"] = $token_secret;
             $this->Member_ext->add($_arr);
             unset($_SESSION["temp"]);
             $this->assigns["tw"] = $user->screen_name;
             $_SESSION["s"]["tw"] = $this->Member_ext->get_by_user_id_type($_SESSION["temp"], 2);
         } else {
             echo "c";
             $_arr["user_id"] = $_SESSION["temp"];
             $_arr["type"] = 2;
             $_arr["ids"] = $user->screen_name;
             $_arr["key"] = $token;
             $_arr["secret"] = $token_secret;
             $this->Member_ext->edit($_arr);
             unset($_SESSION["temp"]);
             $this->assigns["tw"] = $user->screen_name;
             $_SESSION["s"]["tw"] = $this->Member_ext->get_by_user_id_type($_SESSION["temp"], 2);
         }
     } else {
         echo "d";
         $this->assigns["error"] = "aleady";
     }
 }
Example #23
0
 public static function authorize($user, $accessToken)
 {
     $culture = $user->getCulture();
     $profile = $user->getGuardUser()->getProfile();
     $connection = new TwitterOAuth(sfConfig::get("app_twitter_api_consumer_key_{$culture}"), sfConfig::get("app_twitter_api_consumer_secret_{$culture}"), $user->getAttribute('oauth_token', false, 'vo/twitter'), $user->getAttribute('oauth_token_secret', false, 'vo/twitter'));
     $accessToken = $connection->getAccessToken($accessToken);
     if ($connection->http_code == 200) {
         $profile->setTwOauthToken($accessToken['oauth_token']);
         $profile->setTwOauthTokenSecret($accessToken['oauth_token_secret']);
         $profile->save();
         $user->setAttribute('oauth_token', false, 'vo/twitter');
         $user->setAttribute('oauth_token_secret', false, 'vo/twitter');
     }
 }
Example #24
0
 public function callback()
 {
     Phalanx::loadClasses('twitteroauth');
     $connection = new TwitterOAuth(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, $this->session->oauth_token, $this->session->oauth_token_secret);
     $access_token = $connection->getAccessToken($this->get->oauth_verifier);
     $this->session->access_token = $access_token;
     $this->session->destroy('oauth_token');
     $this->session->destroy('oauth_token_secret');
     if ($connection->http_code == 200) {
         $this->session->twitter_status = 'verified';
         Phalanx::loadClasses('SocialNetwork');
         SocialNetwork::link_account($this->session->user->id, TWITTER, $access_token);
         Request::redirect(HOST . 'perfil/configuracoes/');
     }
 }
Example #25
0
 public function getAccessToken($redirectURL = null)
 {
     $http = eZHTTPTool::instance();
     if ($http->hasGetVariable('twitter_request_token') && $http->getVariable('twitter_request_token') !== $http->sessionVariable('twitter_request_token')) {
         throw new Exception('Wrong request token. Refresh the page or try again later.');
     }
     $connection = new TwitterOAuth($this->appSettings['key'], $this->appSettings['secret'], $http->sessionVariable('twitter_request_token'), $http->sessionVariable('twitter_request_token_secret'));
     $accessToken = $connection->getAccessToken($http->getVariable('oauth_verifier'));
     $http->removeSessionVariable('twitter_request_token');
     $http->removeSessionVariable('twitter_request_token_secret');
     if ((int) $connection->http_code === 200) {
         return array('token' => $accessToken['oauth_token'], 'secret' => $accessToken['oauth_token_secret'], 'user_id' => $accessToken['user_id']);
     }
     throw new Exception('Could not get access token. Refresh the page or try again later.');
 }
Example #26
0
 public function SetAccessToken()
 {
     require_once 'includes/twitteroauth.php';
     $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
     $access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
     $_SESSION['access_token'] = $access_token['oauth_token'];
     $_SESSION['access_secret'] = $access_token['oauth_token_secret'];
     unset($_SESSION['oauth_token']);
     unset($_SESSION['oauth_token_secret']);
     if (200 == $connection->http_code) {
         $_SESSION['status'] = 'verified';
         echo '<script>window.location.reload();</script>';
     } else {
         echo "Enter valid API Key and API Secret";
     }
 }
Example #27
0
function handleTwitterAuthentication($state)
{
    global $session;
    /*
     * 'default': Get a request token from Twitter for new user
     * 'returned': The user has authorized the app on Twitter and been returned
     */
    switch ($state) {
        case 'returned':
            $userDetailsJSON = NULL;
            try {
                $to = new TwitterOAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, $_SESSION['oauthRequestToken'], $_SESSION['oauthRequestTokenSecret']);
                $tok = $to->getAccessToken();
                $userDetails = $to->OAuthRequest('https://twitter.com/account/verify_credentials.json', array(), 'GET');
            } catch (Exception $e) {
                /*echo '01 - '.$e->getMessage();
                		debugDump();
                		exit();*/
                header("Location: logout.php");
            }
            $userDetailsJSON = json_decode($userDetails);
            $session->loggedIn = $session->createSession($userDetailsJSON->id, $tok['oauth_token'], $tok['oauth_token_secret'], $userDetailsJSON);
            if (!$session->loggedIn) {
                /*echo '02';
                		debugDump();
                		exit();*/
                header('Location: logout.php');
            }
            break;
        default:
            try {
                $to = new TwitterOAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET);
                $tok = $to->getRequestToken();
            } catch (Exception $e) {
                /*echo '02';
                		debugDump();
                		exit();*/
                header('Location: logout.php');
            }
            $_SESSION['oauthRequestToken'] = $token = $tok['oauth_token'];
            $_SESSION['oauthRequestTokenSecret'] = $tok['oauth_token_secret'];
            $_SESSION['oauthState'] = "start";
            $oAuthRequestLink = $to->getAuthorizeURL($token);
            include 'tmp/account/login.php';
            break;
    }
}
 public function index()
 {
     if ($this->customer->isLogged()) {
         $this->redirect(Url::createUrl("account/account"));
     }
     if (!$this->customer->isLogged() && (!$this->config->get('social_twitter_consumer_key') || !$this->config->get('social_twitter_consumer_secret'))) {
         $this->redirect(Url::createUrl("account/login", array("error" => "No se pudo iniciar sesion utilizando Twitter, por favor intente con otro servicio")));
     }
     $this->load->library('twitter_sdk/twitteroauth');
     if ($this->session->has("oauth_token") && $this->session->has("oauth_token_secret") && $this->request->hasQuery("oauth_verifier")) {
         $twitter = new TwitterOAuth($this->config->get('social_twitter_consumer_key'), $this->config->get('social_twitter_consumer_secret'), $this->session->get("oauth_token"), $this->session->get("oauth_token_secret"));
         $access_token = $twitter->getAccessToken($this->request->getQuery("oauth_verifier"));
         $user_info = $twitter->get('account/verify_credentials');
         $data = array("oauth_id" => $user_info->id, "company" => $user_info->name, "oauth_provider" => 'twitter', "oauth_token" => $this->session->get("oauth_token"), "oauth_token_secret" => $this->session->get("oauth_token_secret"));
         $result = $this->modelCustomer->getCustomerByTwitter($data);
         if ($result) {
             if ($this->customer->loginWithTwitter($data)) {
                 if (!$result['email']) {
                     $this->redirect(Url::createUrl("account/complete_profile"));
                 } elseif ($this->session->has('redirect')) {
                     $this->redirect(str_replace('&amp;', '&', $this->session->get('redirect')));
                 } else {
                     $this->redirect(Url::createUrl("common/home"));
                 }
             } else {
                 $this->redirect(Url::createUrl("account/login", array("error" => "No se pudo iniciar sesion utilizando Twitter, por favor intente con otro servicio")));
             }
         } elseif ($this->modelCustomer->addCustomerFromTwitter($data)) {
             if ($this->customer->loginWithTwitter($data)) {
                 $this->redirect(Url::createUrl("account/complete_profile"));
             } else {
                 $this->redirect(Url::createUrl("account/login", array("error" => "No se pudo iniciar sesion utilizando Twitter, por favor intente con otro servicio")));
             }
         }
     } else {
         $twitter = new TwitterOAuth($this->config->get('social_twitter_consumer_key'), $this->config->get('social_twitter_consumer_secret'));
         $request_token = $twitter->getRequestToken(Url::createUrl("api/twitter"));
         $this->session->set("oauth_token", $request_token['oauth_token']);
         $this->session->set("oauth_token_secret", $request_token['oauth_token_secret']);
         if ($twitter->http_code == '200') {
             $this->redirect($twitter->getAuthorizeURL($request_token['oauth_token']));
         } else {
             $this->redirect(Url::createUrl("account/login", array("error" => "No se pudo iniciar sesion utilizando Twitter, por favor intente con otro servicio")));
         }
     }
 }
Example #29
0
 public function complete()
 {
     $connection = new TwitterOAuth(Kohana::config('twitter.consumer_key'), Kohana::config('twitter.consumer_secret'), $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
     $access_token = $connection->getAccessToken();
     unset($_SESSION['oauth_token']);
     unset($_SESSION['oauth_token_secret']);
     if (200 == $connection->http_code) {
         $twitter_user = ORM::factory('twitter_user', $access_token['screen_name']);
         if ($twitter_user->loaded) {
             $user = ORM::factory('user', $twitter_user->user_id);
             Auth::instance()->force_login($user->username);
             $this->session->set_flash('notice', 'Logged you in via Twitter!');
             url::redirect('/user');
         } else {
             if (Auth::instance()->logged_in()) {
                 $twitter_user->username = $access_token['screen_name'];
                 $twitter_user->user_id = Auth::instance()->get_user()->id;
                 $twitter_user->save();
                 $this->session->set_flash('notice', 'Linked your Twitter account!');
                 url::redirect('/user');
             } else {
                 $user = ORM::factory('user')->where('username', $access_token['screen_name'])->find();
                 if (!$user->loaded) {
                     $user->email = '@' . $access_token['screen_name'] . '@twitter';
                     $user->username = $access_token['screen_name'];
                     $user->password = sha1($access_token['screen_name'] . time() . Kohana::config('qaargh.confirm_salt'));
                     $user->add(ORM::factory('role', 'login'));
                     $user->add(ORM::factory('role', 'twitter'));
                     $user->save();
                     $twitter_user->username = $access_token['screen_name'];
                     $twitter_user->user_id = $user->id;
                     $twitter_user->save();
                     Auth::instance()->force_login($user->username);
                     $this->session->set_flash('notice', 'Created your account via Twitter!');
                     url::redirect('/user');
                 } else {
                     $_SESSION['twitter_user'] = $access_token['screen_name'];
                     url::redirect('/twitter/account');
                 }
             }
         }
     } else {
         $this->session->set_flash('error', 'Server error using your Twitter credentials. Please try again.');
         url::redirect('/user/login');
     }
 }
Example #30
0
 public function __token()
 {
     /* Create a TwitterOauth object with consumer/user tokens. */
     $connection = new TwitterOAuth($this->appCode, $this->appSecret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
     /* Request access tokens from twitter */
     $access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
     // Save access token to session
     $this->token = $access_token;
     $_SESSION[self::SESSION_PREFIX . '_' . $this->id] = $access_token;
     /* Get logged in user to help with tests. */
     $user = $connection->get('account/verify_credentials');
     // Covert user data to generic user object
     if ($user) {
         $this->setUser((array) $user);
     }
     parent::__token();
 }