Overview
Comment:Ré-écriture de la gestion de session, en séparant ça de la classe Membres
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | dev
Files: files | file ages | folders
SHA1: 8c2d53a79df5cb7119eb7548842b4b5e4ea56807
User & Date: bohwaz on 2017-03-17 04:48:11
Other Links: branch diff | manifest | tags
Context
2017-03-17
04:50
Correction de quelques bugs dans la gestion de DB check-in: 171c9591b4 user: bohwaz tags: dev
04:48
Ré-écriture de la gestion de session, en séparant ça de la classe Membres check-in: 8c2d53a79d user: bohwaz tags: dev
04:46
Gérer les objets aussi check-in: ce44c3d07c user: bohwaz tags: dev
Changes

Modified src/include/lib/Garradin/Membres.php from [ee858fee20] to [4464c9f554].

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
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
<?php

namespace Garradin;



class Membres
{
    const DROIT_AUCUN = 0;
    const DROIT_ACCES = 1;
    const DROIT_ECRITURE = 2;
    const DROIT_ADMIN = 9;

    const ITEMS_PER_PAGE = 50;

    protected function _getSalt($length)
    {
        static $str = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        
        $out = '';
        $max = strlen($str) - 1;

        for ($i = 0; $i < $length; $i++)
        {
            $random = \KD2\Security::random_int(0, $max);
            $out .= $str[$random];
        }

        return $out;
    }

    protected function _hashPassword($password)
    {
        $salt = '$2a$08$' . $this->_getSalt(22);
        return crypt($password, $salt);
    }

    protected function _checkPassword($password, $stored_hash)
    {
        return crypt($password, $stored_hash) == $stored_hash;
    }

    protected function _sessionStart($force = false)
    {
        if (!isset($_SESSION) && ($force || isset($_COOKIE[session_name()])))
        {
            session_start();
        }

        return true;
    }

    public function keepSessionAlive()
    {
        $this->_sessionStart(true);
    }

    public function login($id, $passe)
    {
        $db = DB::getInstance();
        $champ_id = Config::getInstance()->get('champ_identifiant');

        $r = $db->simpleQuerySingle('SELECT id, passe, id_categorie, secret_otp FROM membres WHERE '.$champ_id.' = ? LIMIT 1;', true, trim($id));

        if (empty($r))
        {
            return false;
        }

        if (!$this->_checkPassword(trim($passe), $r['passe']))
        {
            return false;
        }

        $droits = $this->getDroits($r['id_categorie']);

        if ($droits['connexion'] == self::DROIT_AUCUN)
        {
            return false;
        }

        $this->_sessionStart(true);

        $_SESSION['otp_required'] = !empty($r['secret_otp']) ? true : false;

        $db->simpleExec('UPDATE membres SET date_connexion = datetime(\'now\') WHERE id = ?;', $r['id']);

        return $this->updateSessionData($r['id'], $droits);
    }

    public function loginOTP($code)
    {
        $this->_sessionStart(true);

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

        $membre = $_SESSION['logged_user'];

        if (!$this->checkOTP($membre['secret_otp'], $code))
        {
            return false;
        }


        $_SESSION['otp_required'] = false;

        return true;
    }

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

