Overview
Comment:Migration vers KD2\UserSession (composant réutilisable)
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | dev
Files: files | file ages | folders
SHA1: 0a535d8a8f769512e06754c8a11a3313869fb41f
User & Date: bohwaz on 2017-09-04 07:06:35
Other Links: branch diff | manifest | tags
Context
2017-09-04
07:07
Corrections pour les changements liés à la migration vers UserSession check-in: 4e5588b1ba user: bohwaz tags: dev
07:06
Migration vers KD2\UserSession (composant réutilisable) check-in: 0a535d8a8f user: bohwaz tags: dev
2017-09-03
00:17
Ne pas prendre en compte LOCAL_LOGIN s'il est positionné sur false/null/0 check-in: 2b5e5aed0c user: bohwaz tags: dev
Changes

Modified src/include/lib/Garradin/Fichiers.php from [6cbd651b6a] to [398f6de205].

170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
		// Page wiki publique, aucune vérification à faire, seul cas d'accès à un fichier en dehors de l'espace admin
		if ($wiki !== false && $wiki == Wiki::LECTURE_PUBLIC)
		{
			return true;
		}
			
		// Pas d'utilisateur connecté, pas d'accès aux fichiers de l'espace admin
		if (empty($user->droits))
		{
			return false;
		}

		if ($wiki !== false)
		{
			// S'il n'a même pas droit à accéder au wiki c'est mort
			if ($user->droits->wiki < Membres::DROIT_ACCES)
			{
				return false;
			}

			// On renvoie à l'objet Wiki pour savoir si l'utilisateur a le droit de lire ce fichier
			$_w = new Wiki;
			$_w->setRestrictionCategorie($user->id_categorie, $user->droits->wiki);
			return $_w->canReadPage($wiki);
		}

		// On regarde maintenant si le fichier est lié à la compta
		$query = sprintf('SELECT 1 FROM fichiers_%s WHERE fichier = ? LIMIT 1;', self::LIEN_COMPTA);
		$compta = $db->firstColumn($query, (int)$this->id);

		if ($compta && $user->droits->compta >= Membres::DROIT_ACCES)
		{
			// OK si accès à la compta
			return true;
		}

		// Enfin, si le fichier est lié à un membre
		$query = sprintf('SELECT id FROM fichiers_%s WHERE fichier = ? LIMIT 1;', self::LIEN_MEMBRES);
		$membre = $db->firstColumn($query, (int)$this->id);

		if ($membre !== false)
		{
			// De manière évidente, l'utilisateur a le droit d'accéder aux fichiers liés à son profil
			if ((int)$membre == $user->id)
			{
				return true;
			}

			// Pour voir les fichiers des membres il faut pouvoir les gérer
			if ($user->droits->membres >= Membres::DROIT_ECRITURE)
			{
				return true;
			}
		}

		return false;
	}







|







|






|







|


















|







170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
		// Page wiki publique, aucune vérification à faire, seul cas d'accès à un fichier en dehors de l'espace admin
		if ($wiki !== false && $wiki == Wiki::LECTURE_PUBLIC)
		{
			return true;
		}
			
		// Pas d'utilisateur connecté, pas d'accès aux fichiers de l'espace admin
		if (!isset($user->droit_wiki))
		{
			return false;
		}

		if ($wiki !== false)
		{
			// S'il n'a même pas droit à accéder au wiki c'est mort
			if (!$session->canAccess('wiki', Membres::DROIT_ACCES))
			{
				return false;
			}

			// On renvoie à l'objet Wiki pour savoir si l'utilisateur a le droit de lire ce fichier
			$_w = new Wiki;
			$_w->setRestrictionCategorie($user->id_categorie, $user->droit_wiki);
			return $_w->canReadPage($wiki);
		}

		// On regarde maintenant si le fichier est lié à la compta
		$query = sprintf('SELECT 1 FROM fichiers_%s WHERE fichier = ? LIMIT 1;', self::LIEN_COMPTA);
		$compta = $db->firstColumn($query, (int)$this->id);

		if ($compta && $session->canAccess('compta', Membres::DROIT_ACCES))
		{
			// OK si accès à la compta
			return true;
		}

		// Enfin, si le fichier est lié à un membre
		$query = sprintf('SELECT id FROM fichiers_%s WHERE fichier = ? LIMIT 1;', self::LIEN_MEMBRES);
		$membre = $db->firstColumn($query, (int)$this->id);

		if ($membre !== false)
		{
			// De manière évidente, l'utilisateur a le droit d'accéder aux fichiers liés à son profil
			if ((int)$membre == $user->id)
			{
				return true;
			}

			// Pour voir les fichiers des membres il faut pouvoir les gérer
			if ($session->canAccess('membres', Membres::DROIT_ECRITURE))
			{
				return true;
			}
		}

		return false;
	}

