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