/** * 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("Authentification failed! The user denied your request.", 5); } if (!isset($_REQUEST['code']) || !isset($_REQUEST['state'])) { throw new Exception("Authentification failed! The user denied your request.", 5); } $code = $_REQUEST['code']; $state = $_REQUEST['state']; $user_id = 0; // try to get the UID of the connected user from fb, should be > 0 try { $user_id = $this->api->getUser($code, $state, $this->endpoint); } catch (Exception $e) { Hybrid_Logger::error("Authentification failed! Renren returned an invalide user id."); Hybrid_Logger::error("Exception:" . $e->getMessage(), $e); } if (!$user_id) { throw new Exception("Authentification failed! {$this->providerId} returned an invalide user id.", 5); } // set user as logged in $this->setUserConnected(); // store access token //$this->token( "access_token", $this->api->getAccessToken() ); }
private function authenticate($code) { $params = array("client_id" => $this->api->client_id, "client_secret" => $this->api->client_secret, "grant_type" => "authorization_code", "redirect_uri" => $this->api->redirect_uri, "code" => $code); $url = $this->api->token_url; $url = $url . (strpos($url, '?') ? '&' : '?') . http_build_query($params); $response = $this->api->api($url, 'POST'); Hybrid_Logger::debug("authenticate with url: {$url}"); if (!$response || !isset($response->access_token)) { throw new Exception("The Authorization Service has return: " . $response->error); } if (isset($response->access_token)) { $this->api->access_token = $response->access_token; } if (isset($response->refresh_token)) { $this->api->refresh_token = $response->refresh_token; } if (isset($response->expires_in)) { $this->api->access_token_expires_in = $response->expires_in; } // calculate when the access token expire if (isset($response->expires_in)) { $this->api->access_token_expires_at = time() + $response->expires_in; } return $response; }
/** * begin login step * * simply call Facebook::require_login(). */ function loginBegin() { $parameters = array("scope" => $this->scope, "redirect_uri" => $this->endpoint, "display" => "page"); $optionals = array("scope", "redirect_uri", "display", "auth_type"); foreach ($optionals as $parameter) { if (isset($this->config[$parameter]) && !empty($this->config[$parameter])) { $parameters[$parameter] = $this->config[$parameter]; //If the auth_type parameter is used, we need to generate a nonce and include it as a parameter if ($parameter == "auth_type") { $nonce = md5(uniqid(mt_rand(), true)); $parameters['auth_nonce'] = $nonce; Hybrid_Auth::storage()->set('fb_auth_nonce', $nonce); } } } if (isset($this->config['force']) && $this->config['force'] === true) { $parameters['auth_type'] = 'reauthenticate'; $parameters['auth_nonce'] = md5(uniqid(mt_rand(), true)); Hybrid_Auth::storage()->set('fb_auth_nonce', $parameters['auth_nonce']); } // get the login url $url = $this->api->getLoginUrl($parameters); if (!$url) { Hybrid_Logger::error("Hybrid_Providers_Facebook: url is empty!"); } // redirect to facebook Hybrid_Auth::redirect($url); }
/** * finish login step */ function loginFinish() { // in case we get error_reason=user_denied&error=access_denied if (isset($_REQUEST['error']) && $_REQUEST['error'] == "access_denied") { Hybrid_Logger::debug("QQ access_denied"); throw new Exception("Authentification failed! The user denied your request.", 5); } if (!isset($_REQUEST['code']) || !isset($_REQUEST['state'])) { Hybrid_Logger::debug("QQ no code or state"); throw new Exception("Authentification failed! The user denied your request.", 5); } $code = $_REQUEST['code']; $state = $_REQUEST['state']; // try to get the UID of the connected user from fb, should be > 0 try { $access_token = $this->api->qq_callback(); $openid = $this->api->get_openid(); Hybrid_Logger::debug("Get QQ openid: {$openid}"); } catch (Exception $e) { Hybrid_Logger::error("Authentification failed for {$this->providerId} "); Hybrid_Logger::error("Exception:" . $e->getMessage(), $e); } if (!$access_token || !$openid) { throw new Exception("Authentification failed! {$this->providerId} returned invalide access token or openid", 5); } // set user as logged in $this->setUserConnected(); // store access token //$this->token( "access_token", $this->api->getAccessToken() ); }
private function request($url, $params = false, $type = "GET") { Hybrid_Logger::info("Enter OAuth2Client::request( {$url} )"); Hybrid_Logger::debug("OAuth2Client::request(). dump request params: ", serialize($params)); if ($type == "GET") { $url = $url . (strpos($url, '?') ? '&' : '?') . http_build_query($params, '', '&'); } $this->http_info = array(); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, $this->api->curl_time_out); curl_setopt($ch, CURLOPT_USERAGENT, $this->api->curl_useragent); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->api->curl_connect_time_out); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->api->curl_ssl_verifypeer); curl_setopt($ch, CURLOPT_HTTPHEADER, $this->api->curl_header); if ($this->api->curl_proxy) { curl_setopt($ch, CURLOPT_PROXY, $this->api->curl_proxy); } if ($type == "POST") { curl_setopt($ch, CURLOPT_POST, 1); if ($params) { curl_setopt($ch, CURLOPT_POSTFIELDS, $params); } } $response = curl_exec($ch); Hybrid_Logger::debug("OAuth2Client::request(). dump request info: ", serialize(curl_getinfo($ch))); Hybrid_Logger::debug("OAuth2Client::request(). dump request result: ", serialize($response)); $this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $this->http_info = array_merge($this->http_info, curl_getinfo($ch)); curl_close($ch); return $response; }
/** * clear the last error */ public static function clearError() { Hybrid_Logger::info("Enter Hybrid_Error::clearError()"); Hybrid_Auth::storage()->delete("hauth_session.error.status"); Hybrid_Auth::storage()->delete("hauth_session.error.message"); Hybrid_Auth::storage()->delete("hauth_session.error.code"); Hybrid_Auth::storage()->delete("hauth_session.error.trace"); Hybrid_Auth::storage()->delete("hauth_session.error.previous"); }
function getUserProfile() { $profile = $this->api->api('me/', 'GET', array('fields' => 'id,username,first_name,last_name,counts,image')); if (!isset($profile->data->id)) { throw new Exception("User profile request failed! {$this->providerId} returned an invalid response:" . Hybrid_Logger::dumpData($profile), 6); } $data = $profile->data; $this->user->profile->identifier = $data->id; $this->user->profile->firstName = $data->first_name; $this->user->profile->lastName = $data->last_name; $this->user->profile->displayName = $data->username; if (isset($data->image->{'60x60'})) { $this->user->profile->photoURL = $data->image->{'60x60'}->url; } return $this->user->profile; }
public function __construct($inc) { Hybrid_Logger::debug("Construct QQ Recorder"); $this->error = new ErrorCase(); //-------读取配置文件 //$incFileContents = file(ROOT."comm/inc.php"); //$incFileContents = $incFileContents[1]; //$this->inc = json_decode($incFileContents); $this->inc = $inc; if (empty($this->inc)) { $this->error->showError("20001"); } if (empty($_SESSION['QC_userData'])) { self::$data = array(); } else { self::$data = $_SESSION['QC_userData']; } }
/** * {@inheritdoc} */ function getUserProfile() { $data = $this->api->api("users/self", "GET", Hybrid_Providers_Foursquare::$apiVersion); if (!isset($data->response->user->id)) { throw new Exception("User profile request failed! {$this->providerId} returned an invalid response:" . Hybrid_Logger::dumpData($data), 6); } $data = $data->response->user; $this->user->profile->identifier = $data->id; $this->user->profile->firstName = $data->firstName; $this->user->profile->lastName = $data->lastName; $this->user->profile->displayName = $this->buildDisplayName($this->user->profile->firstName, $this->user->profile->lastName); $this->user->profile->photoURL = $this->buildPhotoURL($data->photo->prefix, $data->photo->suffix); $this->user->profile->profileURL = "https://www.foursquare.com/user/" . $data->id; $this->user->profile->gender = $data->gender; $this->user->profile->city = $data->homeCity; $this->user->profile->email = $data->contact->email; $this->user->profile->emailVerified = $data->contact->email; return $this->user->profile; }
function __construct() { if (array_key_exists('debug_mode', Hybrid_Auth::$config)) { Hybrid_Logger::$enabled = Hybrid_Auth::$config['debug_mode']; } if (array_key_exists('debug_file', Hybrid_Auth::$config)) { Hybrid_Logger::$log_file = Hybrid_Auth::$config['debug_file']; } if (array_key_exists('debug_level', Hybrid_Auth::$config)) { Hybrid_Logger::$log_level = Hybrid_Auth::$config['debug_level']; } // if debug mode is set to true, then check for the writable log file if (Hybrid_Logger::$enabled) { if (!file_exists(Hybrid_Logger::$log_file)) { throw new Exception("'debug_mode' is set to 'true', but no log file path 'debug_file' given.", 1); } if (!is_writable(Hybrid_Logger::$log_file)) { throw new Exception("'debug_mode' is set to 'true', but the given log file path 'debug_file' is not a writable file.", 1); } } }
/** * {@inheritdoc} */ public function getUserProfile() { $data = $this->api->get("me"); if (!isset($data->id)) { throw new Exception("User profile request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData($data), 6); } $this->user->profile->identifier = property_exists($data, 'id') ? $data->id : ""; $this->user->profile->firstName = property_exists($data, 'first_name') ? $data->first_name : ""; $this->user->profile->lastName = property_exists($data, 'last_name') ? $data->last_name : ""; $this->user->profile->displayName = property_exists($data, 'name') ? trim($data->name) : ""; $this->user->profile->gender = property_exists($data, 'gender') ? $data->gender : ""; //wl.basic $this->user->profile->profileURL = property_exists($data, 'link') ? $data->link : ""; //wl.emails $this->user->profile->email = property_exists($data, 'emails') ? $data->emails->account : ""; $this->user->profile->emailVerified = property_exists($data, 'emails') ? $data->emails->account : ""; //wl.birthday $this->user->profile->birthDay = property_exists($data, 'birth_day') ? $data->birth_day : ""; $this->user->profile->birthMonth = property_exists($data, 'birth_month') ? $data->birth_month : ""; $this->user->profile->birthYear = property_exists($data, 'birth_year') ? $data->birth_year : ""; return $this->user->profile; }
/** * {@inheritdoc} */ function getUserProfile() { $response = json_decode(json_encode($this->api->api($this->api->userinfo_url)), true); //$this->user->profile->identifier = ($response["user"]) ? $response["user"]["userid"] : (($response, "userid")) ? $response["userid"] : ""; if ($response["user"]) { $this->user->profile->identifier = $response["user"] ? $response["user"]["userid"] : ""; $this->user->profile->firstName = $response["user"]["name"] ? $this->get_name_part($response["user"]["name"], 0) : ""; $this->user->profile->lastName = $response["user"]["name"] ? $this->get_name_part($response["user"]["name"], 1) : ""; $this->user->profile->displayName = $response["user"]["name"] ? $response["user"]["name"] : ""; $this->user->profile->photoURL = $response["user"]["profilephoto"] ? "https://api.dataporten.no/userinfo/v1/user/media/" . $response["user"]["profilephoto"] : ""; $this->user->profile->email = $response["user"]["email"] ? $response["user"]["email"] : ""; $this->user->profile->emailVerified = $response["user"]["email"] ? $response["user"]["email"] : ""; } else { if ($response["name"]) { $this->user->profile->identifier = $response["userid"] ? $response["userid"] : ""; $this->user->profile->firstName = $response["name"] ? $this->get_name_part($response["name"], 0) : ""; $this->user->profile->lastName = $response["name"] ? $this->get_name_part($response["name"], 1) : ""; $this->user->profile->displayName = $response["name"] ? $response["name"] : ""; } else { throw new Exception("User profile request failed! {$this->providerId} returned an invalid response:" . Hybrid_Logger::dumpData($response), 6); } } return $this->user->profile; }
/** * set user to unconnected */ public function setUserUnconnected() { Hybrid_Logger::info("Enter [{$this->providerId}]::setUserUnconnected()"); Hybrid_Auth::storage()->set("hauth_session.{$this->providerId}.is_logged_in", 0); }
/** * Utility function, redirect to a given URL with php header or using javascript location.href * * @param string $url URL to redirect to * @param string $mode PHP|JS */ public static function redirect($url, $mode = "PHP") { Hybrid_Logger::info("Enter Hybrid_Auth::redirect( {$url}, {$mode} )"); // Ensure session is saved before sending response, see https://github.com/symfony/symfony/pull/12341 if (PHP_VERSION_ID >= 50400 && PHP_SESSION_ACTIVE === session_status() || PHP_VERSION_ID < 50400 && isset($_SESSION) && session_id()) { session_write_close(); } if ($mode == "PHP") { header("Location: {$url}"); } elseif ($mode == "JS") { echo '<html>'; echo '<head>'; echo '<script type="text/javascript">'; echo 'function redirect(){ window.top.location.href="' . $url . '"; }'; echo '</script>'; echo '</head>'; echo '<body onload="redirect()">'; echo 'Redirecting, please wait...'; echo '</body>'; echo '</html>'; } die; }
public static function authInit() { if (!Hybrid_Endpoint::$initDone) { Hybrid_Endpoint::$initDone = TRUE; # Init Hybrid_Auth try { require_once realpath(dirname(__FILE__)) . "/Storage.php"; $storage = new Hybrid_Storage(); // Check if Hybrid_Auth session already exist if (!$storage->config("CONFIG")) { header("HTTP/1.0 404 Not Found"); die("You cannot access this page directly."); } Hybrid_Auth::initialize($storage->config("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!"); } } }
/** * Makes an HTTP request. * This method can be overridden by subclasses if * developers want to do fancier things or use something other than curl to * make the request. * * @param string $url * The URL to make the request to * @param array $params * The parameters to use for the POST body * @param CurlHandler $ch * Initialized curl handle * * @return string The response text */ protected function makeRequest($url, $params, $ch = null) { if (!$ch) { $ch = curl_init(); } $opts = self::$CURL_OPTS; if ($this->getFileUploadSupport()) { $opts[CURLOPT_POSTFIELDS] = $params; } else { $opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&'); } $opts[CURLOPT_URL] = $url; // disable the 'Expect: 100-continue' behaviour. This causes CURL to wait // for 2 seconds if the server does not support this header. if (isset($opts[CURLOPT_HTTPHEADER])) { $existing_headers = $opts[CURLOPT_HTTPHEADER]; $existing_headers[] = 'Expect:'; $opts[CURLOPT_HTTPHEADER] = $existing_headers; } else { $opts[CURLOPT_HTTPHEADER] = array('Expect:'); } curl_setopt_array($ch, $opts); $result = curl_exec($ch); if (curl_errno($ch) == 60) { // CURLE_SSL_CACERT self::errorLog('Invalid or no certificate authority found, ' . 'using bundled information'); curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/fb_ca_chain_bundle.crt'); $result = curl_exec($ch); } // With dual stacked DNS responses, it's possible for a server to // have IPv6 enabled but not have IPv6 connectivity. If this is // the case, curl will try IPv4 first and if that fails, then it wills // fall back to IPv6 and the error EHOSTUNREACH is returned by the // operating system. if ($result === false && empty($opts[CURLOPT_IPRESOLVE])) { $matches = array(); $regex = '/Failed to connect to ([^:].*): Network is unreachable/'; if (preg_match($regex, curl_error($ch), $matches)) { if (strlen(@inet_pton($matches[1])) === 16) { self::errorLog('Invalid IPv6 configuration on server, ' . 'Please disable or get native IPv6 on your server.'); self::$CURL_OPTS[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4; curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); $result = curl_exec($ch); } } } if (class_exists('Hybrid_Logger')) { Hybrid_Logger::info('FB:Request:Response' . print_r(array($url, $result), true)); } if ($result[0] == '{') { $resultOb = json_decode($result); if (key_exists('error', $resultOb)) { if (class_exists('Hybrid_Logger')) { Hybrid_Logger::error('FB:Error' . print_r($resultOb, true)); } } } if ($result === false) { $e = new FacebookApiException(array('error_code' => curl_errno($ch), 'error' => array('message' => curl_error($ch), 'type' => 'CurlException'))); curl_close($ch); throw $e; } curl_close($ch); return $result; }
/** * Make http request */ function request($url, $method, $postfields = NULL, $auth_header = NULL, $content_type = NULL) { Hybrid_Logger::info("Enter OAuth1Client::request( {$method}, {$url} )"); Hybrid_Logger::debug("OAuth1Client::request(). dump post fields: ", serialize($postfields)); $this->http_info = array(); $ci = curl_init(); /* Curl settings */ curl_setopt($ci, CURLOPT_USERAGENT, $this->curl_useragent); curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->curl_connect_time_out); curl_setopt($ci, CURLOPT_TIMEOUT, $this->curl_time_out); curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:')); curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->curl_ssl_verifypeer); curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader')); curl_setopt($ci, CURLOPT_HEADER, FALSE); if ($content_type) { curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:', "Content-Type: {$content_type}")); } if ($this->curl_proxy) { curl_setopt($ci, CURLOPT_PROXY, $this->curl_proxy); } switch ($method) { case 'POST': curl_setopt($ci, CURLOPT_POST, TRUE); if (!empty($postfields)) { curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields); } if (!empty($auth_header) && $this->curl_auth_header) { curl_setopt($ci, CURLOPT_HTTPHEADER, array('Content-Type: application/atom+xml', $auth_header)); } break; case 'DELETE': curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE'); if (!empty($postfields)) { $url = "{$url}?{$postfields}"; } } curl_setopt($ci, CURLOPT_URL, $url); $response = curl_exec($ci); if ($response === FALSE) { Hybrid_Logger::error("OAuth1Client::request(). curl_exec error: ", curl_error($ci)); } Hybrid_Logger::debug("OAuth1Client::request(). dump request info: ", serialize(curl_getinfo($ci))); Hybrid_Logger::debug("OAuth1Client::request(). dump request result: ", serialize($response)); $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE); $this->http_info = array_merge($this->http_info, curl_getinfo($ci)); curl_close($ci); return $response; }
public static function authInit() { if (!Hybrid_Endpoint::$initDone) { Hybrid_Endpoint::$initDone = TRUE; // Start a new session if (!session_id()) { session_start(); } # Init Hybrid_Auth try { // Check if Hybrid_Auth session already exist if (!isset($_SESSION["HA::CONFIG"])) { 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!"); } } }
/** * {@inheritdoc} */ function getUserProfile() { // request user profile from fb api try { $fields = array('id', 'name', 'first_name', 'last_name', 'link', 'website', 'gender', 'locale', 'about', 'email', 'hometown', 'location', 'birthday'); $data = $this->api->api('/me?fields=' . implode(',', $fields)); } catch (FacebookApiException $e) { throw new Exception("User profile request failed! {$this->providerId} returned an error: {$e->getMessage()}", 6, $e); } // if the provider identifier is not received, we assume the auth has failed if (!isset($data["id"])) { throw new Exception("User profile request failed! {$this->providerId} api returned an invalid response: " . Hybrid_Logger::dumpData($data), 6); } # store the user profile. $this->user->profile->identifier = array_key_exists('id', $data) ? $data['id'] : ""; $this->user->profile->username = array_key_exists('username', $data) ? $data['username'] : ""; $this->user->profile->displayName = array_key_exists('name', $data) ? $data['name'] : ""; $this->user->profile->firstName = array_key_exists('first_name', $data) ? $data['first_name'] : ""; $this->user->profile->lastName = array_key_exists('last_name', $data) ? $data['last_name'] : ""; $this->user->profile->photoURL = "https://graph.facebook.com/" . $this->user->profile->identifier . "/picture?width=150&height=150"; $this->user->profile->coverInfoURL = "https://graph.facebook.com/" . $this->user->profile->identifier . "?fields=cover&access_token=" . $this->api->getAccessToken(); $this->user->profile->profileURL = array_key_exists('link', $data) ? $data['link'] : ""; $this->user->profile->webSiteURL = array_key_exists('website', $data) ? $data['website'] : ""; $this->user->profile->gender = array_key_exists('gender', $data) ? $data['gender'] : ""; $this->user->profile->language = array_key_exists('locale', $data) ? $data['locale'] : ""; $this->user->profile->description = array_key_exists('about', $data) ? $data['about'] : ""; $this->user->profile->email = array_key_exists('email', $data) ? $data['email'] : ""; $this->user->profile->emailVerified = array_key_exists('email', $data) ? $data['email'] : ""; $this->user->profile->region = array_key_exists("location", $data) && array_key_exists("name", $data['location']) ? $data['location']["name"] : ""; if (!empty($this->user->profile->region)) { $regionArr = explode(',', $this->user->profile->region); if (count($regionArr) > 1) { $this->user->profile->city = trim($regionArr[0]); $this->user->profile->country = trim($regionArr[1]); } } if (array_key_exists('birthday', $data)) { list($birthday_month, $birthday_day, $birthday_year) = explode("/", $data['birthday']); $this->user->profile->birthDay = (int) $birthday_day; $this->user->profile->birthMonth = (int) $birthday_month; $this->user->profile->birthYear = (int) $birthday_year; } return $this->user->profile; }
// with /index.php?hauth.done={provider}?{args}... if (strrpos($_SERVER["QUERY_STRING"], '?')) { $_SERVER["QUERY_STRING"] = str_replace("?", "&", $_SERVER["QUERY_STRING"]); parse_str($_SERVER["QUERY_STRING"], $_REQUEST); } $provider_id = trim(strip_tags($_REQUEST["hauth_done"])); $hauth = Hybrid_Auth::setup($provider_id); if (!$hauth) { Hybrid_Logger::error("Endpoint: Invalide parameter on hauth_done!"); $hauth->adapter->setUserUnconnected(); 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}] loginFinish() "); $hauth->adapter->loginFinish(); } catch (Exception $e) { Hybrid_Logger::error("Exception:" . $e->getMessage(), $e); Hybrid_Error::setError($e->getMessage(), $e->getCode(), $e->getTraceAsString(), $e); $hauth->adapter->setUserUnconnected(); } Hybrid_Logger::info("Endpoint: job done. retrun to callback url."); $hauth->returnToCallbackUrl(); die; } } else { # Else, # We advertise our XRDS document, something supposed to be done from the Realm URL page echo str_replace("{X_XRDS_LOCATION}", Hybrid_Auth::getCurrentUrl(false) . "?get=openid_xrds&v=" . Hybrid_Auth::$version, file_get_contents(dirname(__FILE__) . "/Hybrid/resources/openid_realm.html")); die; }
/** * Naive getter of the current connected IDp API client */ function api() { if (!$this->adapter->isUserConnected()) { Hybrid_Logger::error("User not connected to the provider."); throw new Exception("User not connected to the provider.", 7); } return $this->adapter->api; }
/** * Initializes authentication * @throws Hybrid_Exception */ protected function authInit() { if (!$this->initDone) { $this->initDone = true; // Init Hybrid_Auth try { if (!class_exists("Hybrid_Storage", false)) { require_once realpath(dirname(__FILE__)) . "/Storage.php"; } if (!class_exists("Hybrid_Exception", false)) { require_once realpath(dirname(__FILE__)) . "/Exception.php"; } if (!class_exists("Hybrid_Logger", false)) { require_once realpath(dirname(__FILE__)) . "/Logger.php"; } $storage = new Hybrid_Storage(); // Check if Hybrid_Auth session already exist if (!$storage->config("CONFIG")) { throw new Hybrid_Exception("You cannot access this page directly."); } Hybrid_Auth::initialize($storage->config("CONFIG")); } catch (Exception $e) { Hybrid_Logger::error("Endpoint: Error while trying to init Hybrid_Auth: " . $e->getMessage()); throw new Hybrid_Exception("Endpoint: Error while trying to init Hybrid_Auth: " . $e->getMessage(), $e->getCode(), $e); } } }
/** * {@inheritdoc} */ public function getUserProfile() { $includeEmail = isset($this->config['includeEmail']) ? (bool) $this->config['includeEmail'] : false; $response = $this->api->get('account/verify_credentials.json' . ($includeEmail ? '?include_email=true' : '')); // check the last HTTP status code returned if ($this->api->http_code != 200) { throw new Exception("User profile request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 6); } if (!is_object($response) || !isset($response->id)) { throw new Exception("User profile request failed! {$this->providerId} api returned an invalid response: " . Hybrid_Logger::dumpData($response), 6); } # store the user profile. $this->user->profile->identifier = property_exists($response, 'id') ? $response->id : ""; $this->user->profile->displayName = property_exists($response, 'screen_name') ? $response->screen_name : ""; $this->user->profile->description = property_exists($response, 'description') ? $response->description : ""; $this->user->profile->firstName = property_exists($response, 'name') ? $response->name : ""; $this->user->profile->photoURL = property_exists($response, 'profile_image_url') ? str_replace('_normal', '', $response->profile_image_url) : ""; $this->user->profile->profileURL = property_exists($response, 'screen_name') ? "http://twitter.com/" . $response->screen_name : ""; $this->user->profile->webSiteURL = property_exists($response, 'url') ? $response->url : ""; $this->user->profile->region = property_exists($response, 'location') ? $response->location : ""; if ($includeEmail) { $this->user->profile->email = property_exists($response, 'email') ? $response->email : ""; } return $this->user->profile; }
/** * define:endpoint step 3.1 and 3.2 */ protected function processAuthDone() { $provider_id = trim($this->getProperty('hauth_done')); $hauth = Hybrid_Auth::setup($provider_id); if (!$hauth) { Hybrid_Logger::error("Endpoint: Invalid parameter on hauth_done!"); $hauth->adapter->setUserUnconnected(); header("HTTP/1.0 404 Not Found"); return "Invalid parameter! Please return to the login page and try again."; } try { Hybrid_Logger::info("Endpoint: call adapter [{$provider_id}] loginFinish() "); $hauth->adapter->loginFinish(); } catch (Exception $e) { Hybrid_Logger::error("Exception:" . $e->getMessage(), $e); Hybrid_Error::setError($e->getMessage(), $e->getCode(), $e->getTraceAsString(), $e); $hauth->adapter->setUserUnconnected(); } Hybrid_Logger::info("Endpoint: job done. retrun to callback url."); // Save profile data in session $profile = $hauth->adapter->getUserProfile(); // Try to get user by social profile /*$q = $this->modx->newQuery('modUser'); $q->innerJoin('modUserProfile', 'Profile'); $q->innerJoin('modHybridAuthUserProfile', 'SocialProfile'); $q->innerJoin('modHybridAuthProvider', 'Provider', "Provider.id=SocialProfile.provider"); $q->where(array( "SocialProfile.identifier" => $profile->identifier, "Provider.name" => $provider, "modUser.active" => 1, "Profile.blocked" => 0, )); $q->limit(1); if($user = $this->modx->getObject('modUser', $q)){ $user->addSessionContext($this->modx->context->key); $redirectTo = $this->modx->getOption('site_url'); $this->modx->sendRedirect($redirectTo); return; }*/ // else $_SESSION['social_profile'] = array('provider' => $provider_id, 'profile' => $this->modx->error->toArray($profile)); //$q->prepare(); //$this->modx->log(1, $q->toSQL()); // else $hauth->returnToCallbackUrl(); return ''; }
/** * {@inheritdoc} */ function getUserProfile() { // refresh tokens if needed $this->refreshToken(); // ask google api for user infos if (strpos($this->scope, '/auth/plus.profile.emails.read') !== false) { $verified = $this->api->api("https://www.googleapis.com/plus/v1/people/me"); if (!isset($verified->id) || isset($verified->error)) { $verified = new stdClass(); } } else { $verified = $this->api->api("https://www.googleapis.com/plus/v1/people/me/openIdConnect"); if (!isset($verified->sub) || isset($verified->error)) { $verified = new stdClass(); } } $response = $this->api->api("https://www.googleapis.com/plus/v1/people/me"); if (!isset($response->id) || isset($response->error)) { throw new Exception("User profile request failed! {$this->providerId} returned an invalid response:" . Hybrid_Logger::dumpData($response), 6); } $this->user->profile->identifier = property_exists($verified, 'id') ? $verified->id : (property_exists($response, 'id') ? $response->id : ""); $this->user->profile->firstName = property_exists($response, 'name') ? $response->name->givenName : ""; $this->user->profile->lastName = property_exists($response, 'name') ? $response->name->familyName : ""; $this->user->profile->displayName = property_exists($response, 'displayName') ? $response->displayName : ""; $this->user->profile->photoURL = property_exists($response, 'image') ? property_exists($response->image, 'url') ? substr($response->image->url, 0, -2) . "200" : '' : ''; $this->user->profile->profileURL = property_exists($response, 'url') ? $response->url : ""; $this->user->profile->description = property_exists($response, 'aboutMe') ? $response->aboutMe : ""; $this->user->profile->gender = property_exists($response, 'gender') ? $response->gender : ""; $this->user->profile->language = property_exists($response, 'locale') ? $response->locale : (property_exists($verified, 'locale') ? $verified->locale : ""); $this->user->profile->email = property_exists($response, 'email') ? $response->email : (property_exists($verified, 'email') ? $verified->email : ""); $this->user->profile->emailVerified = property_exists($verified, 'email') ? $verified->email : ""; if (property_exists($response, 'emails')) { if (count($response->emails) == 1) { $this->user->profile->email = $response->emails[0]->value; } else { foreach ($response->emails as $email) { if ($email->type == 'account') { $this->user->profile->email = $email->value; break; } } } if (property_exists($verified, 'emails')) { if (count($verified->emails) == 1) { $this->user->profile->emailVerified = $verified->emails[0]->value; } else { foreach ($verified->emails as $email) { if ($email->type == 'account') { $this->user->profile->emailVerified = $email->value; break; } } } } } $this->user->profile->phone = property_exists($response, 'phone') ? $response->phone : ""; $this->user->profile->country = property_exists($response, 'country') ? $response->country : ""; $this->user->profile->region = property_exists($response, 'region') ? $response->region : ""; $this->user->profile->zip = property_exists($response, 'zip') ? $response->zip : ""; if (property_exists($response, 'placesLived')) { $this->user->profile->city = ""; $this->user->profile->address = ""; foreach ($response->placesLived as $c) { if (property_exists($c, 'primary')) { if ($c->primary == true) { $this->user->profile->address = $c->value; $this->user->profile->city = $c->value; break; } } else { if (property_exists($c, 'value')) { $this->user->profile->address = $c->value; $this->user->profile->city = $c->value; } } } } // google API returns multiple urls, but a "website" only if it is verified // see http://support.google.com/plus/answer/1713826?hl=en if (property_exists($response, 'urls')) { foreach ($response->urls as $u) { if (property_exists($u, 'primary') && $u->primary == true) { $this->user->profile->webSiteURL = $u->value; } } } else { $this->user->profile->webSiteURL = ''; } // google API returns age ranges or min. age only (with plus.login scope) if (property_exists($response, 'ageRange')) { if (property_exists($response->ageRange, 'min') && property_exists($response->ageRange, 'max')) { $this->user->profile->age = $response->ageRange->min . ' - ' . $response->ageRange->max; } else { $this->user->profile->age = '> ' . $response->ageRange->min; } } else { $this->user->profile->age = ''; } // google API returns birthdays only if a user set 'show in my account' if (property_exists($response, 'birthday')) { list($birthday_year, $birthday_month, $birthday_day) = explode('-', $response->birthday); $this->user->profile->birthDay = (int) $birthday_day; $this->user->profile->birthMonth = (int) $birthday_month; $this->user->profile->birthYear = (int) $birthday_year; } else { $this->user->profile->birthDay = 0; $this->user->profile->birthMonth = 0; $this->user->profile->birthYear = 0; } return $this->user->profile; }
public function destroySession() { Hybrid_Logger::debug("Enter QC.class destroySession"); $this->recorder->destroySession(); // $cookie_name = "openapi.qzone.qq.com"; // if (array_key_exists($cookie_name, $_COOKIE)) { // Hybrid_Logger::debug( "Enter QC.class delete cookie" ); // setcookie($cookie_name, "", time() - 1); // } print_r($_COOKIE); if (isset($_COOKIE)) { $cookies = explode(';', $_COOKIE); foreach ($cookies as $cookie) { $parts = explode('=', $cookie); $name = trim($parts[0]); Hybrid_Logger::debug("http_cookie {$name}"); //setcookie($name, '', time()-1000); //setcookie($name, '', time()-1000, '/'); } } // $qzone_cookie = array('RK', 'pgv_pvi', 'pgv_si', 'pt2gguin','ptcz'); // if (!empty($_COOKIE)) // { // foreach ($_COOKIE as $name => $value) // { // if (in_array($name, $qzone_cookie)) // { // Hybrid_Logger::debug( "destroy qzone_cookie {$name}" ); // setcookie($name, $value, time() -1); // } // } // } }
/** * General data send/request method. * * @param str $method * The data communication method. * @param str $url * The Linkedin API endpoint to connect with. * @param str $data * [OPTIONAL] The data to send to LinkedIn. * @param arr $parameters * [OPTIONAL] Addition OAuth parameters to send to LinkedIn. * * @return arr * Array containing: * * array( * 'info' => Connection information, * 'linkedin' => LinkedIn response, * 'oauth' => The OAuth request string that was sent to LinkedIn * ) */ protected function fetch($method, $url, $data = NULL, $parameters = array()) { // check for cURL if (!extension_loaded('curl')) { // cURL not present throw new LinkedInException('LinkedIn->fetch(): PHP cURL extension does not appear to be loaded/present.'); } try { // generate OAuth values $oauth_consumer = new OAuthConsumer($this->getApplicationKey(), $this->getApplicationSecret(), $this->getCallbackUrl()); $oauth_token = $this->getToken(); $oauth_token = !is_null($oauth_token) ? new OAuthToken($oauth_token['oauth_token'], $oauth_token['oauth_token_secret']) : NULL; $defaults = array('oauth_version' => self::_API_OAUTH_VERSION); $parameters = array_merge($defaults, $parameters); // generate OAuth request $oauth_req = OAuthRequest::from_consumer_and_token($oauth_consumer, $oauth_token, $method, $url, $parameters); $oauth_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $oauth_consumer, $oauth_token); // start cURL, checking for a successful initiation if (!($handle = curl_init())) { // cURL failed to start throw new LinkedInException('LinkedIn->fetch(): cURL did not initialize properly.'); } // set cURL options, based on parameters passed curl_setopt($handle, CURLOPT_CUSTOMREQUEST, $method); curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($handle, CURLOPT_URL, $url); curl_setopt($handle, CURLOPT_VERBOSE, FALSE); if (isset(Hybrid_Auth::$config["proxy"])) { curl_setopt($handle, CURLOPT_PROXY, Hybrid_Auth::$config["proxy"]); } // configure the header we are sending to LinkedIn - http://developer.linkedin.com/docs/DOC-1203 $header = array($oauth_req->to_header(self::_API_OAUTH_REALM)); if (is_null($data)) { // not sending data, identify the content type $header[] = 'Content-Type: text/plain; charset=UTF-8'; switch ($this->getResponseFormat()) { case self::_RESPONSE_JSON: $header[] = 'x-li-format: json'; break; case self::_RESPONSE_JSONP: $header[] = 'x-li-format: jsonp'; break; } } else { $header[] = 'Content-Type: text/xml; charset=UTF-8'; curl_setopt($handle, CURLOPT_POSTFIELDS, $data); } curl_setopt($handle, CURLOPT_HTTPHEADER, $header); // set the last url, headers $this->last_request_url = $url; $this->last_request_headers = $header; // gather the response $return_data['linkedin'] = curl_exec($handle); if ($return_data['linkedin'] === FALSE) { Hybrid_Logger::error("LinkedIn::fetch(). curl_exec error: ", curl_error($ch)); } $return_data['info'] = curl_getinfo($handle); $return_data['oauth']['header'] = $oauth_req->to_header(self::_API_OAUTH_REALM); $return_data['oauth']['string'] = $oauth_req->base_string; // check for throttling if (self::isThrottled($return_data['linkedin'])) { throw new LinkedInException('LinkedIn->fetch(): throttling limit for this user/application has been reached for LinkedIn resource - ' . $url); } //TODO - add check for NO response (http_code = 0) from cURL // close cURL connection curl_close($handle); // no exceptions thrown, return the data return $return_data; } catch (OAuthException $e) { // oauth exception raised throw new LinkedInException('OAuth exception caught: ' . $e->getMessage()); } }
public static function authInit() { if (!Hybrid_Endpoint::$initDone) { Hybrid_Endpoint::$initDone = TRUE; # Init Hybrid_Auth try { if (!class_exists("Hybrid_Storage")) { require_once realpath(dirname(__FILE__)) . "/Storage.php"; } $storage = new Hybrid_Storage(); // Check if Hybrid_Auth session already exist if (!$storage->config("CONFIG")) { throw new Hybrid_Exception("You cannot access this page directly."); } Hybrid_Auth::initialize($storage->config("CONFIG")); } catch (Exception $e) { Hybrid_Logger::error("Endpoint: Error while trying to init Hybrid_Auth: " . $e->getMessage()); throw new Hybrid_Exception("Oophs. Error!"); } } }
/** * Utility function, redirect to a given URL with php header or using javascript location.href */ public static function redirect($url, $mode = "PHP") { Hybrid_Logger::info("Enter Hybrid_Auth::redirect( {$url}, {$mode} )"); if ($mode == "PHP") { header("Location: {$url}"); } elseif ($mode == "JS") { echo '<html>'; echo '<head>'; echo '<script type="text/javascript">'; echo 'function redirect(){ window.top.location.href="' . $url . '"; }'; echo '</script>'; echo '</head>'; echo '<body onload="redirect()">'; echo 'Redirecting, please wait...'; echo '</body>'; echo '</html>'; } die; }
protected function request_curl($url, $method = 'GET', $params = array(), $update_claimed_id) { $params = http_build_query($params, '', '&'); $curl = curl_init($url . ($method == 'GET' && $params ? '?' . $params : '')); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/xrds+xml, */*')); if (!empty($this->proxy)) { curl_setopt($curl, CURLOPT_PROXY, $this->proxy['host']); if (!empty($this->proxy['port'])) { curl_setopt($curl, CURLOPT_PROXYPORT, $this->proxy['port']); } if (!empty($this->proxy['user'])) { curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->proxy['user'] . ':' . $this->proxy['pass']); } } if ($this->verify_peer !== null) { curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verify_peer); if ($this->capath) { curl_setopt($curl, CURLOPT_CAPATH, $this->capath); } if ($this->cainfo) { curl_setopt($curl, CURLOPT_CAINFO, $this->cainfo); } } if ($method == 'POST') { curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $params); } elseif ($method == 'HEAD') { curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_NOBODY, true); } else { curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_HTTPGET, true); } $response = curl_exec($curl); if ($response === false) { Hybrid_Logger::error("LightOpenID::request_curl(). curl_exec error: ", curl_error($curl)); } if ($method == 'HEAD' && curl_getinfo($curl, CURLINFO_HTTP_CODE) == 405) { curl_setopt($curl, CURLOPT_HTTPGET, true); $response = curl_exec($curl); $response = substr($response, 0, strpos($response, "\r\n\r\n")); } if ($method == 'HEAD' || $method == 'GET') { $header_response = $response; # If it's a GET request, we want to only parse the header part. if ($method == 'GET') { $header_response = substr($response, 0, strpos($response, "\r\n\r\n")); } $headers = array(); foreach (explode("\n", $header_response) as $header) { $pos = strpos($header, ':'); if ($pos !== false) { $name = strtolower(trim(substr($header, 0, $pos))); $headers[$name] = trim(substr($header, $pos + 1)); } } if ($update_claimed_id) { # Updating claimed_id in case of redirections. $effective_url = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL); if ($effective_url != $url) { $this->identity = $this->claimed_id = $effective_url; } } if ($method == 'HEAD') { return $headers; } else { $this->headers = $headers; } } if (curl_errno($curl)) { throw new ErrorException(curl_error($curl), curl_errno($curl)); } return $response; }