summaryrefslogtreecommitdiffstats
path: root/src/Psecio/Gatekeeper/UserModel.php
blob: 1481732c84441ded3a80ff7533b3cbfca80a9810 (plain)
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
<?php

namespace Psecio\Gatekeeper;

/**
 * User class
 *
 * @property string $username
 * @property string $password
 * @property string $email
 * @property string $firstName
 * @property string $lastName
 * @property string $created
 * @property string $updated
 * @property string $status
 * @property string $id
 * @property string $resetCode
 * @property string $resetCodeTimeout
 * @property string $lastLogin
 */
class UserModel extends \Psecio\Gatekeeper\Model\Mysql
{
    const STATUS_ACTIVE = 'active';
    const STATUS_INACTIVE = 'inactive';

    /**
     * Database table name
     * @var string
     */
    protected $tableName = 'users';

    /**
     * Model properties
     * @var array
     */
    protected $properties = array(
        'username' => array(
            'description' => 'Username',
            'column' => 'username',
            'type' => 'varchar'
        ),
        'password' => array(
            'description' => 'Password',
            'column' => 'password',
            'type' => 'varchar'
        ),
        'email' => array(
            'description' => 'Email Address',
            'column' => 'email',
            'type' => 'varchar'
        ),
        'firstName' => array(
            'description' => 'First Name',
            'column' => 'first_name',
            'type' => 'varchar'
        ),
        'lastName' => array(
            'description' => 'Last Name',
            'column' => 'last_name',
            'type' => 'varchar'
        ),
        'created' => array(
            'description' => 'Date Created',
            'column' => 'created',
            'type' => 'datetime'
        ),
        'updated' => array(
            'description' => 'Date Updated',
            'column' => 'updated',
            'type' => 'datetime'
        ),
        'status' => array(
            'description' => 'Status',
            'column' => 'status',
            'type' => 'varchar'
        ),
        'id' => array(
            'description' => 'User ID',
            'column' => 'id',
            'type' => 'integer'
        ),
        'resetCode' => array(
            'description' => 'Password Reset Code',
            'column' => 'password_reset_code',
            'type' => 'varchar'
        ),
        'resetCodeTimeout' => array(
            'description' => 'Password Reset Code Timeout',
            'column' => 'password_reset_code_timeout',
            'type' => 'datetime'
        ),
        'lastLogin' => array(
            'description' => 'Date and Time of Last Login',
            'column' => 'last_login',
            'type' => 'datetime'
        ),
        'groups' => array(
            'description' => 'Groups the User Belongs to',
            'type' => 'relation',
            'relation' => array(
                'model' => '\\Psecio\\Gatekeeper\\UserGroupCollection',
                'method' => 'findByUserId',
                'local' => 'id'
            )
        ),
        'permissions' => array(
            'description' => 'Permissions the user has',
            'type' => 'relation',
            'relation' => array(
                'model' => '\\Psecio\\Gatekeeper\\UserPermissionCollection',
                'method' => 'findByUserId',
                'local' => 'id'
            )
        ),
        'loginAttempts' => array(
            'description' => 'Number of login attempts by user',
            'type' => 'relation',
            'relation' => array(
                'model' => '\\Psecio\\Gatekeeper\\UserModel',
                'method' => 'findAttemptsByUser',
                'local' => 'id',
                'return' => 'value'
            )
        ),
        'throttle' => array(
            'description' => 'Full throttle information for a user',
            'type' => 'relation',
            'relation' => array(
                'model' => '\\Psecio\\Gatekeeper\\ThrottleModel',
                'method' => 'findByUserId',
                'local' => 'id'
            )
        ),
        'securityQuestions' => array(
            'description' => 'Security questions for the user',
            'type' => 'relation',
            'relation' => array(
                'model' => '\\Psecio\\Gatekeeper\\SecurityQuestionCollection',
                'method' => 'findByUserId',
                'local' => 'id'
            )
        ),
        'authTokens' => array(
            'description' => 'Current auth (remember me) tokens for the user',
            'type' => 'relation',
            'relation' => array(
                'model' => '\\Psecio\\Gatekeeper\\AuthTokenCollection',
                'method' => 'findTokensByUserId',
                'local' => 'id'
            )
        )
    );

    /**
     * Check to see if the password needs to be rehashed
     *
     * @param string $value Password string
     * @return string Updated string value
     */
    public function prePassword($value)
    {
        if (password_needs_rehash($value, PASSWORD_DEFAULT) === true) {
            $value = password_hash($value, PASSWORD_DEFAULT);
        }
        return $value;
    }

    /**
     * Find the user by username
     *     If found, user is automatically loaded into model instance
     *
     * @param string $username Username
     * @return boolean Success/fail of find operation
     */
    public function findByUsername($username)
    {
        return $this->getDb()->find(
            $this, array('username' => $username)
        );
    }

    /**
     * Find a user by their given ID
     *
     * @param integer $userId User ID
     * @return boolean Success/fail of find operation
     */
    public function findByUserId($userId)
    {
        return $this->getDb()->find(
            $this, array('id' => $userId)
        );
    }

