PageRenderTime 27ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/engine/_classes/class.bertasecurity.php

https://github.com/raphaelbastide/berta
PHP | 230 lines | 137 code | 70 blank | 23 comment | 26 complexity | ef619e7c373f11631334729e17c9fd8a MD5 | raw file
  1. <?php
  2. /*
  3. ==================================================================================================================================
  4. CLASS BertaSecurity
  5. Manages security and ip-tracking operations:
  6. (*) Log-in and log-out
  7. (*) Session-based authentification
  8. (*) Protected areas
  9. ==================================================================================================================================
  10. */
  11. class BertaSecurity {
  12. const BERTASECURITY_ERROR_SESSION_VARIABLE = 1; // session variable corrupt
  13. const BERTASECURITY_ERROR_SESSION_EXPIRED = 2; // session expired
  14. const BERTASECURITY_ERROR_SESSION_IP_CONFLICT = 3; // ip address has changed
  15. const BERTASECURITY_ERROR_LOGIN_VARIABLE = 4; // login variables corrupt or empty
  16. const BERTASECURITY_ERROR_LOGIN_INCORRECT = 5; // login user and password incorrect
  17. public $authExpiresSeconds; // session idle time
  18. public $authUseAuthentification = false;
  19. public $authentificated = false; // if
  20. public $userLoggedIn = false;
  21. public $user; // array of all user information available in the database (id, ident, nick, email, etc.)
  22. public $accessIP; // array containing ip address by bytes
  23. public $accessIPStr = '';
  24. public $errAuth = 0; // the reason (id), why autentification failed;
  25. public $errLogin = 0; // the reason (id), why login failed;
  26. public function BertaSecurity($authEnvironment = 'site', $authExpiresSeconds = 21600) {
  27. $this->authExpiresSeconds = $authExpiresSeconds;
  28. $this->authUseAuthentification = true;
  29. $this->authentificated = $this->authUseAuthentification ? $this->authentificate() : true;
  30. // todo - change relying on userLoggedIn to a new environment variable
  31. if($authEnvironment == 'site') {
  32. $this->userLoggedIn = false;
  33. }
  34. }
  35. public function getAccessIP() {
  36. $this->accessIPStr = $_SERVER["REMOTE_ADDR"];
  37. if(preg_match("/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/", $this->accessIPStr, $ipRegs)) {
  38. $this->accessIP = array((int) $ipRegs[1],
  39. (int) $ipRegs[2],
  40. (int) $ipRegs[3],
  41. (int) $ipRegs[4]);
  42. return $this->accessIP;
  43. } else
  44. return false;
  45. }
  46. // ------------------------------------------------------------------------------------------------------------------------------
  47. // -- Login and authentification ------------------------------------------------------------------------------------------
  48. // ------------------------------------------------------------------------------------------------------------------------------
  49. public function authentificate() {
  50. //echo Berta::$options['SITE_ABS_ROOT'];
  51. session_name(BertaUtils::canonizeString('berta_' . Berta::$options['version'] . '_' . Berta::$options['SITE_ABS_ROOT'], '_', ''));
  52. session_start();
  53. $curTime = time();
  54. //var_dump($_SESSION);
  55. //echo $curTime - $_SESSION['_berta__user']['last_access'];
  56. if(isset($_SESSION['_berta__user']) && is_array($_SESSION['_berta__user'])) {
  57. if(($curTime - $_SESSION['_berta__user']['last_access'] <= $this->authExpiresSeconds)) {
  58. if($_SESSION['_berta__user']['last_ip'] == $_SERVER['REMOTE_ADDR']) {
  59. $_SESSION['_berta__user']['last_access'] = $curTime;
  60. $this->user = $_SESSION['_berta__user'];
  61. $this->userLoggedIn = true;
  62. if(!empty($_REQUEST['_security_reload_user']))
  63. $this->updateUserSettings($this->user);
  64. return $this->userLoggedIn = true;
  65. } else {
  66. $this->destroy(self::BERTASECURITY_ERROR_SESSION_IP_CONFLICT); // ip conflict
  67. return $this->userLoggedIn = false;
  68. }
  69. } else {
  70. $this->destroy(self::BERTASECURITY_ERROR_SESSION_EXPIRED);
  71. return $this->userLoggedIn = false;
  72. }
  73. } elseif(isset($_SESSION['_berta__user']) && !is_array($_SESSION['_berta__user'])) {
  74. $this->destroy(self::BERTASECURITY_ERROR_SESSION_VARIABLE);
  75. return $this->userLoggedIn = false;
  76. } else {
  77. return $this->userLoggedIn = false;
  78. }
  79. }
  80. public function goToLoginPage($loginPageRelativeURL) {
  81. $qS = $this->errAuth ? "?autherror=" . $this->errAuth : "";
  82. if(headers_sent()) {
  83. echo '<script language="javascript" type="text/javascript">window.location="' . $loginPageRelativeURL . $qS . '";</script>';
  84. echo '<p>Please wait... (or <a href="' . $loginPageRelativeURL . $qS . '">click here</a> if nothing happens)</p>';
  85. } else
  86. header('Location: ' . $loginPageRelativeURL . $qS);
  87. exit;
  88. }
  89. public function login($name, $pass, $realName, $realPass) {
  90. if($name && $pass) {
  91. if($name == $realName && $pass == $realPass) {
  92. $this->destroy();
  93. session_start();
  94. $this->updateUserSettings(array('name' => $realName));
  95. return $this->userLoggedIn = true;
  96. } else {
  97. $this->errLogin = self::BERTASECURITY_ERROR_LOGIN_INCORRECT; // wrong creditentials
  98. return false;
  99. }
  100. } else {
  101. $this->errLogin = self::BERTASECURITY_ERROR_LOGIN_VARIABLE; // no identification supplied
  102. return false;
  103. }
  104. }
  105. public function destroy($authErrNo = false) {
  106. if(isset($_SESSION['_berta__user'])) unset($_SESSION['_berta__user']);
  107. @session_destroy();
  108. $this->user = array();
  109. //echo $authErrNo;
  110. return true;
  111. }
  112. public function updateUserSettings($user = false) {
  113. if(isset($user["last_access_sec"])) $this->user["prev_access"] = $user["last_access_sec"];
  114. if(isset($user["last_ip"])) $this->user["prev_ip"] = $user["last_ip"];
  115. $this->user = array_merge($user, array(
  116. "user_name" => $user["name"] ? $user["name"] : $user['nickname'],
  117. "login_time" => time(),
  118. "last_access" => time(),
  119. "last_ip" => $_SERVER['REMOTE_ADDR']));
  120. $_SESSION['_berta__user'] = $this->user;
  121. }
  122. // ------------------------------------------------------------------------------------------------------------------------------
  123. // -- Misc ----------------------------------------------------------------------------------------------------------------
  124. // ------------------------------------------------------------------------------------------------------------------------------
  125. public function getError($errType, $errId) {
  126. switch($errType) {
  127. case "auth":
  128. switch($errId) {
  129. case self::BERTASECURITY_ERROR_SESSION_VARIABLE: return "Please check whether your browser supports cookies!";
  130. case self::BERTASECURITY_ERROR_SESSION_EXPIRED: return "The max idle time is " . round($this->authExpiresSeconds / 60) . " minutes.";
  131. case self::BERTASECURITY_ERROR_SESSION_IP_CONFLICT: return "Your IP address has changed... any idea why?";
  132. default: return "Unknown error (id: $errId).";
  133. }
  134. case "login":
  135. switch($errId) {
  136. case self::BERTASECURITY_ERROR_LOGIN_VARIABLE: return "Pardon?";
  137. case self::BERTASECURITY_ERROR_LOGIN_INCORRECT:
  138. $arr = array("Pardon?");
  139. return $arr[array_rand($arr)];
  140. case 8: return "You have been deactivated.";
  141. default: return "Unknown error ($errId)";
  142. }
  143. }
  144. }
  145. function dispNocacheHeaders() {
  146. if(!headers_sent()) {
  147. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  148. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  149. header("Cache-Control: no-store, no-cache, must-revalidate");
  150. header("Cache-Control: post-check=0, pre-check=0", false);
  151. header("Pragma: no-cache");
  152. return true;
  153. }
  154. return false;
  155. }
  156. }
  157. ?>