Authenticator.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. /** @package verysimple::Authentication */
  3. /** import supporting libraries */
  4. require_once("IAuthenticatable.php");
  5. require_once("AuthenticationException.php");
  6. /**
  7. * Authenticator is a collection of static methods for storing a current user
  8. * in the session and determining if the user has necessary permissions to
  9. * perform an action
  10. * @package verysimple::Authentication
  11. * @author VerySimple Inc.
  12. * @copyright 1997-2007 VerySimple, Inc.
  13. * @license http://www.gnu.org/licenses/lgpl.html LGPL
  14. * @version 1.0
  15. */
  16. class Authenticator
  17. {
  18. static $user = null;
  19. static $is_initialized = false;
  20. public static function Init()
  21. {
  22. if (!self::$is_initialized)
  23. {
  24. self::$is_initialized = true;
  25. if (session_id() == '')
  26. {
  27. @session_start();
  28. }
  29. }
  30. }
  31. /**
  32. * Returns the currently authenticated user or null
  33. *
  34. * @access public
  35. * @return IAuthenticatable || null
  36. */
  37. public static function GetCurrentUser($guid = "CURRENT_USER")
  38. {
  39. if (self::$user == null)
  40. {
  41. self::Init();
  42. if (isset($_SESSION[$guid]))
  43. {
  44. self::$user = unserialize($_SESSION[$guid]);
  45. }
  46. }
  47. return self::$user;
  48. }
  49. /**
  50. * Set the given IAuthenticable object as the currently authenticated user.
  51. * UnsetAllSessionVars will be called before setting the current user
  52. *
  53. * @param IAuthenticatable $user
  54. * @param mixed $guid a unique id for this session
  55. *
  56. */
  57. public static function SetCurrentUser(IAuthenticatable $user, $guid = "CURRENT_USER")
  58. {
  59. self::UnsetAllSessionVars(); // this calls Init so we don't have to here
  60. self::$user = $user;
  61. $_SESSION[$guid] = serialize($user);
  62. }
  63. /**
  64. * Unsets all session variables without destroying the session
  65. *
  66. */
  67. public static function UnsetAllSessionVars()
  68. {
  69. self::Init();
  70. foreach (array_keys($_SESSION) as $key)
  71. {
  72. unset($_SESSION[$key]);
  73. }
  74. }
  75. /**
  76. * Forcibly clear all _SESSION variables and destroys the session
  77. *
  78. * @param string $guid The GUID of this user
  79. */
  80. public static function ClearAuthentication($guid = "CURRENT_USER")
  81. {
  82. self::Init();
  83. self::$user = null;
  84. unset($_SESSION[$guid]);
  85. self::UnsetAllSessionVars();
  86. @session_destroy();
  87. }
  88. }
  89. ?>