User.php 15.9 KB
Newer Older
1
2
3
<?php

/**
4
 * User
5
 *
6
 * web-DPO : Outil de gestion de vos traitements dans le cadre de la
7
 * réglementation relative à la protection des données personnelles (RGPD)
8
 *
9
10
 * Copyright (c) Libriciel SCOP (https://www.libriciel.fr/)
 *
11
12
 * Licensed under the GNU Affero General Public License version 3 License - AGPL v3
 * For full copyright and license information, please see the "LICENSE" file.
13
 * Redistributions of files must retain the above copyright notice.
14
 *
15
 * @copyright   Copyright (c) Libriciel SCOP (https://www.libriciel.fr/)
16
 * @link        https://www.libriciel.fr/web-dpo/
17
 * @since       web-DPO v1.0.0
18
 * @license     [GNU Affero General Public License version 3](http://www.gnu.org/licenses/agpl-3.0.html) - AGPL v3
19
 * @version     v1.0.0
20
 * @package     App.Model
21
22
23
 */

App::uses('AppModel', 'Model');
24
App::uses('LinkedOrganisationInterface', 'Model/Interface');
25
26
27
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');

use Libriciel\Utility\Password\PasswordStrengthMeterAnssi;
28
use Libriciel\Utility\Password\PasswordGeneratorAnssi;
29

30
class User extends AppModel implements LinkedOrganisationInterface {
31
32

    public $name = 'User';
33

34
    public $validationDomain = 'validation';
35

36
37
38
39
40
41
42
43
44
45
46
47
48
49
    public $actsAs = [
        'Database.DatabaseFormattable' => [
            'Database.DatabaseDefaultFormatter' => [
                'formatTrim' => [
                    'NOT' => ['binary']
                ],
                'formatNull' => true,
                'formatNumeric' => [
                    'float',
                    'integer'
                ],
                'formatSuffix'  => '/_id$/',
                'formatStripNotAlnum' => '/^(telephonefixe|telephoneportable)$/'
            ]
50
51
        ],
        'LettercaseFormattable' => [
52
53
            'upper_noaccents' => ['nom'],
            'title' => ['prenom']
54
55
56
57
58
59
60
61
62
        ]
    ];

    /**
     * Champs virtuels du modèle
     *
     * @var array
     */
    public $virtualFields = [
63
        'is_dpo' => '( EXISTS( SELECT * FROM "organisations" WHERE "organisations"."dpo" = "User"."id" ) )',
64
65
66
67
        'nom_complet' => '( COALESCE( "User"."civilite", \'\' ) || \' \' || COALESCE( "User"."prenom", \'\' ) || \' \' || COALESCE( "User"."nom", \'\' ) )',
        'nom_complet_court' => '( COALESCE( "User"."prenom", \'\' ) || \' \' || COALESCE( "User"."nom", \'\' ) )'
    ];

68
    /**
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
     * validate associations
     *
     * @var array
     *
     * @access public
     * @created 24/10/2015
     * @version V0.9.0
     */
    public $validate = [
        'password' => [
            'checkPasswordStrength' => [
                'allowEmpty' => true,
                'required' => false,
                'rule' => ['checkPasswordStrength'],
                'message' => false
            ]
        ],
        'passwd' => [
            [
                'rule' => 'notBlank',
89
                'message' => 'validation.confirmerPassword'
90
91
92
93
94
95
            ],
            [
                'rule' => [
                    'comparePassword',
                    'password'
                ],
96
                'message' => 'validation.lesMotsPasseNonIdentiques'
97
98
99
            ]
        ],
        'new_password' => [
100
101
102
103
            [
                'rule' => 'notBlank',
                'message' => 'validation.confirmerPassword'
            ],
104
105
106
107
108
109
110
111
            'checkPasswordStrength' => [
                'allowEmpty' => true,
                'required' => false,
                'rule' => ['checkPasswordStrength'],
                'message' => false
            ]
        ],
        'new_passwd' => [
112
113
114
115
            [
                'rule' => 'notBlank',
                'message' => 'validation.confirmerPassword'
            ],
116
117
118
119
120
            [
                'rule' => [
                    'comparePassword',
                    'new_password'
                ],
121
                'message' => 'validation.lesMotsPasseNonIdentiques'
122
123
            ]
        ],
124
125
126
127
128
129
        'old_password' => [
            [
                'rule' => 'notBlank',
                'message' => 'validation.confirmerPassword'
            ]
        ],
130
131
132
        'nom' => [
            [
                'rule' => ['custom', REGEXP_ALPHA_FR],
133
                'message' => 'validation.seulementLettresAcceptees'
134
135
136
137
138
            ]
        ],
        'prenom' => [
            [
                'rule' => ['custom', REGEXP_ALPHA_FR],
139
                'message' => 'validation.seulementLettresAcceptees'
140
141
142
143
144
            ]
        ],
        'email' => [
            [
                'rule' => ['custom', REGEXP_EMAIL_FR],
145
                'message' => 'validation.adresseMailNonValide'
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
            ]
        ]
    ];

