Users sessions are stored using HybridAuth storage system ( HybridAuth 2.0 handle PHP Session only) and can be accessed directly by
Hybrid_Auth::storage()->get($key) to retrieves the data for the given key, or calling
Hybrid_Auth::storage()->set($key, $value) to store the key => $value set.
public static storage ( ) : Hybrid_Storage | ||
return | Hybrid_Storage |
public static function getUser($token) { $config = \Config::get('hybridauth'); $socialAuth = new \Hybrid_Auth($config); $socialAuth->storage()->set("hauth_session.facebook.is_logged_in", 1); $socialAuth->storage()->set("hauth_session.facebook.token.access_token", $token); return SocialLoginManager::getUser('facebook'); }
public static function getUser($token, $secret) { $config = \Config::get('hybridauth'); $socialAuth = new \Hybrid_Auth($config); $socialAuth->storage()->set("hauth_session.twitter.is_logged_in", 1); $socialAuth->storage()->set("hauth_session.twitter.token.access_token", $token); $socialAuth->storage()->set("hauth_session.twitter.token.access_token_secret", $secret); return SocialLoginManager::getUser('twitter'); }
/** * finish login step */ function loginFinish() { parent::loginFinish(); $this->user->profile->emailVerified = $this->user->profile->email; // restore the user profile Hybrid_Auth::storage()->set("hauth_session.{$this->providerId}.user", $this->user); }
/** * finish login step */ function loginFinish() { parent::loginFinish(); $uid = str_replace("http://steamcommunity.com/openid/id/", "", $this->user->profile->identifier); if ($uid) { $data = @file_get_contents("http://steamcommunity.com/profiles/{$uid}/?xml=1"); $data = @new SimpleXMLElement($data); if (!is_object($data)) { return false; } $this->user->profile->displayName = (string) $data->{'steamID'}; $this->user->profile->photoURL = (string) $data->{'avatarMedium'}; $this->user->profile->description = (string) $data->{'summary'}; $realname = (string) $data->{'realname'}; if ($realname) { $this->user->profile->displayName = $realname; } $customURL = (string) $data->{'customURL'}; if ($customURL) { $this->user->profile->profileURL = "http://steamcommunity.com/id/{$customURL}/"; } // restore the user profile Hybrid_Auth::storage()->set("hauth_session.{$this->providerId}.user", $this->user); } }
/** * load the user profile from the IDp api client */ function getUserProfile() { // refresh tokens if needed $this->refreshToken(); // Vkontakte requires user id, not just token for api access $params['uid'] = Hybrid_Auth::storage()->get("hauth_session.{$this->providerId}.user_id"); $params['fields'] = 'first_name,last_name,nickname,screen_name,sex,bdate,timezone,photo_rec,photo_big'; // ask vkontakte api for user infos $response = $this->api->api("https://api.vk.com/method/getProfiles", 'GET', $params); if (!isset($response->response[0]) || !isset($response->response[0]->uid) || isset($response->error)) { throw new Exception("User profile request failed! {$this->providerId} returned an invalid response.", 6); } $response = $response->response[0]; $this->user->profile->identifier = property_exists($response, 'uid') ? $response->uid : ""; $this->user->profile->firstName = property_exists($response, 'first_name') ? $response->first_name : ""; $this->user->profile->lastName = property_exists($response, 'last_name') ? $response->last_name : ""; $this->user->profile->displayName = property_exists($response, 'nickname') ? $response->nickname : ""; $this->user->profile->photoURL = property_exists($response, 'photo_big') ? $response->photo_big : ""; $this->user->profile->profileURL = property_exists($response, 'screen_name') ? "http://vk.com/" . $response->screen_name : ""; if (property_exists($response, 'sex')) { switch ($response->sex) { case 1: $this->user->profile->gender = 'female'; break; case 2: $this->user->profile->gender = 'male'; break; default: $this->user->profile->gender = ''; break; } } return $this->user->profile; }
/** * finish login step */ function loginFinish() { parent::loginFinish(); $this->user->profile->profileURL = $this->user->profile->identifier; // https://ru.wargaming.net/id/5069690-Steel_Master/ $this->user->profile->identifier = preg_replace('/^[^0-9]+([0-9]+)-.+$/', '$1', $this->user->profile->identifier); // restore the user profile Hybrid_Auth::storage()->set("hauth_session.{$this->providerId}.user", $this->user); }
/** * finish login step */ function loginFinish() { if (!$_REQUEST['dr_auth_code']) { throw new Exception('Authentication failed! ' . $this->providerId . ' returned an invalid Token and Verifier.', 5); } $this->token('access_token', $_REQUEST['dr_auth_code']); // set user as logged in $this->setUserConnected(); Hybrid_Auth::storage()->set("hauth_session.{$this->providerId}.user", $this->user); }
function loginFinish() { parent::loginFinish(); $this->user->profile->identifier = str_ireplace("http://steamcommunity.com/openid/id/", "", $this->user->profile->identifier); if (!$this->user->profile->identifier) { throw new Exception("Authentication failed! {$this->providerId} returned an invalid user ID.", 5); } // If API key is not provided, use legacy API methods if (!empty($this->config['keys']['key'])) { $this->getUserProfileWebAPI($this->config['keys']['key']); } else { $this->getUserProfileLegacyAPI(); } Hybrid_Auth::storage()->set("hauth_session.{$this->providerId}.user", $this->user); }
/** * finish login step */ function loginFinish() { parent::loginFinish(); $this->user->profile->identifier = str_ireplace("http://steamcommunity.com/openid/id/", "", $this->user->profile->identifier); if (!$this->user->profile->identifier) { throw new Exception("Authentication failed! {$this->providerId} returned an invalid user ID.", 5); } // if api key is provided, we attempt to use steam web api if (isset(Hybrid_Auth::$config['providers']['Steam']['keys']['key']) && Hybrid_Auth::$config['providers']['Steam']['keys']['key']) { $userProfile = $this->getUserProfileWebAPI(Hybrid_Auth::$config['providers']['Steam']['keys']['key']); } else { $userProfile = $this->getUserProfileLegacyAPI(); } // fetch user profile foreach ($userProfile as $k => $v) { $this->user->profile->{$k} = $v ? $v : $this->user->profile->{$k}; } // store user profile Hybrid_Auth::storage()->set("hauth_session.{$this->providerId}.user", $this->user); }
/** * load the user profile from the IDp api client */ function getUserProfile() { // refresh tokens if needed $this->refreshToken(); // Vkontakte requires user id, not just token for api access $params['uid'] = Hybrid_Auth::storage()->get("hauth_session.{$this->providerId}.user_id"); $params['fields'] = implode(',', $this->fields); // ask vkontakte api for user infos $response = $this->api->api('getProfiles', 'GET', $params); if (!isset($response->response[0]) || !isset($response->response[0]->uid) || isset($response->error)) { throw new Exception("User profile request failed! {$this->providerId} returned an invalid response.", 6); } // Fill datas $response = reset($response->response); foreach ($this->getUserByResponse($response, true) as $k => $v) { $this->user->profile->{$k} = $v; } // Additional data $this->user->profile->email = Hybrid_Auth::storage()->get("hauth_session.{$this->providerId}.user_email"); return $this->user->profile; }
/** * clear all existen tokens for this provider */ public function clearTokens() { Hybrid_Auth::storage()->deleteMatch("hauth_session.{$this->providerId}."); }
` account to completely end your session.</p> <a class="button" href="<?php echo $url; ?> " ><span>Continue</span></a> </div> </body> <?php } else { if (!empty($provider)) { $SocialAuth_WP_providers = get_option('SocialAuth_WP_providers'); if (is_array($SocialAuth_WP_providers) && count($SocialAuth_WP_providers)) { $config = array(); if (isset($SocialAuth_WP_providers[$provider])) { $config["base_url"] = plugin_dir_url(__FILE__) . 'hybridauth/'; $config["providers"] = array(); //this si same as orig config, no need to amke config again $config["providers"][$provider] = $SocialAuth_WP_providers[$provider]; } else { echo "Current Provider is unknowun to system."; exit; } $config["providers"][$provider] = $HA_PROVIDER_CONFIG['providers'][$provider]; require_once dirname(__FILE__) . "/hybridauth/Hybrid/Auth.php"; $hybridauth = new Hybrid_Auth($config); Hybrid_Auth::storage()->delete("hauth_session.{$provider}.is_logged_in"); } } $a = preg_replace("/amp\\;/", "", $a); header('Location: ' . $a); }
/** * Meldet anhand von OAuth Token einen bestimmten Nutzer automatich an. * * @param string $providerId * @param string $token * @param string $secret * @return void */ private static function storeAccesToken($providerId, $token, $secret) { $key = 'hauth_session.' . $providerId . '.'; self::loadHybridAuth(); // store the keys Hybrid_Auth::storage()->set($key . 'token.access_token', $token); Hybrid_Auth::storage()->set($key . 'token.access_token_secret', $secret); // set the user as loged in! Hybrid_Auth::storage()->set($key . 'is_logged_in', 1); }
/** * Redirect the user to hauth_return_to (the callback url) * @return void */ function returnToCallbackUrl() { // get the stored callback url $callback_url = Hybrid_Auth::storage()->get("hauth_session.{$this->id}.hauth_return_to"); // if the user presses the back button in the browser and we already deleted the hauth_return_to from // the session in the previous request, we will redirect to '/' instead of displaying a blank page. if (!$callback_url) { $callback_url = '/'; } // remove some unneeded stored data Hybrid_Auth::storage()->delete("hauth_session.{$this->id}.hauth_return_to"); Hybrid_Auth::storage()->delete("hauth_session.{$this->id}.hauth_endpoint"); Hybrid_Auth::storage()->delete("hauth_session.{$this->id}.id_provider_params"); // back to home Hybrid_Auth::redirect($callback_url); }
/** * return api error */ public static function getApiError() { return Hybrid_Auth::storage() ? Hybrid_Auth::storage()->get("hauth_session.error.apierror") : ''; }
$app->get('/api/languages', 'getLanguages'); // for add page.. $app->get('/api/partsofspeech', 'getPartsOfSpeech'); // for add page.. $app->get('/api/bins/', 'getBins'); // for bins page $app->get('/api/icons/:word', function ($word) use($app, $model) { echo $model->getIcons($word); }); // not working on live server $app->post('/api/u/words', $authenticate($app), function () use($app, $model) { $session_identifier = Hybrid_Auth::storage()->get('user'); echo $model->getMyWords($session_identifier); }); $app->post('/api/u/bins', $authenticate($app), function () use($app, $model) { $session_identifier = Hybrid_Auth::storage()->get('user'); echo $model->getMyBins($session_identifier); }); $app->run(); // POST to api/add/word function addWord() { $app = \Slim\Slim::getInstance(); $request = $app->request(); $data = json_decode($request->getBody()); $i = 0; // To get each WordID[$i] foreach ($data->words as $word) { // Insert word into words table $sql_words = "INSERT INTO `words` (`Word`, `Gender`, `Case`, `Infinitive`, `Aspect`, `Conjugation`, `Person`, `Number`, `IconID`, `IconAuthor`, `IconTerm`, `Timestamp`, `Salt`) VALUES (:word, NULL, NULL, NULL, NULL, NULL, NULL, NULL, :iconID, :iconAuthor, :iconTerm, CURRENT_TIMESTAMP, :salt);"; try {
/** * define:endpoint step 3. */ public static function processAuthStart() { Hybrid_Endpoint::authInit(); $provider_id = trim(strip_tags(Hybrid_Endpoint::$request["hauth_start"])); # check if page accessed directly if (!Hybrid_Auth::storage()->get("hauth_session.{$provider_id}.hauth_endpoint")) { Hybrid_Logger::error("Endpoint: hauth_endpoint parameter is not defined on hauth_start, halt login process!"); header("HTTP/1.0 404 Not Found"); die("You cannot access this page directly."); } # define:hybrid.endpoint.php step 2. $hauth = Hybrid_Auth::setup($provider_id); # if REQUESTed hauth_idprovider is wrong, session not created, etc. if (!$hauth) { Hybrid_Logger::error("Endpoint: Invalide parameter on hauth_start!"); header("HTTP/1.0 404 Not Found"); die("Invalide parameter! Please return to the login page and try again."); } try { Hybrid_Logger::info("Endpoint: call adapter [{$provider_id}] loginBegin()"); $hauth->adapter->loginBegin(); } catch (Exception $e) { Hybrid_Logger::error("Exception:" . $e->getMessage(), $e); Hybrid_Error::setError($e->getMessage(), $e->getCode(), $e->getTraceAsString(), $e); $hauth->returnToCallbackUrl(); } die; }
/** * load the user profile from the IDp api client */ function getUserProfile() { // try to get the user profile from stored data $this->user = Hybrid_Auth::storage()->get("hauth_session.{$this->providerId}.user"); // if not found if (!is_object($this->user)) { throw new Exception("User profile request failed! User is not connected to {$this->providerId} or his session has expired.", 6); } return $this->user->profile; }
/** * @return string detailled error backtrace as string. */ public static function getErrorPrevious() { return Hybrid_Auth::storage()->get("hauth_session.error.previous"); }
<html> <head> <title>Login - HybridAuth App</title> </head> <body> <?php $identifier_session = !empty(Hybrid_Auth::storage()) ? Hybrid_Auth::storage()->get('user') : null; if (isset($identifier_session) && !empty($identifier_session)) { echo '<a href="/welcome">Return to Control Panel</a>'; } if (isset($_GET['err']) && !empty($_GET['err'])) { echo '<div>Authentication failed. Please try again</div>'; } ?> <h1>HybridAuth Demo App</h1> <p>Click any of the link below to login with a social network of your choice</p> <a href="/login/facebook">Facebook</a> | <a href="/login/twitter">Twitter</a> | <a href="/login/google">Google</a> | <a href="/login/github">Github</a> </body> </html>
header("HTTP/1.0 404 Not Found"); die("You cannot access this page directly."); } Hybrid_Auth::initialize(unserialize($_SESSION["HA::CONFIG"])); } catch (Exception $e) { Hybrid_Logger::error("Endpoint: Error while trying to init Hybrid_Auth"); header("HTTP/1.0 404 Not Found"); die("Oophs. Error!"); } Hybrid_Logger::info("Enter Endpoint"); # define:endpoint step 3. # yeah, why not a switch! if (isset($_REQUEST["hauth_start"]) && $_REQUEST["hauth_start"]) { $provider_id = trim(strip_tags($_REQUEST["hauth_start"])); # check if page accessed directly if (!Hybrid_Auth::storage()->get("hauth_session.{$provider_id}.hauth_endpoint")) { Hybrid_Logger::error("Endpoint: hauth_endpoint parameter is not defined on hauth_start, halt login process!"); header("HTTP/1.0 404 Not Found"); die("You cannot access this page directly."); } # define:hybrid.endpoint.php step 2. $hauth = Hybrid_Auth::setup($provider_id); # if REQUESTed hauth_idprovider is wrong, session not created, or shit happen, etc. if (!$hauth) { Hybrid_Logger::error("Endpoint: Invalide parameter on hauth_start!"); header("HTTP/1.0 404 Not Found"); die("Invalide parameter! Please return to the login page and try again."); } try { Hybrid_Logger::info("Endpoint: call adapter [{$provider_id}] loginBegin()"); $hauth->adapter->loginBegin();
/** * define:endpoint step 3.1 and 3.2 */ public static function processAuthDone() { Hybrid_Endpoint::authInit(); $provider_id = trim(strip_tags(Hybrid_Endpoint::$request["hauth_done"])); # check if page accessed directly if (!Hybrid_Auth::storage()->get("hauth_session.{$provider_id}.hauth_endpoint")) { throw new Hybrid_Exception("You cannot access this page directly."); } $hauth = Hybrid_Auth::setup($provider_id); if (!$hauth) { $hauth->adapter->setUserUnconnected(); throw new Hybrid_Exception("Invalid parameter! Please return to the login page and try again."); } try { $hauth->adapter->loginFinish(); } catch (Exception $e) { Hybrid_Error::setError($e->getMessage(), $e->getCode()); $hauth->adapter->setUserUnconnected(); } $hauth->returnToCallbackUrl(); die; }
/** * finish login step */ function loginFinish() { // in case we get error_reason=user_denied&error=access_denied if (isset($_REQUEST['error']) && $_REQUEST['error'] == "access_denied") { throw new Exception("Authentication failed! The user denied your request.", 5); } // in case we are using iOS/Facebook reverse authentication if (isset($_REQUEST['access_token'])) { $this->token("access_token", $_REQUEST['access_token']); $this->api->setAccessToken($this->token("access_token")); $this->api->setExtendedAccessToken(); $access_token = $this->api->getAccessToken(); if ($access_token) { $this->token("access_token", $access_token); $this->api->setAccessToken($access_token); } $this->api->setAccessToken($this->token("access_token")); } // if auth_type is used, then an auth_nonce is passed back, and we need to check it. if (isset($_REQUEST['auth_nonce'])) { $nonce = Hybrid_Auth::storage()->get('fb_auth_nonce'); //Delete the nonce Hybrid_Auth::storage()->delete('fb_auth_nonce'); if ($_REQUEST['auth_nonce'] != $nonce) { throw new Exception("Authentication failed! Invalid nonce used for reauthentication.", 5); } } // try to get the UID of the connected user from fb, should be > 0 if (!$this->api->getUser()) { throw new Exception("Authentication failed! {$this->providerId} returned an invalid user id.", 5); } // set user as logged in $this->setUserConnected(); // store facebook access token $this->token("access_token", $this->api->getAccessToken()); }
$user->snid = $snid[$idp]; $user->identifier = $user_profile->identifier; $user->email = $user_profile->email; $user->first_name = $user_profile->firstName; $user->last_name = $user_profile->lastName; $user->avatar_url = $user_profile->photoURL; $user->reg = R::isoDateTime(); if (R::store($user)) { \Hybrid_Auth::storage()->set('user', ['identifier' => $user_profile->identifier, 'snid' => $snid[$idp]]); $app->redirect($app->wroot . '/welcome/'); } } // Get error } catch (Exception $e) { echo $e->getMessage(); } }); // Logout $app->get('/logout/', function () use($app) { $app->hybridInstance; \Hybrid_Auth::storage()->set('user', null); Hybrid_Auth::logoutAllProviders(); $app->redirect($app->wroot . '/login/'); }); // Wellcome $app->get('/welcome/', $authenticate($app), function () use($app) { $u_ses = Hybrid_Auth::storage()->get('user'); $user = R::findOne('users', ' snid = ? AND identifier = ?', array($u_ses['snid'], $u_ses['identifier'])); $app->render('welcome.php', ['user' => $user->export()]); }); $app->run();
/** * redirect the user to hauth_return_to (the callback url) */ function returnToCallbackUrl() { // get the stored callback url $callback_url = Hybrid_Auth::storage()->get("hauth_session.{$this->id}.hauth_return_to"); // remove some unneed'd stored data Hybrid_Auth::storage()->delete("hauth_session.{$this->id}.hauth_return_to"); Hybrid_Auth::storage()->delete("hauth_session.{$this->id}.hauth_endpoint"); Hybrid_Auth::storage()->delete("hauth_session.{$this->id}.id_provider_params"); // back to home Hybrid_Auth::redirect($callback_url); }
/** Destroy user login session */ public function logout_user() { \Hybrid_Auth::storage()->set('user', null); }
/** * Check if the current user is connected to a given provider */ public static function isConnectedWith($providerId) { return (bool) Hybrid_Auth::storage()->get("hauth_session.{$providerId}.is_logged_in"); }
/** * finish login step */ function loginFinish() { // in case we get error_reason=user_denied&error=access_denied if (isset($_REQUEST['error']) && $_REQUEST['error'] == "access_denied") { //throw new Exception( "Authentication failed! The user denied your request.", 5 ); $baseUrl = Hybrid_Auth::$config['base_url']; $pos = strpos($baseUrl, "/social-auth"); $websiteURL = substr($baseUrl, 0, $pos); parent::logout(); Hybrid_Auth::redirect($websiteURL . "/user/logout"); } // in case we are using iOS/Facebook reverse authentication if (isset($_REQUEST['access_token'])) { $this->token("access_token", $_REQUEST['access_token']); //$this->api->setAccessToken( $this->token("access_token") ); //$this->api->setExtendedAccessToken(); //$access_token = $this->api->getAccessToken(); if (isset($this->session)) { $access_token = $this->session->getAccessToken(); } if ($access_token) { $this->token("access_token", $access_token); //$this->api->setAccessToken( $access_token ); } //$this->api->setAccessToken( $this->token("access_token") ); } // if auth_type is used, then an auth_nonce is passed back, and we need to check it. if (isset($_REQUEST['auth_nonce'])) { $nonce = Hybrid_Auth::storage()->get('fb_auth_nonce'); //Delete the nonce Hybrid_Auth::storage()->delete('fb_auth_nonce'); if ($_REQUEST['auth_nonce'] != $nonce) { throw new Exception("Authentication failed! Invalid nonce used for reauthentication.", 5); } } if (isset($this->session)) { error_log("\nHello, In loginFinish function : getAccessToken :" . $this->session->getAccessToken()); //error_log( "\nHello, In loginFinish function : signedRequest :".$this->session->getSignedRequest()->getUserId()); $user_profile = (new FacebookRequest($this->session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className()); // try to get the UID of the connected user from fb, should be > 0 //if ( ! $this->api->getUser() ){ //$this->session = new FacebookSession($this->session->getAccessToken()); error_log("\nHello, In loginFinish function : UID of the connected user from fb :" . $user_profile->getId() . ", Name :" . $user_profile->getName()); if (!$user_profile->getId()) { throw new Exception("Authentication failed! {$this->providerId} returned an invalid user id.", 5); } // set user as logged in $this->setUserConnected(); // store facebook access token $this->token("access_token", $this->session->getAccessToken()); } }