Modified src/include/lib/Garradin/Membres.php from [4adbad4a37] to [0578514af1].

35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
        // Remove NUL bytes
        // see http://blog.ircmaxell.com/2015/03/security-issue-combining-bcrypt-with.html
        $password = str_replace("\0", '', $password);

        return password_hash($password, \PASSWORD_DEFAULT);
    }

    static public function checkPassword($password, $stored_hash)
    {
        // Remove NUL bytes
        // see http://blog.ircmaxell.com/2015/03/security-issue-combining-bcrypt-with.html
        $password = str_replace("\0", '', $password);

        return password_verify($password, $stored_hash);
    }

    // Gestion des données ///////////////////////////////////////////////////////

    public function _checkFields(&$data, $check_editable = true, $check_password = true)
    {
        $champs = Config::getInstance()->get('champs_membres');

        foreach ($champs->getAll() as $key=>$config)







<
<
<
<
<
<
<
<
<







35
36
37
38
39
40
41









42
43
44
45
46
47
48
        // Remove NUL bytes
        // see http://blog.ircmaxell.com/2015/03/security-issue-combining-bcrypt-with.html
        $password = str_replace("\0", '', $password);

        return password_hash($password, \PASSWORD_DEFAULT);
    }










    // Gestion des données ///////////////////////////////////////////////////////

    public function _checkFields(&$data, $check_editable = true, $check_password = true)
    {
        $champs = Config::getInstance()->get('champs_membres');

        foreach ($champs->getAll() as $key=>$config)
255
256
257
258
259
260
261


262
263
264
265
266
267
268
269
    public function delete($ids)
    {
        if (!is_array($ids))
        {
            $ids = [(int)$ids];
        }



        if ($session = Session::get())
        {
            $user = $session->getUser();

            foreach ($ids as $id)
            {
                if ($user->id == $id)
                {







>
>
|







246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
    public function delete($ids)
    {
        if (!is_array($ids))
        {
            $ids = [(int)$ids];
        }

        $session = new Session;

        if ($session->isLogged())
        {
            $user = $session->getUser();

            foreach ($ids as $id)
            {
                if ($user->id == $id)
                {

Modified src/include/lib/Garradin/Membres/Session.php from [ba6c3b5d63] to [ae5630354e].

1
2
3
4
5
6
7
8
9

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

72
73
74
75
76
77
78
79
80
81
82
83

84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204


205
206
207

208
209
210
211
212

213
214
215
216
217
218
219

220
221
222

223
224
225
226


227
228
229

230
231
232
233
234
235
236
237

238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253













254
255
256
257
258
259
260
<?php

namespace Garradin\Membres;

use Garradin\Config;
use Garradin\DB;
use Garradin\Utils;
use Garradin\Membres;
use Garradin\UserException;

use const Garradin\SECRET_KEY;
use const Garradin\WWW_URL;

use KD2\Security;
use KD2\Security_OTP;
use KD2\QRCode;

class Session
{
	const HASH_ALGO = 'sha256';
	const REQUIRE_OTP = 'otp';

	protected $cookie;
	protected $user;
	protected $id;

	const SESSION_COOKIE_NAME = 'gdin';
	const PERMANENT_COOKIE_NAME = 'gdinp';

	static protected function getSessionOptions()
	{
		$url = parse_url(\Garradin\WWW_URL);

		return [
			'name'            => self::SESSION_COOKIE_NAME,
			'cookie_path'     => $url['path'],
			'cookie_domain'   => $url['host'],
			'cookie_secure'   => (\Garradin\PREFER_HTTPS >= 2) ? true : false,
			'cookie_httponly' => true,
		];
	}

	static protected function start($write = false)
	{
		// Don't start session if it has been already started
		if (isset($_SESSION))
		{
			return true;
		}

		// Only start session if it exists
		if ($write || isset($_COOKIE[self::SESSION_COOKIE_NAME]))
		{
			session_name(self::SESSION_COOKIE_NAME);
			return session_start(self::getSessionOptions());
		}

		return false;
	}

	static public function refresh()
	{
		return self::start(true);
	}

	static public function get()
	{
		try {
			return new Session;
		}
		catch (\LogicException $e) {
			return false;

		}
	}

	static public function login($id, $passe, $permanent = false)
	{
		assert(is_bool($permanent));
		assert(is_string($id));
		assert(is_string($passe));

		$db = DB::getInstance();
		$champ_id = Config::getInstance()->get('champ_identifiant');


		$query = 'SELECT id, passe, secret_otp,
			(SELECT droit_connexion FROM membres_categories AS mc WHERE mc.id = id_categorie) AS droit_connexion
			FROM membres WHERE %s = ? LIMIT 1;';

		$query = sprintf($query, $champ_id);

		$membre = $db->first($query, trim($id));

		// Membre non trouvé
		if (empty($membre))
		{
			return false;
		}

		// vérification du mot de passe
		if (!Membres::checkPassword(trim($passe), $membre->passe))
		{
			return false;
		}

		// vérification que le membre a le droit de se connecter
		if ($membre->droit_connexion == Membres::DROIT_AUCUN)
		{
			return false;
		}

		if ($membre->secret_otp)
		{
			self::start(true);

			$_SESSION = [];

			$_SESSION['otp'] = (object) [
				'id'        => (int) $membre->id,
				'secret'    => $membre->secret_otp,
				'permanent' => $permanent,
			];

			return self::REQUIRE_OTP;
		}
		else
		{
			$user = self::createUserSession($membre->id);

			if ($permanent)
			{
				self::createPermanentSession($membre);
			}

			return true;
		}
	}

	static protected function createUserSession($id)
	{
		$db = DB::getInstance();
		$user = $db->first('SELECT * FROM membres WHERE id = ?;', (int)$id);

		if (!$user)
		{
			throw new \LogicException(sprintf('Aucun utilisateur trouvé avec l\'ID %s', $id));
		}

		$user->droits = new \stdClass;

		// Récupérer les droits
		$droits = $db->first('SELECT * FROM membres_categories WHERE id = ?;', (int)$user->id_categorie);

		foreach ($droits as $key=>$value)
		{
			// Renommer pour simplifier
			$key = str_replace('droit_', '', $key, $found);

			// Si le nom de colonne contient droit_ c'est que c'est un droit !
			if ($found)
			{
				$user->droits->$key = (int) $value;
			}
		}

		self::start(true);
		$_SESSION['user'] = $user;

		return $user;
	}

	/**
	 * Créer une session permanente "remember me"
	 *
	 * @see autoLogin method
	 * @param  \stdClass $user
	 * @return boolean
	 */
	static protected function createPermanentSession(\stdClass $user)
	{
		$selector = hash(self::HASH_ALGO, Security::random_bytes(10));
		$verifier = hash(self::HASH_ALGO, Security::random_bytes(10));
		$expire = (new \DateTime)->modify('+3 months');

		$hash = hash(self::HASH_ALGO, $selector . $verifier . $user->passe . $expire->format(DATE_ATOM));

		DB::getInstance()->insert('membres_sessions', [
			'selecteur' => $selector,
			'hash'      => $hash,
			'expire'    => $expire,
			'id_membre' => $user->id,
		]);

		$cookie = $selector . '|' . $verifier;

		$options = self::getSessionOptions();

		setcookie(self::PERMANENT_COOKIE_NAME, $cookie, $expire->getTimestamp(),
			$options['cookie_path'], $options['cookie_domain'], $options['cookie_secure'],
			$options['cookie_httponly']);

		return true;
	}

	static public function isOTPRequired()
	{


		self::start();

		return !empty($_SESSION['otp']);

	}

	static public function loginOTP($code)
	{
		self::start();


		if (empty($_SESSION['otp']))
		{
			return false;
		}

		$user = $_SESSION['otp'];


		if (empty($user->secret) || empty($user->id))
		{

			return false;
		}

		if (!self::checkOTP($user->secret, $code))


		{
			var_dump($user->secret, $code);
			return false;

		}

		self::createUserSession($user->id);
		$session = new Session($user->id);

		return $session;
	}


	static public function checkOTP($secret, $code)
	{
		if (!Security_OTP::TOTP($secret, $code))
		{
			// Vérifier encore, mais avec le temps NTP
			// au cas où l'horloge du serveur n'est pas à l'heure
			$time = Security_OTP::getTimeFromNTP(\Garradin\NTP_SERVER);

			if (!Security_OTP::TOTP($secret, $code, $time))
			{
				return false;
			}
		}

		return true;
	}














	static public function recoverPasswordCheck($id)
	{
		$db = DB::getInstance();
		$config = Config::getInstance();

		$champ_id = $config->get('champ_identifiant');









>







|

<
<
|
|
|
|

<
<
|
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
<
|
<
<
<
|
<
<
|
<
<
<
<
|
<
<
<
<
<
<
|
>
|
|
|
<

<
<
<
<
<


>
|
<
|
|
<
<
<
<
<
|
<
<
<
|
<
<
<
<
<
|
<
<
|
<
<
|
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
|
<
|

<
<
|
<
<
<
<
|
<
|
<
<
|
<
<
<
<
|
<
<
<
<
|
|
|
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|


|
|

|
<

<
|
<
<
<
|
|


|

>
>
|
|
<
>


|

<
>
|
<
|
|
<
|
<
>
|
<
|
>
|
<
|
<
>
>

<
<
>


<
<
|
<


>
|















>
>
>
>
>
>
>
>
>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19


20
21
22
23
24


25



26
















27
28

29



30


31




32






33
34
35
36
37

38





39
40
41
42

43
44





45



46





47


48


49

50





















51
52
53

54
55


56




57

58


59




60




61
62
63


64


















65
66
67
68
69
70
71

72

73



74
75
76
77
78
79
80
81
82
83

84
85
86
87
88

89
90

91
92

93

94
95

96
97
98

99

100
101
102


103
104
105


106

107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
<?php

namespace Garradin\Membres;

use Garradin\Config;
use Garradin\DB;
use Garradin\Utils;
use Garradin\Membres;
use Garradin\UserException;

use const Garradin\SECRET_KEY;
use const Garradin\WWW_URL;

use KD2\Security;
use KD2\Security_OTP;
use KD2\QRCode;

class Session extends \KD2\UserSession
{


	// Personalisation de la config de UserSession
	protected $cookie_name = 'gdin';
	protected $remember_me_cookie_name = 'gdinp';
	protected $remember_me_expiry = '+3 months';



	// Extension des méthodes de UserSession



	public function __construct()
















	{
		$url = parse_url(WWW_URL);





		parent::__construct(DB::getInstance(), [


			'cookie_domain' => $url['host'],




			'cookie_path'   => $url['path'],






			'cookie_secure' => (\Garradin\PREFER_HTTPS >= 2) ? true : false,
		]);
	}

	protected function getUserForLogin($login)

	{





		$champ_id = Config::getInstance()->get('champ_identifiant');

		// Ne renvoie un membre que si celui-ci a le droit de se connecter
		$query = 'SELECT id, %1$s AS login, passe AS password, secret_otp AS otp_secret

			FROM membres AS m
			INNER JOIN membres_categories AS mc ON mc.id = m.id_categorie





			FROM membres



			WHERE %1$s = ? AND mc.droit_connexion >= %2$d





			LIMIT 1;';





		$query = sprintf($query, $champ_id, Membres::DROIT_ACCES);























		return $db->first($query, $login);
	}


	protected function getUserDataForSession($id)
	{


		return $this->db->first('SELECT m.*, c.droit_connexion, c.droit_wiki, 




			c.droit_membres, c.droit_compta, c.droit_config, c.droit_membres

			FROM membres AS m


			INNER JOIN membres_categories AS c ON m.id_categorie = c.id




			WHERE m.id = ? LIMIT 1;', $id);




	}

	protected function storeRememberMeSelector($selector, $hash, \DateTime $expiry, $user_id)


	{


















		return $this->db->insert('membres_sessions', [
			'selecteur' => $selector,
			'hash'      => $hash,
			'expire'    => $expiry,
			'id_membre' => $user_id,
		]);
	}



	protected function expireRememberMeSelectors()



	{
		return $this->db->delete('membres_sessions', $this->db->where('expire', '<', new \DateTime));
	}

	protected function getRememberMeSelector($selector)
	{
		return $this->db->get('SELECT selecteur AS selector, hash,
			id_membre AS user_id, m.passe AS user_password
			FROM membres_sessions AS s
			INNER JOIN membres AS m ON m.id = s.id_membre

			WHERE s.selecteur = ? LIMIT 1;', $selector);
	}

	protected function deleteRememberMeSelector($selector)
	{

		return $this->db->delete('membres_sessions', $this->db->where('selecteur', $selector));
	}


	protected function deleteAllRememberMeSelectors($user_id)

	{

		return $this->db->delete('membres_sessions', $this->db->where('id_membre', $user_id));
	}


	// Ajout de la gestion de LOCAL_LOGIN
	public function isLogged()

	{

		if (empty($_SESSION['user']) && defined('\Garradin\LOCAL_LOGIN')
			&& is_int(\Garradin\LOCAL_LOGIN) && \Garradin\LOCAL_LOGIN > 0)
		{


			$this->create(\Garradin\LOCAL_LOGIN);
		}



		return parent::isLogged();

	}

	// Ici checkOTP utilise NTP en second recours
	public function checkOTP($secret, $code)
	{
		if (!Security_OTP::TOTP($secret, $code))
		{
			// Vérifier encore, mais avec le temps NTP
			// au cas où l'horloge du serveur n'est pas à l'heure
			$time = Security_OTP::getTimeFromNTP(\Garradin\NTP_SERVER);

			if (!Security_OTP::TOTP($secret, $code, $time))
			{
				return false;
			}
		}

		return true;
	}

	public function generateNewOTPSecret()
	{
		$out = [];
		$out['secret'] = Security_OTP::getRandomSecret();
		$out['secret_display'] = implode(' ', str_split($out['secret'], 4));
		$out['url'] = Security_OTP::getOTPAuthURL(Config::getInstance()->get('nom_asso'), $out['secret']);
	
		$qrcode = new QRCode($out['url']);
		$out['qrcode'] = 'data:image/svg+xml;base64,' . base64_encode($qrcode->toSVG());

		return $out;
	}

	static public function recoverPasswordCheck($id)
	{
		$db = DB::getInstance();
		$config = Config::getInstance();

		$champ_id = $config->get('champ_identifiant');
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
		$password = Membres::hashPassword($password);

		$db->update('membres', ['passe' => $password], 'id = :id', ['id' => (int)$id]);

		return Utils::mail($membre->email, '['.$config->get('nom_asso').'] Nouveau mot de passe', $message);
	}

	public function __construct()
	{
		if (empty($_SESSION['user']) && defined('\Garradin\LOCAL_LOGIN')
			&& is_int(\Garradin\LOCAL_LOGIN) && \Garradin\LOCAL_LOGIN > 0)
		{
			self::createUserSession(\Garradin\LOCAL_LOGIN);
		}

		// Démarrage session
		self::start();

		if (empty($_SESSION['user']))
		{
			$this->autoLogin();
		}

		if (empty($_SESSION['user']))
		{
			throw new \LogicException('Aucun utilisateur connecté.');
		}

		$this->user = $_SESSION['user'];
		$this->id = $this->user->id;
	}

	protected function getPermanentCookie()
	{
		if (empty($_COOKIE[self::PERMANENT_COOKIE_NAME]))
		{
			return false;
		}

		$cookie = $_COOKIE[self::PERMANENT_COOKIE_NAME];

		$data = explode('|', $cookie);

		if (count($data) !== 2)
		{
			return false;
		}

		return (object) [
			'selector' => $data[0],
			'verifier' => $data[1],
		];
	}

	/**
	 * Connexion automatique en utilisant un cookie permanent
	 * (fonction "remember me")
	 *
	 * @link   https://www.databasesandlife.com/persistent-login/
	 * @link   https://paragonie.com/blog/2015/04/secure-authentication-php-with-long-term-persistence
	 * @link   https://paragonie.com/blog/2017/02/split-tokens-token-based-authentication-protocols-without-side-channels
	 * @link   http://jaspan.com/improved_persistent_login_cookie_best_practice
	 * @return boolean
	 */
	protected function autoLogin()
	{
		$cookie = $this->getPermanentCookie();

		if (!$cookie)
		{
			return false;
		}

		$db = DB::getInstance();

		// Suppression des sessions qui ont expiré déjà
		$db->delete('membres_sessions', 'expire < strftime(\'%s\',\'now\')');
		
		$row = $db->first('SELECT ms.hash, ms.id_membre AS id, 
			strftime("%s", ms.expire) AS expire, membres.passe
			FROM membres_sessions AS ms
			INNER JOIN membres ON membres.id = ms.id_membre
			WHERE ms.selecteur = ?;',
			$cookie->selector);

		// Le sélecteur n'est pas valide: supprimons le cookie
		if (!$row)
		{
			return $this->logout();
		}

		// La session stockée ne sert plus à rien à partir de maintenant,
		// et ça empêche de le rejouer
		$db->delete('membres_sessions', 'selecteur = ?', $cookie->selector);

		// On utilise le mot de passe: si l'utilisateur change de mot de passe
		// toutes les sessions précédentes sont invalidées
		$hash = hash(self::HASH_ALGO, $cookie->selector . $cookie->verifier . $row->passe . date(DATE_ATOM, $row->expire));

		// Vérification du token
		if (!hash_equals($row->hash, $hash))
		{
			// Le sélecteur est valide, mais pas le token ?
			// c'est probablement que le cookie a été volé, qu'un attaquant
			// a obtenu un nouveau token, et que l'utilisateur se représente 
			// avec un token qui n'est plus valide.
			// Dans ce cas supprimons toutes les sessions de ce membre pour 
			// le forcer à se re-connecter

			return $this->logout();
		}

		// Re-générons un nouveau vérifieur et mettons à jour le cookie
		// car chaque vérifieur est à usage unique
		self::createPermanentSession($row);

		$this->id = $row->id;

		self::createUserSession($this->id);

		return true;
	}

	public function logout()
	{
		$options = self::getSessionOptions();

		if ($cookie = $this->getPermanentCookie())
		{
			// Suppression de cette session permanente
			DB::getInstance()->delete('membres_sessions', 'selecteur = ?', $cookie->selector);

			setcookie(self::PERMANENT_COOKIE_NAME, null, -1, $options['cookie_path'],
				$options['cookie_domain'], $options['cookie_secure'], $options['cookie_httponly']);
			unset($_COOKIE[self::PERMANENT_COOKIE_NAME]);
		}

		self::start(true);
		session_destroy();
		$_SESSION = [];

		setcookie($options['name'], null, -1, $options['cookie_path'],
			$options['cookie_domain'], $options['cookie_secure'], $options['cookie_httponly']);

		unset($_COOKIE[self::SESSION_COOKIE_NAME]);
	
		return true;
	}

	public function editUser($data)
	{
		(new Membres)->edit($this->id, $data, false);
		$this->updateSessionData();

		return true;
	}

	public function getUser($key = null)
	{
		if (null === $key)
		{
			return $this->user;
		}
		elseif (property_exists($key, $this->user))
		{
			return $this->user->$key;
		}
		else
		{
			return null;
		}
	}

	public function canAccess($category, $permission)
	{
		if (!$this->user)
		{
			return false;
		}

		return ($this->user->droits->$category >= $permission);
	}

	public function requireAccess($category, $permission)
	{
		if (!$this->canAccess($category, $permission))
		{
			throw new UserException('Vous n\'avez pas le droit d\'accéder à cette page.');







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<



|




<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







|







218
219
220
221
222
223
224














































































































































225
226
227
228
229
230
231
232
















233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
		$password = Membres::hashPassword($password);

		$db->update('membres', ['passe' => $password], 'id = :id', ['id' => (int)$id]);

		return Utils::mail($membre->email, '['.$config->get('nom_asso').'] Nouveau mot de passe', $message);
	}















































































































































	public function editUser($data)
	{
		(new Membres)->edit($this->id, $data, false);
		$this->refresh();

		return true;
	}

















	public function canAccess($category, $permission)
	{
		if (!$this->user)
		{
			return false;
		}

		return ($this->user->{'droit_' . $category} >= $permission);
	}

	public function requireAccess($category, $permission)
	{
		if (!$this->canAccess($category, $permission))
		{
			throw new UserException('Vous n\'avez pas le droit d\'accéder à cette page.');
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
	
		$qrcode = new QRCode($out['url']);
		$out['qrcode'] = 'data:image/svg+xml;base64,' . base64_encode($qrcode->toSVG());

		return $out;
	}

	public function sessionStore($key, $value)
	{
		if (!isset($_SESSION['storage']))
		{
			$_SESSION['storage'] = [];
		}

		if ($value === null)
		{
			unset($_SESSION['storage'][$key]);
		}
		else
		{
			$_SESSION['storage'][$key] = $value;
		}

		return true;
	}

	public function sessionGet($key)
	{
		if (!isset($_SESSION['storage'][$key]))
		{
			return null;
		}

		return $_SESSION['storage'][$key];
	}

	public function sendMessage($dest, $sujet, $message, $copie = false)
	{
		$from = $this->getUser();
		$from = $from['email'];
		// Uniquement adresse email pour le moment car faudrait trouver comment
		// indiquer le nom mais qu'il soit correctement échappé FIXME

		$config = Config::getInstance();

		$message .= "\n\n--\nCe message a été envoyé par un membre de ".$config->get('nom_asso');
		$message .= ", merci de contacter ".$config->get('email_asso')." en cas d'abus.";

		if ($copie)
		{
			Utils::mail($from, $sujet, $message);
		}

		return Utils::mail($dest, $sujet, $message, ['From' => $from]);
	}


	public function checkPassword($password)
	{
		return Membres::checkPassword($password, $this->user->passe);
	}

	public function editSecurity(Array $data = [])
	{
		$allowed_fields = ['passe', 'clef_pgp', 'secret_otp'];

		foreach ($data as $key=>$value)
		{
			if (!in_array($key, $allowed_fields))







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















<
<
<
<
<
<







257
258
259
260
261
262
263





























264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283






284
285
286
287
288
289
290
	
		$qrcode = new QRCode($out['url']);
		$out['qrcode'] = 'data:image/svg+xml;base64,' . base64_encode($qrcode->toSVG());

		return $out;
	}






























	public function sendMessage($dest, $sujet, $message, $copie = false)
	{
		$from = $this->getUser();
		$from = $from['email'];
		// Uniquement adresse email pour le moment car faudrait trouver comment
		// indiquer le nom mais qu'il soit correctement échappé FIXME

		$config = Config::getInstance();

		$message .= "\n\n--\nCe message a été envoyé par un membre de ".$config->get('nom_asso');
		$message .= ", merci de contacter ".$config->get('email_asso')." en cas d'abus.";

		if ($copie)
		{
			Utils::mail($from, $sujet, $message);
		}

		return Utils::mail($dest, $sujet, $message, ['From' => $from]);
	}







	public function editSecurity(Array $data = [])
	{
		$allowed_fields = ['passe', 'clef_pgp', 'secret_otp'];

		foreach ($data as $key=>$value)
		{
			if (!in_array($key, $allowed_fields))
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
			{
				throw new UserException('Clé PGP invalide : impossible d\'extraire l\'empreinte.');
			}
		}

		$db = DB::getInstance();
		$db->update('membres', $data, $db->where('id', (int)$this->id));
		$this->updateSessionData();

		return true;
	}

	public function getPGPFingerprint($key, $display = false)
	{
		if (!Security::canUseEncryption())
		{
			return false;
		}

		$fingerprint = Security::getEncryptionKeyFingerprint($key);

		if ($display && $fingerprint)
		{
			$fingerprint = str_split($fingerprint, 4);
			$fingerprint = implode(' ', $fingerprint);
		}

		return $fingerprint;
	}

	public function updateSessionData()
	{
		$this->user = self::createUserSession($this->id);
	}
}







|



|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
315
316
317
318
319
320
321
322
323
324
325
326























			{
				throw new UserException('Clé PGP invalide : impossible d\'extraire l\'empreinte.');
			}
		}

		$db = DB::getInstance();
		$db->update('membres', $data, $db->where('id', (int)$this->id));
		$this->refresh();

		return true;
	}
}























Modified src/www/admin/_inc.php from [1060426865] to [4e850891ca].

41
42
43
44
45
46
47
48
49

50
51
52
53
54
55
56
57
58
59
60
61
62
63

$tpl = Template::getInstance();
$tpl->assign('admin_url', WWW_URL . 'admin/');

$form = new Form;
$tpl->assign_by_ref('form', $form);

$session = Session::get();


$tpl->assign('config', Config::getInstance()->getConfig());

if (!defined('Garradin\LOGIN_PROCESS'))
{
    if (!$session)
    {
        if (Session::isOTPRequired())
        {
            Utils::redirect('/admin/login_otp.php');
        }
        else
        {
            Utils::redirect('/admin/login.php');
        }







|

>




|

|







41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

$tpl = Template::getInstance();
$tpl->assign('admin_url', WWW_URL . 'admin/');

$form = new Form;
$tpl->assign_by_ref('form', $form);

$session = new Session;

$tpl->assign('session', $session);
$tpl->assign('config', Config::getInstance()->getConfig());

if (!defined('Garradin\LOGIN_PROCESS'))
{
    if (!$session->isLogged())
    {
        if ($session->isOTPRequired())
        {
            Utils::redirect('/admin/login_otp.php');
        }
        else
        {
            Utils::redirect('/admin/login.php');
        }