        return $out;
    }

    public function checkOTP($secret, $code)
    {
        if (!\KD2\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 = \KD2\Security_OTP::getTimeFromNTP('fr.pool.ntp.org');

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

        return true;
    }

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

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

        $membre = $db->simpleQuerySingle('SELECT id, email FROM membres WHERE '.$champ_id.' = ? LIMIT 1;', true, trim($id));

        if (!$membre || trim($membre['email']) == '')
        {
            return false;
        }

        $this->_sessionStart(true);
        $hash = sha1($membre['email'] . $membre['id'] . 'recover' . ROOT . time());
        $_SESSION['recover_password'] = [
            'id' => (int) $membre['id'],
            'email' => $membre['email'],
            'hash' => $hash
        ];

        $message = "Bonjour,\n\nVous avez oublié votre mot de passe ? Pas de panique !\n\n";
        $message.= "Il vous suffit de cliquer sur le lien ci-dessous pour recevoir un nouveau mot de passe.\n\n";
        $message.= WWW_URL . 'admin/password.php?c=' . substr($hash, -10);
        $message.= "\n\nSi vous n'avez pas demandé à recevoir ce message, ignorez-le, votre mot de passe restera inchangé.";

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

    public function recoverPasswordConfirm($hash)
    {
        $this->_sessionStart();

        if (empty($_SESSION['recover_password']['hash']))
            return false;

        if (substr($_SESSION['recover_password']['hash'], -10) != $hash)
            return false;

        $config = Config::getInstance();
        $db = DB::getInstance();

        $password = Utils::suggestPassword();

        $dest = $_SESSION['recover_password']['email'];
        $id = (int)$_SESSION['recover_password']['id'];

        $message = "Bonjour,\n\nVous avez demandé un nouveau mot de passe pour votre compte.\n\n";
        $message.= "Votre adresse email : ".$dest."\n";
        $message.= "Votre nouveau mot de passe : ".$password."\n\n";
        $message.= "Si vous n'avez pas demandé à recevoir ce message, merci de nous le signaler.";

        $password = $this->_hashPassword($password);

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

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

    public function updateSessionData($membre = null, $droits = null)
    {
        if (is_null($membre))
        {
            $membre = $this->get($_SESSION['logged_user']['id']);
        }
        elseif (is_int($membre))
        {
            $membre = $this->get($membre);
        }

        if (is_null($droits))
        {
            $droits = $this->getDroits($membre['id_categorie']);
        }

        $membre['droits'] = $droits;
        $_SESSION['logged_user'] = $membre;
        return true;
    }

    public function localLogin()
    {
        if (!defined('Garradin\LOCAL_LOGIN'))
            return false;

        if (trim(LOCAL_LOGIN) == '')
            return false;

        $db = DB::getInstance();
        $config = Config::getInstance();
        $champ_id = $config->get('champ_identifiant');
        
        if (is_int(LOCAL_LOGIN) && $db->simpleQuerySingle('SELECT 1 FROM membres WHERE id = ? LIMIT 1;', true, LOCAL_LOGIN))
        {
            $this->_sessionStart(true);
            return $this->updateSessionData(LOCAL_LOGIN);
        }
        elseif ($id = $db->simpleQuerySingle('SELECT id FROM membres WHERE '.$champ_id.' = ? LIMIT 1;', true, LOCAL_LOGIN))
        {
            $this->_sessionStart(true);
            return $this->updateSessionData($membre);
        }

        throw new UserException('Le membre ' . LOCAL_LOGIN . ' n\'existe pas, merci de modifier la directive Garradin\LOCAL_LOGIN.');
    }

    public function isLogged()
    {
        $this->_sessionStart();

        if (empty($_SESSION['logged_user']))
        {
            if (defined('Garradin\LOCAL_LOGIN'))
            {
                return $this->localLogin();
            }

            return false;
        }

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

        return true;
    }

    public function isOTPRequired()
    {
        $this->_sessionStart();

        return empty($_SESSION['otp_required']) ? false : true;
    }

    public function getLoggedUser()
    {
        if (!$this->isLogged())
            return false;

        return $_SESSION['logged_user'];
    }

    public function logout()
    {
        $_SESSION = [];
        setcookie(session_name(), '', 0, '/');
        return true;
    }

    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)
    {
        if (!$this->isLogged())
        {
            throw new \LogicException('Cette fonction ne peut être appelée que par un utilisateur connecté.');
        }

        $from = $this->getLoggedUser();
        $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]);
    }

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

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




>
>









|








|






|

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

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

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

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

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



<
<
|
<
<
|
<
<
<
<
<

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







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
<?php

namespace Garradin;

