-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathUser.php
More file actions
677 lines (594 loc) · 21.4 KB
/
User.php
File metadata and controls
677 lines (594 loc) · 21.4 KB
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
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
<?php
namespace DreamFactory\Core\Models;
use DreamFactory\Core\Components\RegisterContact;
use DreamFactory\Core\Database\Schema\RelationSchema;
use DreamFactory\Core\Events\UserCreatingEvent;
use DreamFactory\Core\Events\UserDeletedEvent;
use DreamFactory\Core\Exceptions\NotFoundException;
use DreamFactory\Core\Exceptions\ForbiddenException;
use DreamFactory\Core\Exceptions\InternalServerErrorException;
use DreamFactory\Core\Exceptions\BadRequestException;
use DreamFactory\Core\Utility\DataFormatter;
use DreamFactory\Core\Utility\JWTUtilities;
use DreamFactory\Core\Utility\Session;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;
use Validator;
/**
* User
*
* @property integer $id
* @property string $name
* @property string $username
* @property string $first_name
* @property string $last_name
* @property string $email
* @property string $phone
* @property string $confirm_code
* @property string $remember_token
* @property string $adldap
* @property string $oauth_provider
* @property string $security_question
* @property string $security_answer
* @property int $default_app_id
* @property boolean $is_active
* @property boolean $is_sys_admin
* @property string $last_login_date
* @property string $created_date
* @property string $last_modified_date
* @method static \Illuminate\Database\Query\Builder|User whereId($value)
* @method static \Illuminate\Database\Query\Builder|User whereName($value)
* @method static \Illuminate\Database\Query\Builder|User whereFirstName($value)
* @method static \Illuminate\Database\Query\Builder|User whereLastName($value)
* @method static \Illuminate\Database\Query\Builder|User whereEmail($value)
* @method static \Illuminate\Database\Query\Builder|User whereIsActive($value)
* @method static \Illuminate\Database\Query\Builder|User whereIsSysAdmin($value)
* @method static \Illuminate\Database\Query\Builder|User whereCreatedDate($value)
* @method static \Illuminate\Database\Query\Builder|User whereLastModifiedDate($value)
*/
class User extends BaseSystemModel implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'user';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'username',
'ldap_username',
'first_name',
'last_name',
'email',
'is_active',
'phone',
'security_question',
'security_answer',
'adldap',
'oauth_provider',
'last_login_date',
'default_app_id',
'saml',
'integrateio_id'
];
/**
* Input validation rules.
*
* @type array
*/
protected $rules = [
'name' => 'required|max:255',
'email' => 'required|email|max:255',
'username' => 'min:6|unique:user,username|regex:/^\S*$/u|nullable'
];
/**
* Appended fields.
*
* @var array
*/
protected $appends = ['confirmed', 'expired'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['is_sys_admin', 'password', 'remember_token', 'security_answer', 'confirm_code'];
/**
* Field type casting
*
* @var array
*/
protected $casts = ['is_active' => 'boolean', 'is_sys_admin' => 'boolean', 'id' => 'integer'];
/**
* Gets account confirmation status.
*
* @return string
*/
public function getConfirmedAttribute()
{
$code = $this->confirm_code;
if ($code === 'y' || is_null($code)) {
return true;
} else {
return false;
}
}
/**
* Shows confirmation expiration.
*
* @return bool
*/
public function getExpiredAttribute()
{
return $this->isConfirmationExpired();
}
/**
* Checks to se if confirmation period is expired.
*
* @return bool
*/
public function isConfirmationExpired()
{
$ttl = \Config::get('df.confirm_code_ttl', 1440);
$lastModTime = strtotime($this->last_modified_date);
$code = $this->confirm_code;
if ('y' !== $code && !is_null($code) && ((time() - $lastModTime) > ($ttl * 60))) {
return true;
} else {
return false;
}
}
/**
* Assigns a role to a user for all apps in the system.
*
* @param $user
* @param $defaultRole
*
* @return bool
* @throws \Exception
*/
public static function applyDefaultUserAppRole($user, $defaultRole)
{
$apps = App::all();
if (count($apps) === 0) {
return false;
}
foreach ($apps as $app) {
if (!UserAppRole::whereUserId($user->id)->whereAppId($app->id)->exists()) {
$userAppRoleData = [
'user_id' => $user->id,
'app_id' => $app->id,
'role_id' => $defaultRole
];
UserAppRole::create($userAppRoleData);
}
}
return true;
}
/**
* Applies App to Role mapping to a user.
*
* @param User $user
* @param integer $serviceId
*/
public static function applyAppRoleMapByService($user, $serviceId)
{
$maps = AppRoleMap::whereServiceId($serviceId)->get();
foreach ($maps as $map) {
UserAppRole::whereUserId($user->id)->whereAppId($map->app_id)->delete();
$userAppRoleData = [
'user_id' => $user->id,
'app_id' => $map->app_id,
'role_id' => $map->role_id
];
UserAppRole::create($userAppRoleData);
}
}
/**
* {@inheritdoc}
*/
public function validate($data, $throwException = true)
{
$loginAttribute = strtolower(config('df.login_attribute', 'email'));
if ($loginAttribute === 'username') {
$this->rules['username'] = str_replace('|nullable', '|required', $this->rules['username']);
}
return parent::validate($data, $throwException);
}
/**
* @param $password
*
* @throws \DreamFactory\Core\Exceptions\BadRequestException
*/
public static function validatePassword($password)
{
$data = [
'password' => $password
];
$rule = [
'password' => 'min:6'
];
$validator = Validator::make($data, $rule);
if ($validator->fails()) {
$msg = $validator->errors()->getMessages();
$errorString = DataFormatter::validationErrorsToString($msg);
throw new BadRequestException('Invalid data supplied.' . $errorString, null, null, $msg);
}
}
/**
* {@inheritdoc}
*/
protected static function createInternal($record, $params = [])
{
try {
if (!isset($record['name'])) {
// potentially combine first and last
$first = (isset($record['first_name']) ? $record['first_name'] : null);
$last = (isset($record['last_name']) ? $record['last_name'] : null);
$name = (!empty($first)) ? $first : '';
$name .= (!empty($name) && !empty($last)) ? ' ' : '';
$name .= (!empty($last)) ? $last : '';
if (empty($name)) {
// use the first part of their email or the username
$email = (isset($record['email']) ? $record['email'] : null);
$name = (!empty($email) && strpos($email, '@')) ? strstr($email, '@', true) : '';
}
$record['name'] = $name;
}
$password = array_get($record, 'password');
if (!empty($password)) {
static::validatePassword($password);
}
$model = static::create($record);
if (array_get_bool($params, 'admin') && array_get_bool($record, 'is_sys_admin')) {
$model->is_sys_admin = 1;
}
$model->password = $password;
$model->save();
} catch (\Exception $ex) {
if (!$ex instanceof ForbiddenException && !$ex instanceof BadRequestException) {
throw new InternalServerErrorException('Failed to create resource: ' . $ex->getMessage());
} else {
throw $ex;
}
}
return static::buildResult($model, $params);
}
/**
* {@inheritdoc}
*/
public static function updateInternal($id, $record, $params = [])
{
if (empty($record)) {
throw new BadRequestException('There are no fields in the record to create . ');
}
if (empty($id)) {
//Todo:perform logging below
//Log::error( 'Update request with no id supplied: ' . print_r( $record, true ) );
throw new BadRequestException('Identifying field "id" can not be empty for update request . ');
}
/** @type User $model */
$model = static::find($id);
if (!$model instanceof Model) {
throw new NotFoundException("Record with identifier '$id' not found.");
}
$pk = $model->primaryKey;
// Remove the PK from the record since this is an update
unset($record[$pk]);
try {
if ($model->is_sys_admin && !array_get_bool($params, 'admin')) {
throw new ForbiddenException('Not allowed to change an admin user.');
} elseif (array_get_bool($params, 'admin') && !$model->is_sys_admin) {
throw new BadRequestException('Cannot update a non-admin user.');
}
$password = array_get($record, 'password');
if (!empty($password)) {
$model->password = $password;
static::validatePassword($password);
}
$model->update($record);
return static::buildResult($model, $params);
} catch (\Exception $ex) {
if (!$ex instanceof ForbiddenException && !$ex instanceof BadRequestException) {
throw new InternalServerErrorException('Failed to update resource: ' . $ex->getMessage());
} else {
throw $ex;
}
}
}
/**
* {@inheritdoc}
*/
public function update(array $attributes = [], array $options = [])
{
$oldEmail = $this->email;
$updated = parent::update($attributes);
if ($updated && $this->is_sys_admin) {
$newEmail = $this->email;
if (('user@example.com' === $oldEmail) && ('user@example.com' !== $newEmail)) {
// Register user
RegisterContact::registerUser($this);
}
}
return $updated;
}
/**
* {@inheritdoc}
*/
public static function deleteInternal($id, $record, $params = [])
{
if (empty($record)) {
throw new BadRequestException('There are no fields in the record to create . ');
}
if (empty($id)) {
//Todo:perform logging below
//Log::error( 'Update request with no id supplied: ' . print_r( $record, true ) );
throw new BadRequestException('Identifying field "id" can not be empty for update request . ');
}
/** @type User $model */
$model = static::find($id);
if (!$model instanceof Model) {
throw new NotFoundException("Record with identifier '$id' not found.");
}
try {
if ($model->is_sys_admin && !array_get_bool($params, 'admin')) {
throw new ForbiddenException('Not allowed to delete an admin user.');
} elseif (array_get_bool($params, 'admin') && !$model->is_sys_admin) {
throw new BadRequestException('Cannot delete a non-admin user.');
} elseif (Session::getCurrentUserId() === $model->id) {
throw new ForbiddenException('Cannot delete your account.');
}
$result = static::buildResult($model, $params);
if ('sqlsrv' === $model->getConnection()->getDriverName()) {
// cleanup references not happening automatically due to schema setup
$references = $model->getReferences();
/** @type RelationSchema $reference */
foreach ($references as $reference) {
if ((RelationSchema::HAS_ONE === $reference->type) &&
(('created_by_id' === $reference->refField[0]) ||
('last_modified_by_id' === $reference->refField[0]))
) {
$stmt =
'update [' .
$reference->refTable .
'] set [' .
$reference->refField[0] .
'] = null where [' .
$reference->refField[0] .
'] = ' .
$id;
if (0 !== $rows = \DB::update($stmt)) {
\Log::debug('found rows: ' . $rows);
}
} elseif ((RelationSchema::HAS_MANY === $reference->type) &&
(('created_by_id' === $reference->refField[0]) ||
('last_modified_by_id' === $reference->refField[0]))
) {
$stmt =
'update [' .
$reference->refTable .
'] set [' .
$reference->refField[0] .
'] = null where [' .
$reference->refField[0] .
'] = ' .
$id;
if (0 !== $rows = \DB::update($stmt)) {
\Log::debug('found rows: ' . $rows);
}
} elseif ((RelationSchema::BELONGS_TO === $reference->type) &&
(('created_by_id' === $reference->field[0]) ||
('last_modified_by_id' === $reference->field[0]))
) {
$stmt =
'update [' .
$reference->refTable .
'] set [' .
$reference->field[0] .
'] = null where [' .
$reference->field[0] .
'] = ' .
$id . ' and [' . $reference->refField[0] . '] != ' . $id;
if (0 !== $rows = \DB::update($stmt)) {
\Log::debug('found rows: ' . $rows);
}
}
}
}
$model->delete();
return $result;
} catch (\Exception $ex) {
if (!$ex instanceof ForbiddenException && !$ex instanceof BadRequestException) {
throw new InternalServerErrorException('Failed to delete resource: ' . $ex->getMessage());
} else {
throw $ex;
}
}
}
/**
* Encrypts security answer.
*
* @param string $value
*/
public function setSecurityAnswerAttribute($value)
{
$this->attributes['security_answer'] = Hash::make($value);
}
/**
* Encrypts password.
*
* @param $password
*/
public function setPasswordAttribute($password)
{
if (!empty($password)) {
$password = Hash::make($password);
JWTUtilities::invalidateTokenByUserId($this->id);
// When password is set user account must be confirmed. Confirming user
// account here with confirm_code = null.
// confirm_code = 'y' indicates cases where account is confirmed by user
// using confirmation email.
if (isset($this->attributes['confirm_code']) && $this->attributes['confirm_code'] !== 'y') {
$this->attributes['confirm_code'] = null;
}
}
$this->attributes['password'] = $password;
}
/**
* Updates password hash directly.
* This is used by package import in order to preserve
* user password during import.
*
* @param $hash
*/
public function updatePasswordHash($hash)
{
$this->attributes['password'] = $hash;
$this->save();
}
public static function boot()
{
parent::boot();
static::creating(
function (User $user){
event(new UserCreatingEvent($user));
}
);
static::saved(
function (User $user){
if (!$user->is_active) {
JWTUtilities::invalidateTokenByUserId($user->id);
}
\Cache::forget('user:' . $user->id);
}
);
static::deleted(
function (User $user){
JWTUtilities::invalidateTokenByUserId($user->id);
\Cache::forget('user:' . $user->id);
event(new UserDeletedEvent($user));
}
);
}
/**
* Returns user info cached, or reads from db if not present.
* Pass in a key to return a portion/index of the cached data.
*
* @param int $id
* @param null|string $key
* @param null $default
*
* @return mixed|null
*/
public static function getCachedInfo($id, $key = null, $default = null)
{
$cacheKey = 'user:' . $id;
$result = \Cache::remember($cacheKey, \Config::get('df.default_cache_ttl'), function () use ($id){
$user = static::whereId($id)->first();
if (empty($user)) {
throw new NotFoundException("User not found.");
}
if (!$user->is_active) {
throw new ForbiddenException("User is not active.");
}
$userInfo = $user->toArray();
$userInfo['is_sys_admin'] = $user->is_sys_admin;
return $userInfo;
});
if (is_null($result)) {
return $default;
}
if (is_null($key)) {
return $result;
}
return (isset($result[$key]) ? $result[$key] : $default);
}
/**
* @return boolean
*/
public static function adminExists()
{
return \Cache::rememberForever('admin_exists', function (){
return static::whereIsActive(1)->whereIsSysAdmin(1)->exists();
});
}
public static function resetAdminExists()
{
return \Cache::forget('admin_exists');
}
/**
* Creates first admin user.
*
* @param array $data
*
* @return User|boolean
*/
public static function createFirstAdmin(array &$data)
{
if (empty($data['username'])) {
$data['username'] = $data['email'];
}
$validationRules = [
'name' => 'required|max:255',
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'email' => 'required|email|max:255|unique:user',
'password' => 'required|confirmed|min:6',
'username' => 'min:6|unique:user,username|regex:/^\S*$/u|required',
'phone' => 'required|max:32',
];
$validator = Validator::make($data, $validationRules);
if ($validator->fails()) {
$errors = $validator->getMessageBag()->all();
$data = array_merge($data, ['errors' => $errors, 'version' => \Config::get('app.version')]);
return false;
} else {
/** @type User $user */
$attributes = array_only($data, ['name', 'first_name', 'last_name', 'email', 'username', 'phone']);
$attributes['is_active'] = 1;
$user = static::create($attributes);
$user->password = array_get($data, 'password');
$user->is_sys_admin = 1;
$user->save();
InstanceId::getInstanceIdOrGenerate();
// Register user
RegisterContact::registerUser($user);
// Reset admin_exists flag in cache.
\Cache::forever('admin_exists', true);
return $user;
}
}
public function save(array $options = [])
{
if ($this->exists) {
// Check uniqueness of username excluding this user that is being updated.
$usernameRules = explode('|', $this->rules['username']);
$usernameRules[1] .= ',' . $this->id;
$this->rules['username'] = implode('|', $usernameRules);
}
$loginAttribute = strtolower(config('df.login_attribute', 'email'));
$username = array_get($this->attributes, 'username');
if ($loginAttribute !== 'username' && empty($username)) {
$this->attributes['username'] = $this->attributes['email'];
}
return parent::save($options);
}
protected static function getModelFromTable($table)
{
if ('lookup' === $table) {
return UserLookup::class;
}
return parent::getModelFromTable($table);
}
}