    /**
     * hasAndBelongsToMany associations
     *
     * @var array
     *
     * @access public
     * @created 18/12/2015
     * @version V0.9.0
     */
    public $hasAndBelongsToMany = [
        'Organisation' => [
            'className' => 'Organisation',
            'joinTable' => 'organisations_users',
            'foreignKey' => 'user_id',
            'associationForeignKey' => 'organisation_id',
            'unique' => true,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'finderQuery' => '',
            'with' => 'OrganisationUser'
        ]
    ];

    /**
     * hasMany associations
     *
     * @var array
     *
     * @access public
     * @created 26/03/2015
     * @version V0.9.0
     */
    public $hasMany = [
        'Fiche' => [
            'className' => 'Fiche',
            'foreignKey' => 'user_id',
            'dependent' => true,
        ],
        'EtatFiche' => [
            'className' => 'EtatFiche',
            'foreignKey' => 'user_id',
            'dependent' => true,
        ],
        'Previous' => [
            'className' => 'EtatFiche',
            'foreignKey' => 'previous_user_id'
        ],
        'Commentaire' => [
            'className' => 'Commentaire',
            'foreignKey' => 'user_id'
        ],
        'Destin' => [
            'className' => 'Commentaire',
            'foreignKey' => 'destinataire_id'
        ],
208
        'Dpo' => [
209
            'className' => 'Organisation',
210
            'foreignKey' => 'dpo'
211
212
213
214
        ],
        'Notification' => [
            'className' => 'Notification',
            'foreignKey' => 'user_id'
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
        ],
        'Role' => [
            'className' => 'Role',
            'foreignKey' => 'id'
        ],
        'OrganisationUserRole' => [
            'className' => 'OrganisationUserRole',
            'foreignKey' => 'id'
        ],
        'RoleDroit' => [
            'className' => 'RoleDroit',
            'foreignKey' => 'id'
        ],
        'Droit' => [
            'className' => 'Droit',
            'foreignKey' => 'id'
        ],
232
233
234
235
        'Organisationdpo' => [
            'className' => 'Organisation',
            'foreignKey' => 'dpo'
        ]
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
    ];

    /**
     * hasOne associations
     *
     * @var array
     *
     * @access public
     * @created 26/06/2015
     * @version V0.9.0
     */
    public $hasOne = [
        'Admin' => [
            'className' => 'Admin',
            'foreignKey' => 'user_id',
            'dependent' => true
        ]
    ];

    /**
     * @param type $options
     * @return boolean
     *
     * @access public
     * @created 29/04/2015
     * @version V0.9.0
     */
    public function beforeSave($options = []) {
        if (false === isset($this->data[$this->alias]['password']) && true === isset($this->data[$this->alias]['new_password'])) {
            $this->data[$this->alias]['password'] = $this->data[$this->alias]['new_password'];
        }
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
        if (isset($this->data[$this->alias]['password'])) {
            $passwordHasher = new SimplePasswordHasher();

            $password = $this->data[$this->alias]['password'];
            $this->data[$this->alias]['password'] = $passwordHasher->hash($password);
            $this->data[$this->alias]['password_force'] = PasswordStrengthMeterAnssi::strength($password);
        }
        return true;
    }