use \KD2\Security;

class Membres
{
    const DROIT_AUCUN = 0;
    const DROIT_ACCES = 1;
    const DROIT_ECRITURE = 2;
    const DROIT_ADMIN = 9;

    const ITEMS_PER_PAGE = 50;

    static protected function _getSalt($length)
    {
        static $str = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        
        $out = '';
        $max = strlen($str) - 1;

        for ($i = 0; $i < $length; $i++)
        {
            $random = Security::random_int(0, $max);
            $out .= $str[$random];
        }

        return $out;
    }

    static public function hashPassword($password)
    {



        // Remove NUL bytes




        // see http://blog.ircmaxell.com/2015/03/security-issue-combining-bcrypt-with.html






        $password = str_replace("\0", '', $password);
























































        if (function_exists('password_hash'))
        {

            return password_hash($password, \PASSWORD_DEFAULT);

        }
























        else


        {


            // Support for PHP < 5.5, FIXME: remove when dropping support for PHP 5.4




            $salt = '$2a$08$' . self::_getSalt(22);






            return crypt($password, $salt);
        }
    }



































































    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);










        if (function_exists('password_verify'))


        {



            return password_verify($password, $stored_hash);


















































        }
        else
        {


            // Support for PHP < 5.5, FIXME: remove when dropping support for PHP 5.4


            return crypt($password, $stored_hash) === $stored_hash;





        }



























    }

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

    public function _checkFields(&$data, $check_editable = true, $check_password = true)
    {
        $champs = Config::getInstance()->get('champs_membres');
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
            && $db->simpleQuerySingle('SELECT 1 FROM membres WHERE '.$id.' = ? LIMIT 1;', false, $data[$id]))
        {
            throw new UserException('La valeur du champ '.$id.' est déjà utilisée par un autre membre, hors ce champ doit être unique à chaque membre.');
        }

        if (isset($data['passe']) && trim($data['passe']) != '')
        {
            $data['passe'] = $this->_hashPassword($data['passe']);
        }
        else
        {
            unset($data['passe']);
        }

        if (empty($data['id_categorie']))







|







