PageRenderTime 52ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/views/users/bootstrap/hybridauth/Hybrid/Auth.php

https://gitlab.com/iarafat/yellow-php-user-management-system
PHP | 411 lines | 195 code | 66 blank | 150 comment | 48 complexity | 6fccec1744e4ef47314b3131fa36bf72 MD5 | raw file
  1. <?php
  2. /**
  3. * HybridAuth
  4. * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
  5. * (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
  6. */
  7. /**
  8. * Hybrid_Auth class
  9. *
  10. * Hybrid_Auth class provide a simple way to authenticate users via OpenID and OAuth.
  11. *
  12. * Generally, Hybrid_Auth is the only class you should instanciate and use throughout your application.
  13. */
  14. class Hybrid_Auth {
  15. public static $version = "2.7.0";
  16. /**
  17. * Configuration array
  18. * @var array
  19. */
  20. public static $config = array();
  21. /**
  22. * Auth cache
  23. * @var Hybrid_Storage
  24. */
  25. public static $store = null;
  26. /**
  27. * Error pool
  28. * @var Hybrid_Error
  29. */
  30. public static $error = null;
  31. /**
  32. * Logger
  33. * @var Hybrid_Logger
  34. */
  35. public static $logger = null;
  36. /**
  37. * Try to start a new session of none then initialize Hybrid_Auth
  38. *
  39. * Hybrid_Auth constructor will require either a valid config array or
  40. * a path for a configuration file as parameter. To know more please
  41. * refer to the Configuration section:
  42. * http://hybridauth.sourceforge.net/userguide/Configuration.html
  43. *
  44. * @param array $config Configuration array or path to a configratuion file
  45. */
  46. function __construct($config) {
  47. Hybrid_Auth::initialize($config);
  48. }
  49. /**
  50. * Try to initialize Hybrid_Auth with given $config hash or file
  51. *
  52. * @param array $config Configuration array or path to a configratuion file
  53. * @return void
  54. * @throws Exception
  55. */
  56. public static function initialize($config) {
  57. if (!is_array($config) && !file_exists($config)) {
  58. throw new Exception("Hybriauth config does not exist on the given path.", 1);
  59. }
  60. if (!is_array($config)) {
  61. $config = include $config;
  62. }
  63. // build some need'd paths
  64. $config["path_base"] = realpath(dirname(__FILE__)) . "/";
  65. $config["path_libraries"] = $config["path_base"] . "thirdparty/";
  66. $config["path_resources"] = $config["path_base"] . "resources/";
  67. $config["path_providers"] = $config["path_base"] . "Providers/";
  68. // reset debug mode
  69. if (!isset($config["debug_mode"])) {
  70. $config["debug_mode"] = false;
  71. $config["debug_file"] = null;
  72. }
  73. # load hybridauth required files, a autoload is on the way...
  74. require_once $config["path_base"] . "Error.php";
  75. require_once $config["path_base"] . "Exception.php";
  76. require_once $config["path_base"] . "Logger.php";
  77. require_once $config["path_base"] . "Provider_Adapter.php";
  78. require_once $config["path_base"] . "Provider_Model.php";
  79. require_once $config["path_base"] . "Provider_Model_OpenID.php";
  80. require_once $config["path_base"] . "Provider_Model_OAuth1.php";
  81. require_once $config["path_base"] . "Provider_Model_OAuth2.php";
  82. require_once $config["path_base"] . "User.php";
  83. require_once $config["path_base"] . "User_Profile.php";
  84. require_once $config["path_base"] . "User_Contact.php";
  85. require_once $config["path_base"] . "User_Activity.php";
  86. if (!class_exists("Hybrid_Storage", false)) {
  87. require_once $config["path_base"] . "Storage.php";
  88. }
  89. // hash given config
  90. Hybrid_Auth::$config = $config;
  91. // instance of log mng
  92. Hybrid_Auth::$logger = new Hybrid_Logger();
  93. // instance of errors mng
  94. Hybrid_Auth::$error = new Hybrid_Error();
  95. // start session storage mng
  96. Hybrid_Auth::$store = new Hybrid_Storage();
  97. Hybrid_Logger::info("Enter Hybrid_Auth::initialize()");
  98. Hybrid_Logger::info("Hybrid_Auth::initialize(). PHP version: " . PHP_VERSION);
  99. Hybrid_Logger::info("Hybrid_Auth::initialize(). Hybrid_Auth version: " . Hybrid_Auth::$version);
  100. Hybrid_Logger::info("Hybrid_Auth::initialize(). Hybrid_Auth called from: " . Hybrid_Auth::getCurrentUrl());
  101. // PHP Curl extension [http://www.php.net/manual/en/intro.curl.php]
  102. if (!function_exists('curl_init')) {
  103. Hybrid_Logger::error('Hybridauth Library needs the CURL PHP extension.');
  104. throw new Exception('Hybridauth Library needs the CURL PHP extension.');
  105. }
  106. // PHP JSON extension [http://php.net/manual/en/book.json.php]
  107. if (!function_exists('json_decode')) {
  108. Hybrid_Logger::error('Hybridauth Library needs the JSON PHP extension.');
  109. throw new Exception('Hybridauth Library needs the JSON PHP extension.');
  110. }
  111. // session.name
  112. if (session_name() != "PHPSESSID") {
  113. Hybrid_Logger::info('PHP session.name diff from default PHPSESSID. http://php.net/manual/en/session.configuration.php#ini.session.name.');
  114. }
  115. // safe_mode is on
  116. if (ini_get('safe_mode')) {
  117. Hybrid_Logger::info('PHP safe_mode is on. http://php.net/safe-mode.');
  118. }
  119. // open basedir is on
  120. if (ini_get('open_basedir')) {
  121. Hybrid_Logger::info('PHP open_basedir is on. http://php.net/open-basedir.');
  122. }
  123. Hybrid_Logger::debug("Hybrid_Auth initialize. dump used config: ", serialize($config));
  124. Hybrid_Logger::debug("Hybrid_Auth initialize. dump current session: ", Hybrid_Auth::storage()->getSessionData());
  125. Hybrid_Logger::info("Hybrid_Auth initialize: check if any error is stored on the endpoint...");
  126. if (Hybrid_Error::hasError()) {
  127. $m = Hybrid_Error::getErrorMessage();
  128. $c = Hybrid_Error::getErrorCode();
  129. $p = Hybrid_Error::getErrorPrevious();
  130. Hybrid_Logger::error("Hybrid_Auth initialize: A stored Error found, Throw an new Exception and delete it from the store: Error#$c, '$m'");
  131. Hybrid_Error::clearError();
  132. // try to provide the previous if any
  133. // Exception::getPrevious (PHP 5 >= 5.3.0) http://php.net/manual/en/exception.getprevious.php
  134. if (version_compare(PHP_VERSION, '5.3.0', '>=') && ($p instanceof Exception)) {
  135. throw new Exception($m, $c, $p);
  136. } else {
  137. throw new Exception($m, $c);
  138. }
  139. }
  140. Hybrid_Logger::info("Hybrid_Auth initialize: no error found. initialization succeed.");
  141. }
  142. /**
  143. * Hybrid storage system accessor
  144. *
  145. * Users sessions are stored using HybridAuth storage system ( HybridAuth 2.0 handle PHP Session only) and can be accessed directly by
  146. * Hybrid_Auth::storage()->get($key) to retrieves the data for the given key, or calling
  147. * Hybrid_Auth::storage()->set($key, $value) to store the key => $value set.
  148. *
  149. * @return Hybrid_Storage
  150. */
  151. public static function storage() {
  152. return Hybrid_Auth::$store;
  153. }
  154. /**
  155. * Get hybridauth session data
  156. * @return string|null
  157. */
  158. function getSessionData() {
  159. return Hybrid_Auth::storage()->getSessionData();
  160. }
  161. /**
  162. * Restore hybridauth session data
  163. *
  164. * @param string $sessiondata Serialized session data
  165. * @retun void
  166. */
  167. function restoreSessionData($sessiondata = null) {
  168. Hybrid_Auth::storage()->restoreSessionData($sessiondata);
  169. }
  170. /**
  171. * Try to authenticate the user with a given provider.
  172. *
  173. * If the user is already connected we just return and instance of provider adapter,
  174. * ELSE, try to authenticate and authorize the user with the provider.
  175. *
  176. * $params is generally an array with required info in order for this provider and HybridAuth to work,
  177. * like :
  178. * hauth_return_to: URL to call back after authentication is done
  179. * openid_identifier: The OpenID identity provider identifier
  180. * google_service: can be "Users" for Google user accounts service or "Apps" for Google hosted Apps
  181. *
  182. * @param string $providerId ID of the provider
  183. * @param array $params Params
  184. * @return
  185. */
  186. public static function authenticate($providerId, $params = null) {
  187. Hybrid_Logger::info("Enter Hybrid_Auth::authenticate( $providerId )");
  188. if (!Hybrid_Auth::storage()->get("hauth_session.$providerId.is_logged_in")) {
  189. // if user not connected to $providerId then try setup a new adapter and start the login process for this provider
  190. Hybrid_Logger::info("Hybrid_Auth::authenticate( $providerId ), User not connected to the provider. Try to authenticate..");
  191. $provider_adapter = Hybrid_Auth::setup($providerId, $params);
  192. $provider_adapter->login();
  193. } else {
  194. // else, then return the adapter instance for the given provider
  195. Hybrid_Logger::info("Hybrid_Auth::authenticate( $providerId ), User is already connected to this provider. Return the adapter instance.");
  196. return Hybrid_Auth::getAdapter($providerId);
  197. }
  198. }
  199. /**
  200. * Return the adapter instance for an authenticated provider
  201. *
  202. * @param string $providerId ID of the provider
  203. * @return Hybrid_Provider_Adapter
  204. */
  205. public static function getAdapter($providerId = null) {
  206. Hybrid_Logger::info("Enter Hybrid_Auth::getAdapter( $providerId )");
  207. return Hybrid_Auth::setup($providerId);
  208. }
  209. /**
  210. * Setup an adapter for a given provider
  211. *
  212. * @param string $providerId ID of the provider
  213. * @param array $params Adapter params
  214. * @return Hybrid_Provider_Adapter
  215. */
  216. public static function setup($providerId, $params = null) {
  217. Hybrid_Logger::debug("Enter Hybrid_Auth::setup( $providerId )", $params);
  218. if (!$params) {
  219. $params = Hybrid_Auth::storage()->get("hauth_session.$providerId.id_provider_params");
  220. Hybrid_Logger::debug("Hybrid_Auth::setup( $providerId ), no params given. Trying to get the stored for this provider.", $params);
  221. }
  222. if (!$params) {
  223. $params = array();
  224. Hybrid_Logger::info("Hybrid_Auth::setup( $providerId ), no stored params found for this provider. Initialize a new one for new session");
  225. }
  226. if (is_array($params) && !isset($params["hauth_return_to"])) {
  227. $params["hauth_return_to"] = Hybrid_Auth::getCurrentUrl();
  228. Hybrid_Logger::debug("Hybrid_Auth::setup( $providerId ). HybridAuth Callback URL set to: ", $params["hauth_return_to"]);
  229. }
  230. # instantiate a new IDProvider Adapter
  231. $provider = new Hybrid_Provider_Adapter();
  232. $provider->factory($providerId, $params);
  233. return $provider;
  234. }
  235. /**
  236. * Check if the current user is connected to a given provider
  237. *
  238. * @param string $providerId ID of the provider
  239. * @return bool
  240. */
  241. public static function isConnectedWith($providerId) {
  242. return (bool) Hybrid_Auth::storage()->get("hauth_session.{$providerId}.is_logged_in");
  243. }
  244. /**
  245. * Return array listing all authenticated providers
  246. * @return array
  247. */
  248. public static function getConnectedProviders() {
  249. $idps = array();
  250. foreach (Hybrid_Auth::$config["providers"] as $idpid => $params) {
  251. if (Hybrid_Auth::isConnectedWith($idpid)) {
  252. $idps[] = $idpid;
  253. }
  254. }
  255. return $idps;
  256. }
  257. /**
  258. * Return array listing all enabled providers as well as a flag if you are connected
  259. *
  260. * <code>
  261. * array(
  262. * 'Facebook' => array(
  263. * 'connected' => true
  264. * )
  265. * )
  266. * </code>
  267. * @return array
  268. */
  269. public static function getProviders() {
  270. $idps = array();
  271. foreach (Hybrid_Auth::$config["providers"] as $idpid => $params) {
  272. if ($params['enabled']) {
  273. $idps[$idpid] = array('connected' => false);
  274. if (Hybrid_Auth::isConnectedWith($idpid)) {
  275. $idps[$idpid]['connected'] = true;
  276. }
  277. }
  278. }
  279. return $idps;
  280. }
  281. /**
  282. * A generic function to logout all connected provider at once
  283. * @return void
  284. */
  285. public static function logoutAllProviders() {
  286. $idps = Hybrid_Auth::getConnectedProviders();
  287. foreach ($idps as $idp) {
  288. $adapter = Hybrid_Auth::getAdapter($idp);
  289. $adapter->logout();
  290. }
  291. }
  292. /**
  293. * Utility function, redirect to a given URL with php header or using javascript location.href
  294. *
  295. * @param string $url URL to redirect to
  296. * @param string $mode PHP|JS
  297. */
  298. public static function redirect($url, $mode = "PHP") {
  299. Hybrid_Logger::info("Enter Hybrid_Auth::redirect( $url, $mode )");
  300. // Ensure session is saved before sending response, see https://github.com/symfony/symfony/pull/12341
  301. if ((PHP_VERSION_ID >= 50400 && PHP_SESSION_ACTIVE === session_status()) || (PHP_VERSION_ID < 50400 && isset($_SESSION) && session_id())) {
  302. session_write_close();
  303. }
  304. if ($mode == "PHP") {
  305. header("Location: $url");
  306. } elseif ($mode == "JS") {
  307. echo '<html>';
  308. echo '<head>';
  309. echo '<script type="text/javascript">';
  310. echo 'function redirect(){ window.top.location.href="' . $url . '"; }';
  311. echo '</script>';
  312. echo '</head>';
  313. echo '<body onload="redirect()">';
  314. echo 'Redirecting, please wait...';
  315. echo '</body>';
  316. echo '</html>';
  317. }
  318. die();
  319. }
  320. /**
  321. * Utility function, return the current url
  322. *
  323. * @param bool $request_uri true to get $_SERVER['REQUEST_URI'], false for $_SERVER['PHP_SELF']
  324. * @return string
  325. */
  326. public static function getCurrentUrl($request_uri = true) {
  327. if (php_sapi_name() == 'cli') {
  328. return '';
  329. }
  330. $protocol = 'http://';
  331. if ((isset($_SERVER['HTTPS']) && ( $_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1 ))
  332. || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))
  333. {
  334. $protocol = 'https://';
  335. }
  336. $url = $protocol . $_SERVER['HTTP_HOST'];
  337. if ($request_uri) {
  338. $url .= $_SERVER['REQUEST_URI'];
  339. } else {
  340. $url .= $_SERVER['PHP_SELF'];
  341. }
  342. // return current url
  343. return $url;
  344. }
  345. }