    /**
     * Attach a permission to a user account
     *
     * @param integer|PermissionModel $perm Permission ID or model isntance
     * @param integer $expire Expiration time of the permission relationship
     */
    public function addPermission($perm, $expire = null)
    {
        if ($perm instanceof PermissionModel) {
            $perm = $perm->id;
        }
        $data = [
            'user_id' => $this->id,
            'permission_id' => $perm
        ];
        if ($expire !== null && is_int($expire)) {
            $data['expire'] = $expire;
        }
        $perm = new UserPermissionModel($this->getDb(), $data);
        return $this->getDb()->save($perm);
    }

    /**
     * Revoke a user permission
     *
     * @param integer|PermissionModel $perm Permission ID or model instance
     * @return boolean Success/fail of delete
     */
    public function revokePermission($perm)
    {
        if ($perm instanceof PermissionModel) {
            $perm = $perm->id;
        }
        $perm = new UserPermissionModel($this->getDb(), array(
            'user_id' => $this->id,
            'permission_id' => $perm
        ));
        return $this->getDb()->delete($perm);
    }

    /**
     * Add a group to the user
     *
     * @param integer|GroupModel $group Add the user to a group
     * @return boolean Success/fail of add
     */
    public function addGroup($group, $expire = null)
    {
        if ($group instanceof GroupModel) {
            $group = $group->id;
        }
        $data = [
            'group_id' => $group,
            'user_id' => $this->id
        ];
        if ($expire !== null && is_int($expire)) {
            $data['expire'] = $expire;
        }
        $group = new UserGroupModel($this->getDb(), $data);
        return $this->getDb()->save($group);
    }

    /**
     * Revoke access to a group for a user
     *
     * @param integer|GroupModel $group ID or model of group to remove
     * @return boolean
     */
    public function revokeGroup($group)
    {
        if ($group instanceof GroupModel) {
            $group = $group->id;
        }
        $group = new UserGroupModel($this->getDb(), array(
            'group_id' => $group,
            'user_id' => $this->id
        ));
        return $this->getDb()->delete($group);
    }

    /**
     * Activate the user (status)
     *
     * @return boolean Success/fail of activation
     */
    public function activate()
    {
        // Verify we have a user
        if ($this->id === null) {
            return false;
        }
        $this->status = self::STATUS_ACTIVE;
        return $this->getDb()->save($this);
    }

    /**
     * Deactivate the user
     *
     * @return boolean Success/fail of deactivation
     */
    public function deactivate()
    {
        // Verify we have a user
        if ($this->id === null) {
            return false;
        }
        $this->status = self::STATUS_INACTIVE;
        return $this->getDb()->save($this);
    }

    /**
     * Generate and return the code for a password reset
     *     Also updates the user record
     *
     * @param integer $length Length of returned string
     * @return string Geenrated code
     */
    public function getResetPasswordCode($length = 80)
    {
        // Verify we have a user
        if ($this->id === null) {
            return false;
        }
        // Generate a random-ish code and save it to the user record
        $code = substr(bin2hex(openssl_random_pseudo_bytes($length)), 0, $length);
        $this->resetCode = $code;
        $this->resetCodeTimeout = date('Y-m-d H:i:s', strtotime('+1 hour'));
        $this->getDb()->save($this);

        return $code;
    }

    /**
     * Check the given code against he value in the database
     *
     * @param string $resetCode Reset code to verify
     * @return boolean Pass/fail of verification
     */
    public function checkResetPasswordCode($resetCode)
    {
        // Verify we have a user
        if ($this->id === null) {
            return false;
        }
        if ($this->resetCode === null) {
            throw new Exception\PasswordResetInvalid('No reset code defined for user '.$this->username);
        }

        // Verify the timeout
        $timeout = new \DateTime($this->resetCodeTimeout);
        if ($timeout <= new \DateTime()) {
            $this->clearPasswordResetCode();
            throw new Exception\PasswordResetTimeout('Reset code has timeed out!');
        }

        // We made it this far, compare the hashes
        $result = (Gatekeeper::hash_equals($this->resetCode, $resetCode));
        if ($result === true) {
            $this->clearPasswordResetCode();
        }
        return $result;
    }

    /**
     * Clear all data from the passsword reset code handling
     * @return [type] [description]
     */
    public function clearPasswordResetCode()
    {
        // Verify we have a user
        if ($this->id === null) {
            return false;
        }
        $this->resetCode = null;
        $this->resetCodeTimeout = null;
        return $this->getDb()->save($this);
    }

    /**
     * Check to see if the user is in the group
     *
     * @param integer $groupId Group ID or name
     * @return boolean Found/not found in the group
     */
    public function inGroup($groupId)
    {
        $find = ['user_id' => $this->id];
        if (!is_numeric($groupId)) {
            $g = Gatekeeper::findGroupByName($groupId);
            $groupId = $g->id;
        }
        $find['group_id'] = $groupId;

        $userGroup = new UserGroupModel($this->getDb());
        $userGroup = $this->getDb()->find($userGroup, $find);
        if ($userGroup->id === null) {
            return false;
        }
        return ($userGroup->id !== null && $userGroup->groupId == $groupId) ? true : false;
    }

