PageRenderTime 26ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/tiendasikah/core/libs/auth/auth.php

http://tiendasikah.googlecode.com/
PHP | 294 lines | 165 code | 0 blank | 129 comment | 27 complexity | 10d3617eaba63e5ba93c266aaefb9720 MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause
  1. <?php
  2. /**
  3. * KumbiaPHP web & app Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://wiki.kumbiaphp.com/Licencia
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@kumbiaphp.com so we can send you a copy immediately.
  14. *
  15. * Esta clase permite autenticar usuarios
  16. *
  17. * @category extensions
  18. * @package Auth
  19. * @copyright Copyright (c) 2005-2009 Kumbia Team (http://www.kumbiaphp.com)
  20. * @license http://wiki.kumbiaphp.com/Licencia New BSD License
  21. */
  22. /**
  23. * @see AuthInterface
  24. */
  25. require_once CORE_PATH . 'libs/auth/auth_interface.php';
  26. class Auth
  27. {
  28. /**
  29. * Nombre del adaptador usado para autenticar
  30. *
  31. * @var string
  32. */
  33. private $adapter;
  34. /**
  35. * Objeto Adaptador actual
  36. *
  37. * @var mixed
  38. */
  39. private $adapter_object = null;
  40. /**
  41. * Indica si un usuario debe loguearse solo una vez en el sistema desde
  42. * cualquier parte
  43. *
  44. * @var boolean
  45. */
  46. private $active_session = false;
  47. /**
  48. * Tiempo en que expirara la sesion en caso de que no se termine con destroy_active_session
  49. *
  50. * @var integer
  51. */
  52. private $expire_time = 3600;
  53. /**
  54. * Argumentos extra enviados al Adaptador
  55. *
  56. * @var array
  57. */
  58. private $extra_args = array();
  59. /**
  60. * Tiempo que duerme la aplicacion cuando falla la autenticacion
  61. */
  62. private $sleep_time = 0;
  63. /**
  64. * Indica si el ultimo llamado a authenticate tuvo exito o no (persistente en sesion)
  65. *
  66. * @var boolean
  67. */
  68. private static $is_valid = null;
  69. /**
  70. * Ultima identidad obtenida por Authenticate (persistente en sesion)
  71. *
  72. * @var array
  73. */
  74. private static $active_identity = array();
  75. /**
  76. * Constructor del Autenticador
  77. *
  78. * @param string $adapter
  79. */
  80. public function __construct ()
  81. {
  82. $extra_args = Util::getParams(func_get_args());
  83. if (isset($extra_args[0])) {
  84. $adapter = $extra_args[0];
  85. unset($extra_args[0]);
  86. } else {
  87. $adapter = 'model';
  88. }
  89. $this->set_adapter($adapter, $this, $extra_args);
  90. }
  91. public function set_adapter ($adapter, $auth = null, $extra_args = array())
  92. {
  93. if (! in_array($adapter, array('digest' , 'http' , 'model' , 'kerberos5' , 'radius'))) {
  94. throw new kumbiaException("Adaptador de autenticaci&oacute;n '$adapter' no soportado");
  95. }
  96. $this->adapter = Util::camelcase($adapter);
  97. require_once CORE_PATH . "libs/auth/adapters/{$adapter}_auth.php";
  98. $adapter_class = $this->adapter . 'Auth';
  99. $this->extra_args = $extra_args;
  100. $this->adapter_object = new $adapter_class($auth, $extra_args);
  101. }
  102. /**
  103. * Obtiene el nombre del adaptador actual
  104. * @return boolean
  105. */
  106. public function get_adapter_name ($adapter)
  107. {
  108. return $this->adapter;
  109. }
  110. /**
  111. * Realiza el proceso de autenticaci?n
  112. *
  113. * @return array
  114. */
  115. public function authenticate ()
  116. {
  117. $result = $this->adapter_object->authenticate();
  118. /**
  119. * Si es una sesion activa maneja un archivo persistente para control
  120. */
  121. if ($result && $this->active_session) {
  122. $user_hash = md5(serialize($this->extra_args));
  123. $filename = APP_PATH . 'temp/cache/' . base64_encode('auth');
  124. if (file_exists($filename)) {
  125. $fp = fopen($filename, 'r');
  126. while (! feof($fp)) {
  127. $line = fgets($fp);
  128. $user = explode(':', $line);
  129. if ($user_hash == $user[0]) {
  130. if ($user[1] + $user[2] > time()) {
  131. if ($this->sleep_time) {
  132. sleep($this->sleep_time);
  133. }
  134. self::$active_identity = array();
  135. self::$is_valid = false;
  136. return false;
  137. } else {
  138. fclose($fp);
  139. $this->destroy_active_session();
  140. file_put_contents($filename, $user_hash . ':' . time() . ':' . $this->expire_time . "\n");
  141. }
  142. }
  143. }
  144. fclose($fp);
  145. $fp = fopen($filename, 'a');
  146. fputs($fp, $user_hash . ':' . time() . ':' . $this->expire_time . "\n");
  147. fclose($fp);
  148. } else {
  149. file_put_contents($filename, $user_hash . ':' . time() . ':' . $this->expire_time . "\n");
  150. }
  151. }
  152. if (! $result) {
  153. if ($this->sleep_time) {
  154. sleep($this->sleep_time);
  155. }
  156. }
  157. $_SESSION['KUMBIA_AUTH_IDENTITY'] = $this->adapter_object->get_identity();
  158. self::$active_identity = $this->adapter_object->get_identity();
  159. $_SESSION['KUMBIA_AUTH_VALID'] = $result;
  160. self::$is_valid = $result;
  161. return $result;
  162. }
  163. /**
  164. * Realiza el proceso de autenticaci&oacute;n usando HTTP
  165. *
  166. * @return array
  167. */
  168. public function authenticate_with_http ()
  169. {
  170. if (! $_SERVER['PHP_AUTH_USER']) {
  171. header('WWW-Authenticate: Basic realm="basic"');
  172. header('HTTP/1.0 401 Unauthorized');
  173. return false;
  174. } else {
  175. $options = array("username" => $_SERVER['PHP_AUTH_USER'] , "password" => $_SERVER['PHP_AUTH_PW']);
  176. $this->adapter_object->set_params($options);
  177. return $this->authenticate();
  178. }
  179. }
  180. /**
  181. * Devuelve la identidad encontrada en caso de exito
  182. *
  183. * @return array
  184. */
  185. public function get_identity ()
  186. {
  187. return $this->adapter_object->get_identity();
  188. }
  189. /**
  190. * Permite controlar que usuario no se loguee mas de una vez en el sistema desde cualquier parte
  191. *
  192. * @param string $value
  193. */
  194. public function set_active_session ($value, $time = 3600)
  195. {
  196. $this->active_session = $value;
  197. $this->expire_time = $time;
  198. }
  199. /**
  200. * Destruir sesion activa del usuario autenticado
  201. *
  202. */
  203. public function destroy_active_session ()
  204. {
  205. $user_hash = md5(serialize($this->extra_args));
  206. $filename = APP_PATH . 'temp/cache/' . base64_encode('auth');
  207. $lines = file($filename);
  208. $lines_out = array();
  209. foreach ($lines as $line) {
  210. if (substr($line, 0, 32) != $user_hash) {
  211. $lines_out[] = $line;
  212. }
  213. }
  214. file_put_contents($filename, join("\n", $lines_out));
  215. }
  216. /**
  217. * Devuelve la instancia del adaptador
  218. *
  219. * @return string
  220. */
  221. public function get_adapter_instance ()
  222. {
  223. return $this->adapter_object;
  224. }
  225. /**
  226. * Determinar si debe dormir la aplicacion cuando falle la autenticacion y cuanto tiempo en segundos
  227. *
  228. * @param boolean $value
  229. * @param integer $time
  230. */
  231. public function sleep_on_fail ($value, $time = 2)
  232. {
  233. $time = (int) $time;
  234. if ($time < 0) {
  235. $time = 0;
  236. }
  237. if ($value) {
  238. $this->sleep_time = $time;
  239. } else {
  240. $this->sleep_time = 0;
  241. }
  242. }
  243. /**
  244. * Devuelve el resultado del ultimo llamado a authenticate desde el ultimo objeto Auth instanciado
  245. *
  246. * @return boolean
  247. */
  248. static public function is_valid ()
  249. {
  250. if (! is_null(self::$is_valid)) {
  251. return self::$is_valid;
  252. } else {
  253. self::$is_valid = isset($_SESSION['KUMBIA_AUTH_VALID']) ? $_SESSION['KUMBIA_AUTH_VALID'] : null;
  254. return self::$is_valid;
  255. }
  256. }
  257. /**
  258. * Devuelve el resultado de la ultima identidad obtenida en authenticate desde el ultimo objeto Auth instanciado
  259. *
  260. * @return array
  261. */
  262. static public function get_active_identity ()
  263. {
  264. if (count(self::$active_identity)) {
  265. return self::$active_identity;
  266. } else {
  267. self::$active_identity = $_SESSION['KUMBIA_AUTH_IDENTITY'];
  268. return self::$active_identity;
  269. }
  270. }
  271. /**
  272. * Obtiene un valor de la identidad actual
  273. *
  274. * @param string $var
  275. * @return string
  276. */
  277. public static function get($var = null)
  278. {
  279. if($var){
  280. return $_SESSION['KUMBIA_AUTH_IDENTITY'][$var];
  281. }
  282. }
  283. /**
  284. * Anula la identidad actual
  285. *
  286. */
  287. static public function destroy_identity ()
  288. {
  289. self::$is_valid = null;
  290. unset($_SESSION['KUMBIA_AUTH_VALID']);
  291. self::$active_identity = null;
  292. unset($_SESSION['KUMBIA_AUTH_IDENTITY']);
  293. }
  294. }