    /**
     * @param type $field
     * @param type|null $compareField
     * @return boolean
     *
     * @access public
     * @created 29/04/2015
     * @version V0.9.0
     */
    function comparePassword($field = [], $compareField = null) {
        foreach ($field as $key => $value) {
            $v1 = $value;
            $v2 = $this->data[$this->name][$compareField];

            if ($v1 != $v2) {
                return false;
            } else {
                continue;
            }
        }
        return true;
    }

    /**
     * Retourne la force de mot de passe minimale pour un utilisateur donné en
     * fonction de ce qui est configuré pour ses entités.
304
     *
305
306
     * Si on ne trouve pas d'entité (ex. superadmin au début), on retourne la
     * valeur maximale.
307
     *
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
     * @param int $id L'id de l'utilisateur
     * @return int
     */
    public function getMinUserPasswordStrength($id) {
        $query = [
            'fields' => ['MAX(Organisation.force) AS "Organisation__force"'],
            'joins' => [
                $this->join('OrganisationUser', ['type' => 'INNER']),
                $this->OrganisationUser->join('Organisation', ['type' => 'INNER'])
            ],
            'conditions' => [
                'User.id' => $id
            ]
        ];
        $result = (array)$this->find('first', $query);
        $force = Hash::get($result, 'Organisation.force');

        return null === $force ? 5 : $force;
    }
327

328
329
330
    /**
     * Retourne la force de mot de passe minimale pour un utilisateur donné en
     * fonction de ce qui est configuré pour ses entités.
331
     *
332
333
     * Si on ne trouve pas d'entité (ex. superadmin au début), on retourne la
     * valeur maximale.
334
     *
335
336
337
338
339
     * @param int $id L'id de l'utilisateur
     * @return int
     */
    public function getMaxForceOrganisationStrength(array $id = null) {
        $force = null;
340

341
342
343
344
345
346
347
348
349
350
351
        if ($id != null) {
            $result = $this->Organisation->find('first',[
                'conditions' => [
                    'id' => $id
                ],
                'fields' => [
                    'MAX(Organisation.force) AS "Organisation__force"'
                ],
            ]);
            $force = Hash::get($result, 'Organisation.force');
        }
352

353
354
355
356
357
358
359
360
361
362
363
364
365
366
        return null === $force ? 5 : $force;
    }

    // @fixme: supprimer les autres règles de validation sur 5 caractères
    public function checkPasswordStrength(array $check) {
        $organisations_ids = Hash::get($this->data, 'User.organisation_id');

        if (is_numeric($this->id) && true === empty($organisations_ids)){
            $force = $this->getMinUserPasswordStrength($this->id);
        } else {
            $organisations = Hash::get($this->data, 'User.organisation_id');
            if (empty($organisations)){
                $organisations = null;
            }
367

368
369
            $force = $this->getMaxForceOrganisationStrength($organisations);
        }
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
        $success = true;
        foreach($check as $field => $value) {
            if (PasswordStrengthMeterAnssi::strength($value) < $force) {
                $success = false;
                $message = 'Vous devez renseigner un mot de passe de force %d au minimum';
                $this->invalidate($field, sprintf($message, $force));
            }
        }
        return $success;
    }