    /**
     * Check to see if a user has a permission
     *
     * @param integer $permId Permission ID or name
     * @return boolean Found/not found in user permission set
     */
    public function hasPermission($permId)
    {
        $find = ['user_id' => $this->id];
        if (!is_numeric($permId)) {
            $p = Gatekeeper::findPermissionByName($permId);
            $permId = $p->id;
        }
        $find['permission_id'] = $permId;

        $perm = new UserPermissionModel($this->getDb());
        $perm = $this->getDb()->find($perm, $find);
        return ($perm->id !== null && $perm->id === $permId) ? true : false;
    }

    /**
     * Check to see if a user is banned
     *
     * @return boolean User is/is not banned
     */
    public function isBanned()
    {
        $throttle = new ThrottleModel($this->getDb());
        $throttle = $this->getDb()->find($throttle, array('user_id' => $this->id));

        return ($throttle->status === ThrottleModel::STATUS_BLOCKED) ? true : false;
    }

    /**
     * Find the number of login attempts for a user
     *
     * @param integer $userId User ID [optional]
     * @return integer Number of login attempts
     */
    public function findAttemptsByUser($userId = null)
    {
        $userId = ($userId === null) ? $this->id : $userId;

        $throttle = new ThrottleModel($this->getDb());
        $throttle = $this->getDb()->find($throttle, array('user_id' => $userId));

        return ($throttle->attempts === null) ? 0 : $throttle->attempts;
    }

    /**
     * Grant permissions and groups (multiple) at the same time
     *
     * @param array $config Configuration settings (permissions & groups)
     * @param integer $expire Expiration time for the settings
     */
    public function grant(array $config, $expire = null)
    {
        $return = true;
        if (isset($config['permissions'])) {
            $result = $this->grantPermissions($config['permissions'], $expire);
            if ($result === false && $return === true) {
                $return = false;
            }
        }
        if (isset($config['groups'])) {
            $result = $this->grantGroups($config['groups'], $expire);
            if ($result === false && $return === true) {
                $return = false;
            }
        }
        return $return;
    }

    /**
     * Handle granting of multiple permissions
     *
     * @param array $permissions Set of permissions (either IDs or objects)
     * @param integer $expire EXpiration (unix timestamp) for the permissions
     * @return boolean Success/fail of all saves
     */
    public function grantPermissions(array $permissions, $expire = null)
    {
        $return = true;
        foreach ($permissions as $permission) {
            $permission = ($permission instanceof PermissionModel) ? $permission->id : $permission;
            $data = [
                'userId' => $this->id,
                'permissionId' => $permission
            ];
            if ($expire !== null && is_int($expire)) {
                $data['expire'] = $expire;
            }
            $userPerm = new UserPermissionModel($this->getDb(), $data);
            $result = $this->getDb()->save($userPerm);
            if ($result === false && $return === true) {
                $return = false;
            }
        }
        return $return;
    }

    /**
     * Handle granting of multiple groups
     *
     * @param array $groups Set of groups (either IDs or objects)
     * @param integer $expire EXpiration (unix timestamp) for the permissions
     * @return boolean Success/fail of all saves
     */
    public function grantGroups(array $groups, $expire = null)
    {
        $return = true;
        foreach ($groups as $group) {
            $group = ($group instanceof GroupModel) ? $group->id : $group;
            $data = [
                'userId' => $this->id,
                'groupId' => $group
            ];
            if ($expire !== null && is_int($expire)) {
                $data['expire'] = $expire;
            }
            $userGroup = new UserGroupModel($this->getDb(), $data);
            $result = $this->getDb()->save($userGroup);
            if ($result === false && $return === true) {
                $return = false;
            }
        }
        return $return;
    }

    /**
     * Add a new security question to the current user
     *
     * @param array $data Security question data
     * @return boolean Result of save operation
     */
    public function addSecurityQuestion(array $data)
    {
        if (!isset($data['question']) || !isset($data['answer'])) {
            throw new \InvalidArgumentException('Invalid question/answer data provided.');
        }

        // Ensure that the answer isn't the same as the user's password
        if (password_verify($data['answer'], $this->password) === true) {
            throw new \InvalidArgumentException('Security question answer cannot be the same as password.');
        }

        $question = new SecurityQuestionModel($this->getDb(), array(
            'question' => $data['question'],
            'answer' => $data['answer'],
            'userId' => $this->id
        ));
        return $this->getDb()->save($question);
    }

    /**
     * Update the last login time for the current user
     *
     * @param integer $time Unix timestamp [optional]
     * @return boolean Success/fail of update
     */
    public function updateLastLogin($time = null)
    {
        $time = ($time !== null) ? $time : time();
        $this->lastLogin = date('Y-m-d H:i:s', $time);
        return $this->getDb()->save($this);
    }
}