196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
            && $db->simpleQuerySingle('SELECT 1 FROM membres WHERE '.$id.' = ? LIMIT 1;', false, $data[$id]))
        {
            throw new UserException('La valeur du champ '.$id.' est déjà utilisée par un autre membre, hors ce champ doit être unique à chaque membre.');
        }

        if (isset($data['passe']) && trim($data['passe']) != '')
        {
            $data['passe'] = self::hashPassword($data['passe']);
        }
        else
        {
            unset($data['passe']);
        }

        if (empty($data['id_categorie']))
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
            {
                throw new UserException('Le numéro n\'est pas modifiable pour ce membre car des contenus sont liés à ce numéro de membre (wiki, compta, etc.).');
            }
        }

        if (!empty($data['passe']) && trim($data['passe']))
        {
            $data['passe'] = $this->_hashPassword($data['passe']);
        }
        else
        {
            unset($data['passe']);
        }

        if (isset($data['id_categorie']) && empty($data['id_categorie']))
        {
            $data['id_categorie'] = Config::getInstance()->get('categorie_membres');
        }

        if (empty($data))
        {
            return true;
        }

        return $db->simpleUpdate('membres', $data, 'id = '.(int)$id);
    }

    public function checkPassword($password)
    {
        $user = $this->getLoggedUser();

        if (!$user)
        {
            return false;
        }

        return $this->_checkPassword($password, $user['passe']);
    }

    public function editSecurity(Array $data = [])
    {
        $user = $this->getLoggedUser();

        if (!$user)
        {
            throw new \LogicException('Utilisateur non connecté.');
        }

        $allowed_fields = ['passe', 'clef_pgp', 'secret_otp'];

        foreach ($data as $key=>$value)
        {
            if (!in_array($key, $allowed_fields))
            {
                throw new \RuntimeException(sprintf('Le champ %s n\'est pas autorisé dans cette méthode.', $key));
            }
        }

        if (isset($data['passe']) && trim($data['passe']) !== '')
        {
            if (strlen($data['passe']) < 5)
            {
                throw new UserException('Le mot de passe doit faire au moins 5 caractères.');
            }

            $data['passe'] = $this->_hashPassword($data['passe']);
        }
        else
        {
            unset($data['passe']);
        }

        if (isset($data['clef_pgp']))
        {
            $data['clef_pgp'] = trim($data['clef_pgp']);

            if (!$this->getPGPFingerprint($data['clef_pgp']))
            {
                throw new UserException('Clé PGP invalide : impossible d\'extraire l\'empreinte.');
            }
        }

        DB::getInstance()->simpleUpdate('membres', $data, 'id = '.(int)$user['id']);
        $this->updateSessionData();

        return true;
    }

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

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

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

        return $fingerprint;
    }

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

        return $db->simpleQuerySingle('SELECT *,
            '.$config->get('champ_identite').' AS identite,
            strftime(\'%s\', date_inscription) AS date_inscription,
            strftime(\'%s\', date_connexion) AS date_connexion
            FROM membres WHERE id = ? LIMIT 1;', true, (int)$id);
    }

    public function delete($ids)
    {
        if (!is_array($ids))
        {
            $ids = [(int)$ids];
        }

        if ($this->isLogged())
        {
            $user = $this->getLoggedUser();

            foreach ($ids as $id)
            {
                if ($user['id'] == $id)
                {
                    throw new UserException('Il n\'est pas possible de supprimer son propre compte.');
                }







|



















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



















|

|







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
291
292















































































293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
            {
                throw new UserException('Le numéro n\'est pas modifiable pour ce membre car des contenus sont liés à ce numéro de membre (wiki, compta, etc.).');
            }
        }

        if (!empty($data['passe']) && trim($data['passe']))
        {
            $data['passe'] = self::hashPassword($data['passe']);
        }
        else
        {
            unset($data['passe']);
        }

        if (isset($data['id_categorie']) && empty($data['id_categorie']))
        {
            $data['id_categorie'] = Config::getInstance()->get('categorie_membres');
        }

        if (empty($data))
        {
            return true;
        }

        return $db->simpleUpdate('membres', $data, 'id = '.(int)$id);
    }
















































































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

        return $db->simpleQuerySingle('SELECT *,
            '.$config->get('champ_identite').' AS identite,
            strftime(\'%s\', date_inscription) AS date_inscription,
            strftime(\'%s\', date_connexion) AS date_connexion
            FROM membres WHERE id = ? LIMIT 1;', true, (int)$id);
    }

    public function delete($ids)
    {
        if (!is_array($ids))
        {
            $ids = [(int)$ids];
        }

        if (Membres\Session::isLogged())
        {
            $user = Membres\Session::get();

            foreach ($ids as $id)
            {
                if ($user['id'] == $id)
                {
                    throw new UserException('Il n\'est pas possible de supprimer son propre compte.');
                }
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
    {
        $db = DB::getInstance();
        $config = Config::getInstance();

        return $db->simpleQuerySingle('SELECT '.$config->get('champ_identite').' FROM membres WHERE id = ? LIMIT 1;', false, (int)$id);
    }

    public function getDroits($id)
    {
        $db = DB::getInstance();
        $droits = $db->simpleQuerySingle('SELECT * FROM membres_categories WHERE id = ?;', true, (int)$id);

        foreach ($droits as $key=>$value)
        {
            unset($droits[$key]);
            $key = str_replace('droit_', '', $key, $found);

            if ($found)
            {
                $droits[$key] = (int) $value;
            }
        }

        return $droits;
    }

    public function search($field, $query)
    {
        $db = DB::getInstance();
        $config = Config::getInstance();

        $champs = $config->get('champs_membres');








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







329
330
331
332
333
334
335



















336
337
338
339
340
341
342
    {
        $db = DB::getInstance();
        $config = Config::getInstance();

        return $db->simpleQuerySingle('SELECT '.$config->get('champ_identite').' FROM membres WHERE id = ? LIMIT 1;', false, (int)$id);
    }




















    public function search($field, $query)
    {
        $db = DB::getInstance();
        $config = Config::getInstance();

        $champs = $config->get('champs_membres');

Added src/include/lib/Garradin/Membres/Session.php version [bd1c665f48].



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
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
521
522
523
524
525
526
527
528
529
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
<?php

namespace Garradin\Membres;

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

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]))
		{
			return false;
		}

		return session_start(self::getSessionOptions());
	}

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

	static public function get()
	{
		try {
			return new Session;
		}
		catch (\LogicException $e) {
			throw $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();

			$_SESSION = [];

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

			return self::REQUIRE_OTP;
		}
		else
		{
			return self::create((int) $membre->id, $permanent);
		}
	}

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

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

		$token = hash(self::HASH_ALGO, $token . $user->passe);
		$cookie = $selector . '|' . $token;

		setcookie(self::PERMANENT_COOKIE_NAME, $cookie, $expire->getTimestamp(),
			$url['path'], $url['host'], (\Garradin\PREFER_HTTPS >= 2), true);

		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 (!Security_OTP::TOTP($user->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('fr.pool.ntp.org');

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

		$session = new Session($user->id);
		$session->updateLoginDate();
		return $session;
	}

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

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

		$membre = $db->first('SELECT id, email FROM membres WHERE '.$champ_id.' = ? LIMIT 1;', trim($id));

		if (!$membre || trim($membre['email']) == '')
		{
			return false;
		}

		self::start(true);
		$hash = sha1($membre['email'] . $membre['id'] . 'recover' . ROOT . time());
		$_SESSION['recover_password'] = [
			'id' => (int) $membre['id'],
			'email' => $membre['email'],
			'hash' => $hash
		];

		$message = "Bonjour,\n\nVous avez oublié votre mot de passe ? Pas de panique !\n\n";
		$message.= "Il vous suffit de cliquer sur le lien ci-dessous pour recevoir un nouveau mot de passe.\n\n";
		$message.= WWW_URL . 'admin/password.php?c=' . substr($hash, -10);
		$message.= "\n\nSi vous n'avez pas demandé à recevoir ce message, ignorez-le, votre mot de passe restera inchangé.";

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

	static public function recoverPasswordConfirm($hash)
	{
		self::start();

		if (empty($_SESSION['recover_password']['hash']))
			return false;

		if (substr($_SESSION['recover_password']['hash'], -10) != $hash)
			return false;

		$config = Config::getInstance();
		$db = DB::getInstance();

		$password = Utils::suggestPassword();

		$dest = $_SESSION['recover_password']['email'];
		$id = (int)$_SESSION['recover_password']['id'];

		$message = "Bonjour,\n\nVous avez demandé un nouveau mot de passe pour votre compte.\n\n";
		$message.= "Votre adresse email : ".$dest."\n";
		$message.= "Votre nouveau mot de passe : ".$password."\n\n";
		$message.= "Si vous n'avez pas demandé à recevoir ce message, merci de nous le signaler.";

		$password = $this->_hashPassword($password);

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

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

	public function __construct()
	{
		if (defined('\Garradin\LOCAL_LOGIN') && is_int(\Garradin\LOCAL_LOGIN) && \Garradin\LOCAL_LOGIN > 0)
		{
			$this->id = \Garradin\LOCAL_LOGIN;

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

		$this->autoLogin();

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

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

	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],
			'token'    => $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   http://jaspan.com/improved_persistent_login_cookie_best_practice
	 * @return boolean
	 */
	protected function autoLogin()
	{
		$cookie = $this->getPermanentCookie();

		if (!$cookie)
		{
			return false;
		}

		$db = DB::getInstance();
		$row = $db->first('SELECT ms.token, ms.id_membre, 
			strftime("%s", ms.expire) AS expire, membres.passe
			INNER JOIN membres ON membres.id = ms.id_membre
			FROM membres_sessions AS ms WHERE ms.selecteur = ?;',
			$cookie->selector);

		if ($row->expire < time())
		{
			return $this->logout();
		}

		// 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, $row->token . $row->passe);

		// Vérification du token
		if (!Security::hash_equals($cookie->token, $row->token))
		{
			// 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
			$db->delete('membres_sessions', 'id_membre = :id', ['id' => (int) $row->id_membre]);

			return $this->logout();
		}

		// Re-générons un nouveau token et mettons à jour le cookie
		$token = hash(self::HASH_ALGO, Security::random_bytes(10));
		$expire = (new DateTime)->modify('+3 months');

		$db->update('membres_sessions', [
			'token'     => $token,
			'expire'    => $expire,
		], 'selecteur = :selecteur AND id_membre = :id_membre', [
			'selecteur' => $cookie->selector,
			'id_membre' => $row->id_membre,
		]);

		$new_cookie = $cookie->selector . '|' . $token;

		setcookie(self::PERMANENT_COOKIE_NAME, $new_cookie, $expire->getTimestamp(),
			$url['path'], $url['host'], (\Garradin\PREFER_HTTPS >= 2), true);


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

		$this->populateUserData();

		return true;
	}

	public function logout()
	{
		$url = parse_url(\Garradin\WWW_URL);

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

			setcookie(self::PERMANENT_COOKIE_NAME, null, -1, $url['path'], $url['host'], false, true);
			unset($_COOKIE[self::PERMANENT_COOKIE_NAME]);
		}

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

		setcookie(self::SESSION_COOKIE_NAME, null, -1, $url['path'], $url['host'], false, true);

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


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

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

		$this->user->droits = new \stdClass;

		// Récupérer les droits
		$droits = $db->first('SELECT * FROM membres_categories WHERE id = ?;', (int)$this->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)
			{
				$this->user->droits->$key = (int) $value;
			}
		}

		self::start(true);
		$_SESSION['user'] =& $this->user;

		return $this->user;
	}

	public function editUser($data)
	{
		return (new \Garradin\Membres)->edit($this->id, $data, false);
	}

	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 canUserAccess($category, $permission)
	{
		if (!$this->user)
		{
			return false;
		}

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

	public function getNewOTPSecret()
	{
		$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;
	}

	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 updateSessionData($membre = null, $droits = null)
	{
		if (is_null($membre))
		{
			$membre = $this->get($_SESSION['logged_user']['id']);
		}
		elseif (is_int($membre))
		{
			$membre = $this->get($membre);
		}

		if (is_null($droits))
		{
			$droits = $this->getDroits($membre['id_categorie']);
		}

		$membre['droits'] = $droits;
		$_SESSION['logged_user'] = $membre;
		return true;
	}

	public function sendMessage($dest, $sujet, $message, $copie = false)
	{
		$from = $this->getLoggedUser();
		$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 = [])
	{
		$user = $this->getLoggedUser();

		if (!$user)
		{
			throw new \LogicException('Utilisateur non connecté.');
		}

		$allowed_fields = ['passe', 'clef_pgp', 'secret_otp'];

		foreach ($data as $key=>$value)
		{
			if (!in_array($key, $allowed_fields))
			{
				throw new \RuntimeException(sprintf('Le champ %s n\'est pas autorisé dans cette méthode.', $key));
			}
		}

		if (isset($data['passe']) && trim($data['passe']) !== '')
		{
			if (strlen($data['passe']) < 5)
			{
				throw new UserException('Le mot de passe doit faire au moins 5 caractères.');
			}

			$data['passe'] = $this->_hashPassword($data['passe']);
		}
		else
		{
			unset($data['passe']);
		}

		if (isset($data['clef_pgp']))
		{
			$data['clef_pgp'] = trim($data['clef_pgp']);

			if (!$this->getPGPFingerprint($data['clef_pgp']))
			{
				throw new UserException('Clé PGP invalide : impossible d\'extraire l\'empreinte.');
			}
		}

		DB::getInstance()->simpleUpdate('membres', $data, 'id = '.(int)$user['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;
	}

}

Modified src/www/admin/_inc.php from [846ebd1438] to [48fbe337e7].

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
<?php

namespace Garradin;



require_once __DIR__ . '/../../include/init.php';

// Redirection automatique en HTTPS si nécessaire
if (PREFER_HTTPS !== true && PREFER_HTTPS >= 2 && empty($_SERVER['HTTPS']) && empty($_POST))
{
    utils::redirect(str_replace('http://', 'https://', utils::getSelfURL()));
    exit;
}

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

$membres = new Membres;

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

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


    $tpl->assign('user', $membres->getLoggedUser());
    $user = $membres->getLoggedUser();

    $tpl->assign('current', '');
    $tpl->assign('plugins_menu', Plugin::listMenu());

    if ($user['droits']['membres'] >= Membres::DROIT_ACCES)
    {
        $tpl->assign('nb_membres', $membres->countAllButHidden());
    }
}



>
>













|



|

|











>
>
|
<




|

|


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
<?php

namespace Garradin;

use Garradin\Membres\Session;

require_once __DIR__ . '/../../include/init.php';

// Redirection automatique en HTTPS si nécessaire
if (PREFER_HTTPS !== true && PREFER_HTTPS >= 2 && empty($_SERVER['HTTPS']) && empty($_POST))
{
    utils::redirect(str_replace('http://', 'https://', utils::getSelfURL()));
    exit;
}

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

$session = Session::get();

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

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

    $user = $session->getUser();
    $tpl->assign('user', $user);


    $tpl->assign('current', '');
    $tpl->assign('plugins_menu', Plugin::listMenu());

    if ($session->canUserAccess('membres', Membres::DROIT_ACCES))
    {
        $tpl->assign('nb_membres', (new Membres)->countAllButHidden());
    }
}

Modified src/www/admin/login.php from [aecfcafaf0] to [c09efdc59d].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
namespace Garradin;

const LOGIN_PROCESS = true;

require_once __DIR__ . '/_inc.php';

if ($membres->isLogged())
{
    Utils::redirect('/admin/');
}

// Relance session_start et renvoie une image de 1px transparente
if (isset($_GET['keepSessionAlive']))
{
    $membres->keepSessionAlive();

    header('Cache-Control: no-cache, must-revalidate');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');

    header('Content-Type: image/gif');
    echo base64_decode("R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==");








|







|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
namespace Garradin;

const LOGIN_PROCESS = true;

require_once __DIR__ . '/_inc.php';

if ($session)
{
    Utils::redirect('/admin/');
}

// Relance session_start et renvoie une image de 1px transparente
if (isset($_GET['keepSessionAlive']))
{
    Session::refresh();

    header('Cache-Control: no-cache, must-revalidate');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');

    header('Content-Type: image/gif');
    echo base64_decode("R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==");

31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
    if (!Utils::CSRF_check('login'))
    {
        $error = 'OTHER';
    }
    else
    {
        if (Utils::post('id') && Utils::post('passe')
            && $membres->login(Utils::post('id'), Utils::post('passe')))
        {
            Utils::redirect('/admin/');
        }

        $error = 'LOGIN';
    }
}







|







31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
    if (!Utils::CSRF_check('login'))
    {
        $error = 'OTHER';
    }
    else
    {
        if (Utils::post('id') && Utils::post('passe')
            && Membres\Session::login(Utils::post('id'), Utils::post('passe')))
        {
            Utils::redirect('/admin/');
        }

        $error = 'LOGIN';
    }
}