    /**
     * Suppression des erreurs de validation non traduites (Validate::checkPasswordStrength)
     * pour les champs password et new_password lorsqu'il existe au moins un autre
     * message d'erreur.
     */
    public function afterValidate() {
        foreach($this->validationErrors as $field => $errors) {
            if(true === in_array($field, ['password', 'new_password'])) {
                foreach($errors as $idx => $error) {
                    if('Validate::checkPasswordStrength' === $error && $idx > 0) {
                        unset($this->validationErrors[$field][$idx]);
                    }
                }
            }
        }
        parent::afterValidate();
    }
399

400
401
    public function saveLdapManagerLdap($data) {
        $this->Role->recursive = -1;
402
403
404
405
406
407
408

        if (!$this->Role->exists($data['User']['role_id']) ||
            !isset($data['User']['username']) ||
            !isset($data['User']['prenom']) ||
            !isset($data['User']['nom']) ||
            !isset($data['User']['email'])
        ) {
409
410
            return false;
        }
411
412
413
414
415

        if (!isset($data['User']['ldap'])) {
            $data['User']['ldap'] = true;
        }

416
417
418
        if (!isset($data['User']['civilite'])) {
            $data['User']['civilite'] = 'M.';
        }
419

420
421
422
        if (!isset($data['User']['password'])) {
            $data['User']['password'] = PasswordGeneratorAnssi::generate();
        }
423

424
425
        $role_organisationId = $this->Role->find('first', [
            'conditions' => [
426
                'id' => $data['User']['role_id']
427
428
429
430
431
            ],
            'fields' => [
                'organisation_id'
            ]
        ]);
432

433
434
435
        $userLdap = parent::save($data, [
            'validate' => true,
            'fieldList' => [
436
                'ldap',
437
438
439
440
441
442
443
444
                'username',
                'nom',
                'prenom',
                'email',
                'civilite',
                'password'
            ]
        ]);
445

446
447
448
449
450
451
452
        if (is_array($userLdap)) {
            $this->OrganisationUser->create([
                'OrganisationUser' => [
                    'user_id' => $userLdap['User']['id'],
                    'organisation_id' => $role_organisationId['Role']['organisation_id'],
                ]
            ]);
453
454
            $this->OrganisationUser->save(null, ['atomic' => false]);

455
456
457
458
459
460
            $this->OrganisationUserRole->create([
                'OrganisationUserRole' => [
                    'organisation_user_id' => $this->OrganisationUser->id,
                    'role_id' => $userLdap['User']['role_id'],
                ]
            ]);
461
462
            $this->OrganisationUserRole->save(null, ['atomic' => false]);

463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
            // Droits
            $query = [
                'conditions' => [
                    'RoleDroit.role_id' => $data['User']['role_id']
                ],
                'fields' => [
                    'liste_droit_id'
                ]
            ];
            $droits = $this->RoleDroit->find('all', $query);

            foreach($droits as $droit) {
                $this->Droit->create([
                    'organisation_user_id' => $this->OrganisationUser->id,
                    'liste_droit_id' => $droit['RoleDroit']['liste_droit_id']
                ]);
479
                $this->Droit->save(null, ['atomic' => false]);
480
            }
481

482
483
484
485
486
            return $userLdap;
        } else {
            return false;
        }
    }
487

488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
    /**
     * Retourne les id des organisations liées à l'utilisateur.
     *
     * @param int $id
     * @return array
     */
    public function getLinkedOrganisationsIds($id) {
        $query = [
            'fields' => ['organisation_id'],
            'conditions' => ['user_id' => $id],
        ];
        return Hash::extract(
            $this->OrganisationUser->find('all', $query),
            '{n}.OrganisationUser.organisation_id'
        );
    }

505
506
507
508
509
    public function vfNomComplet($alias = null, $fieldName = 'nom_complet') {
        $alias = $alias === null ? $this->alias : $alias;
        $sql = str_replace("\"{$this->name}\"", "\"{$alias}\"", $this->virtualFields['nom_complet']);
        return "{$sql} AS \"{$alias}__{$fieldName}\"";
    }
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529

    /**
     * Retourne une condition permettant de limiter aux enregistrements liés à une ou plusieurs entités.
     *
     * @param array|int $organisation_id
     * @return string
     */
    public function getConditionOrganisation($organisation_id) {
        $query = [
            'alias' => 'organisations_users',
            'fields' => [
                'organisations_users.user_id'
            ],
            'conditions' => [
                'organisations_users.organisation_id' => $organisation_id
            ]
        ];
        $sql = $this->OrganisationUser->sql($query);
        return "{$this->alias}.{$this->primaryKey} IN ( {$sql} )";
    }
530
}