SessionManager.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace Shaarli;
  3. /**
  4. * Manages the server-side session
  5. */
  6. class SessionManager
  7. {
  8. protected $session = [];
  9. /**
  10. * Constructor
  11. *
  12. * @param array $session The $_SESSION array (reference)
  13. * @param ConfigManager $conf ConfigManager instance
  14. */
  15. public function __construct(& $session, $conf)
  16. {
  17. $this->session = &$session;
  18. $this->conf = $conf;
  19. }
  20. /**
  21. * Generates a session token
  22. *
  23. * @return string token
  24. */
  25. public function generateToken()
  26. {
  27. $token = sha1(uniqid('', true) .'_'. mt_rand() . $this->conf->get('credentials.salt'));
  28. $this->session['tokens'][$token] = 1;
  29. return $token;
  30. }
  31. /**
  32. * Checks the validity of a session token, and destroys it afterwards
  33. *
  34. * @param string $token The token to check
  35. *
  36. * @return bool true if the token is valid, else false
  37. */
  38. public function checkToken($token)
  39. {
  40. if (! isset($this->session['tokens'][$token])) {
  41. // the token is wrong, or has already been used
  42. return false;
  43. }
  44. // destroy the token to prevent future use
  45. unset($this->session['tokens'][$token]);
  46. return true;
  47. }
  48. /**
  49. * Validate session ID to prevent Full Path Disclosure.
  50. *
  51. * See #298.
  52. * The session ID's format depends on the hash algorithm set in PHP settings
  53. *
  54. * @param string $sessionId Session ID
  55. *
  56. * @return true if valid, false otherwise.
  57. *
  58. * @see http://php.net/manual/en/function.hash-algos.php
  59. * @see http://php.net/manual/en/session.configuration.php
  60. */
  61. public static function checkId($sessionId)
  62. {
  63. if (empty($sessionId)) {
  64. return false;
  65. }
  66. if (!$sessionId) {
  67. return false;
  68. }
  69. if (!preg_match('/^[a-zA-Z0-9,-]{2,128}$/', $sessionId)) {
  70. return false;
  71. }
  72. return true;
  73. }
  74. }