-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathUser.php
More file actions
1422 lines (1270 loc) · 44.2 KB
/
User.php
File metadata and controls
1422 lines (1270 loc) · 44.2 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
678
679
680
681
682
683
684
685
686
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Fleetbase\Models;
use Fleetbase\Casts\Json;
use Fleetbase\Exceptions\InvalidVerificationCodeException;
use Fleetbase\Notifications\UserCreated;
use Fleetbase\Notifications\UserInvited;
use Fleetbase\Support\NotificationRegistry;
use Fleetbase\Support\Timezone;
use Fleetbase\Support\Utils;
use Fleetbase\Traits\ClearsHttpCache;
use Fleetbase\Traits\Expandable;
use Fleetbase\Traits\Filterable;
use Fleetbase\Traits\HasApiModelBehavior;
use Fleetbase\Traits\HasCacheableAttributes;
use Fleetbase\Traits\HasMetaAttributes;
use Fleetbase\Traits\HasOptionsAttributes;
use Fleetbase\Traits\HasPresence;
use Fleetbase\Traits\HasPublicId;
use Fleetbase\Traits\HasSessionAttributes;
use Fleetbase\Traits\HasUuid;
use Fleetbase\Traits\ProxiesAuthorizationMethods;
use Fleetbase\Traits\Searchable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Concerns\HasTimestamps;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\CausesActivity;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
class User extends Authenticatable
{
use HasUuid;
use HasPublicId;
use HasPresence;
use Searchable;
use Notifiable;
use HasApiTokens;
use HasSlug;
use HasApiModelBehavior;
use HasCacheableAttributes;
use HasMetaAttributes;
use HasOptionsAttributes;
use HasTimestamps;
use LogsActivity;
use CausesActivity;
use SoftDeletes;
use ProxiesAuthorizationMethods, Expandable {
ProxiesAuthorizationMethods::__call insteadof Expandable;
Expandable::__call as __callExpansion;
}
use Filterable;
use ClearsHttpCache;
use HasSessionAttributes;
/**
* The database connection to use.
*
* @var string
*/
protected $connection = 'mysql';
/**
* Override the default primary key.
*
* @var string
*/
protected $primaryKey = 'uuid';
/**
* The "type" of the primary key ID.
*
* @var string
*/
protected $keyType = 'string';
/**
* Primary key is non incrementing.
*
* @var string
*/
public $incrementing = false;
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = true;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The type of public Id to generate.
*
* @var string
*/
protected $publicIdType = 'user';
/**
* The default guard for this model.
*
* @var string
*/
public $guard_name = 'sanctum';
/**
* The attributes that can be queried.
*
* @var array
*/
protected $searchableColumns = ['name', 'email', 'phone'];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'uuid',
'public_id',
'company_uuid',
'_key',
'avatar_uuid',
'username',
'email',
'apple_user_id',
'facebook_user_id',
'google_user_id',
'name',
'phone',
'date_of_birth',
'timezone',
'meta',
'options',
'country',
'ip_address',
'last_login',
'email_verified_at',
'phone_verified_at',
'slug',
'status',
];
/**
* Attributes which are not mass assignable.
*
* @var array
*/
protected $guarded = ['password', 'type'];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = ['password', 'remember_token', 'secret', 'avatar', 'username', 'company', 'companyUsers', 'companies'];
/**
* Dynamic attributes that are appended to object.
*
* @var array
*/
protected $appends = [
'avatar_url',
'session_status',
'company_name',
'company_onboarding_completed',
'is_admin',
'is_online',
'last_seen_at',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'meta' => Json::class,
'options' => Json::class,
'email_verified_at' => 'datetime',
'phone_verified_at' => 'datetime',
'last_login' => 'datetime',
];
/**
* Get the options for generating the slug.
*/
public function getSlugOptions(): SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug');
}
/**
* Get the activity log options for the model.
*/
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly([
'name',
'username',
'email',
'phone',
'date_of_birth',
'timezone',
'country',
'avatar_uuid',
])
->logOnlyDirty()
->dontLogIfAttributesChangedOnly(['last_login']);
}
/**
* Bootstraps the model and its events.
*
* This method overrides the default Eloquent model boot method
* to add a custom 'creating' event listener. This listener is used
* to set default values when a new model instance is being created.
*
* @return void
*/
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->username = $model->username ? $model->username : static::generateUsername($model->name);
});
}
/**
* Defines the relationship between the user and their company.
*
* This method establishes a `BelongsTo` relationship, indicating that the user belongs to a single company.
*
* @return BelongsTo the relationship instance between the User and the Company model
*/
public function company(): BelongsTo
{
return $this->belongsTo(Company::class);
}
/**
* Defines the relationship between the user and their avatar file.
*
* This method establishes a `BelongsTo` relationship, indicating that the user's avatar is a file record.
*
* @return BelongsTo the relationship instance between the User and the File model
*/
public function avatar(): BelongsTo
{
return $this->belongsTo(File::class);
}
/**
* Defines the relationship between the user and their devices.
*
* This method establishes a `HasMany` relationship, indicating that the user can have multiple associated devices.
*
* @return HasMany the relationship instance between the User and the UserDevice model
*/
public function devices(): HasMany
{
return $this->hasMany(UserDevice::class);
}
/**
* Retrieves all CompanyUser pivot records associated with the user.
*
* This method defines a one-to-many relationship between the User model and the CompanyUser model.
* It allows fetching all pivot records that link the user to various companies through the
* `company_users` pivot table using the `user_uuid` foreign key.
*
* **Usage Example:**
* ```php
* $user = User::find($userId);
* $companyUsers = $user->companyUsers;
* foreach ($companyUsers as $companyUser) {
* echo $companyUser->company->name;
* }
* ```
*
* @return HasMany the HasMany relationship instance
*
* @throws \LogicException if the relationship is improperly defined or the models do not exist
*
* @see CompanyUser
* @see Company
*/
public function companyUsers(): HasMany
{
return $this->hasMany(CompanyUser::class, 'user_uuid');
}
/**
* Retrieves all companies associated with the user through the CompanyUser pivot table.
*
* This method defines a HasManyThrough relationship between the User model and the Company model
* via the CompanyUser pivot table. It allows fetching all companies that the user is associated with
* through their entries in the CompanyUser pivot.
*
* **Usage Example:**
* ```php
* $user = User::find($userId);
* $companies = $user->companies;
* foreach ($companies as $company) {
* echo $company->name;
* }
* ```
*
* @return HasManyThrough the HasManyThrough relationship instance
*
* @throws \LogicException if the relationship is improperly defined or the models do not exist
*
* @see CompanyUser
* @see Company
*/
public function companies(): HasManyThrough
{
return $this->hasManyThrough(Company::class, CompanyUser::class, 'company_uuid', 'uuid', 'uuid', 'user_uuid');
}
/**
* Defines the relationship between the user and their current company user record.
*
* This method establishes a `HasOne` relationship, indicating that the user has one associated
* `CompanyUser` record for the current company (determined by the `company_uuid` stored in the session).
*
* @return HasOne|Builder the relationship instance between the User and the CompanyUser model
*/
public function companyUser(): HasOne|Builder
{
return $this->hasOne(CompanyUser::class, 'user_uuid', 'uuid')->where('company_uuid', $this->company_uuid);
}
/**
* Defines the relationship between the user and any company user record.
*
* This method establishes a `HasOne` relationship, indicating that the user has one associated
* `CompanyUser` record, regardless of the company.
*
* @return HasOne|Builder the relationship instance between the User and the CompanyUser model
*/
public function anyCompanyUser(): HasOne|Builder
{
return $this->hasOne(CompanyUser::class, 'user_uuid', 'uuid');
}
/**
* Defines the relationship between the user and the groups they are part of.
*
* This method establishes a `HasManyThrough` relationship, indicating that the user can belong to multiple groups
* through the `GroupUser` pivot table.
*
* @return HasManyThrough the relationship instance between the User and the Group model
*/
public function groups(): HasManyThrough
{
return $this->hasManyThrough(Group::class, GroupUser::class, 'user_uuid', 'uuid', 'uuid', 'group_uuid');
}
/**
* Retrieves the locale setting for the company.
*
* This method fetches the locale preference associated with the company using the company's UUID.
* It utilizes the `Setting::lookup` method to retrieve the locale value from the settings storage.
* If no locale is set for the company, it defaults to `'en-us'`.
*
* **Usage Example:**
* ```php
* try {
* $company = Company::find($companyId);
* $locale = $company->getLocale();
* // $locale might return 'en-us' or any other locale set for the company
* } catch (\Exception $e) {
* // Handle exception (e.g., log error, notify user)
* Log::error('Failed to retrieve company locale: ' . $e->getMessage());
* }
* ```
*
* @return string The locale code for the company (e.g., 'en-us', 'fr-fr').
*
* @throws \Exception if there is an issue accessing the settings storage
*
* @see Setting::lookup()
*/
public function getLocale(): string
{
try {
return Setting::lookup('user.' . $this->uuid . '.locale', 'en-us');
} catch (\Exception $e) {
throw new \Exception('Unable to retrieve user locale setting at this time.', 0, $e);
}
}
/**
* Generates a unique username based on the provided name.
*
* This method creates a username by taking the given name, appending
* a random 4-character string, and then converting the combination
* into a slug format. The name and the random string are separated
* by an underscore. The slugification ensures the username is URL-friendly
* (lowercase, with spaces and special characters turned into underscores).
*
* @param string $name the base name to be used for generating the username
*
* @return string the generated username in slug format with a random 4-character string
*/
public static function generateUsername(string $name): string
{
return Str::slug($name . '_' . Str::random(4), '_');
}
/**
* Retrieves the `CompanyUser` record for the user, either for the current or a specified company.
*
* This method first attempts to load the `companyUser` relationship, which is associated with the current company
* (as determined by the session). If a `CompanyUser` record is found, it is returned.
* If not, and a specific company is provided, the method searches the user's associated companies
* for a `CompanyUser` record matching the given company UUID.
*
* @param Company|null $company the company to retrieve the `CompanyUser` record for, or null to use the current company
*
* @return CompanyUser|null the `CompanyUser` instance if found, or null if not found
*/
public function getCompanyUser(?Company $company = null): ?CompanyUser
{
$this->loadMissing(['companyUser', 'companyUsers']);
if ($this->companyUser) {
return $this->companyUser;
}
$companyUuid = $company ? $company->uuid : $this->company_uuid;
if (!$companyUuid) {
return null;
}
$companyUser = $this->companyUsers()->where('company_uuid', $companyUuid)->first();
if ($companyUser) {
$this->setRelation('companyUser', $companyUser);
return $companyUser;
}
return null;
}
/**
* Load the associated company user relationship for the current user.
*
* This method ensures that the `companyUser` relationship is loaded for the user.
* If the relationship is not already loaded and no associated `companyUser` exists,
* it attempts to load the `company` relationship and retrieve the `companyUser`
* associated with the loaded company. If a `companyUser` is found, it sets
* the relationship accordingly.
*
* @return $this the current instance of the user model with the `companyUser` relationship loaded
*/
public function loadCompanyUser(): self
{
$this->loadMissing('companyUser');
if (!$this->companyUser) {
$this->loadMissing('company');
$companyUser = $this->getCompanyUser($this->company);
if ($companyUser) {
$this->setRelation('companyUser', $companyUser);
}
}
return $this;
}
/**
* Set the `companyUser` relation on the user for the specified company.
*
* This method searches for the `CompanyUser` relationship instance associated with the provided
* company. If a matching `CompanyUser` record is found, it sets the `companyUser` relation
* on the user model, allowing it to be accessed as if it were loaded through a relationship.
*
* @param Company $company the company instance to set the `companyUser` relation for
*/
public function setCompanyUserRelation(Company $company): void
{
$companyUser = $this->companyUsers()->where('company_uuid', $company->uuid)->first();
if ($companyUser) {
$this->setRelation('companyUser', $companyUser);
}
}
/**
* Assigns the user to a company and handles related processes.
*
* This method assigns the given company to the user by updating the `company_uuid` attribute.
* It creates a new `CompanyUser` record if it does not exist. If the user is not an admin
* and is not the company owner, they will be invited to join the company and the company owner
* will be notified that a user has been created.
*
* @param Company $company the company to assign the user to
* @param string|null $role The name or ID of the role to assign to the user. Defaults to the user's current role if null.
*
* @return self returns the current User instance
*/
public function assignCompany(Company $company, string $role = 'Administrator'): self
{
$this->company_uuid = $company->uuid;
// Create company user record
if (CompanyUser::where(['company_uuid' => $company->uuid, 'user_uuid' => $this->uuid])->doesntExist()) {
$companyUser = $company->addUser($this, $role);
$this->setRelation('companyUser', $companyUser);
}
// Determine if user should receive invite to join company
if ($this->isNotAdmin() && !$this->isCompanyOwner($company)) {
// Invite user to join company
$this->sendInviteFromCompany($company);
// Notify the company owner a user has been created
NotificationRegistry::notify(UserCreated::class, $this, $company);
}
$this->save();
return $this;
}
/**
* Sets the user's company without any additional processing.
*
* This method directly assigns the given company to the user by updating the `company_uuid` attribute
* and saving the model.
*
* @param Company $company the company to set for the user
*
* @return self returns the current User instance
*/
public function setCompany(Company $company): self
{
$this->company_uuid = $company->uuid;
$this->save();
return $this;
}
/**
* Checks if the user is the owner of the given company.
*
* This method compares the user's UUID with the owner's UUID of the specified company
* to determine if the user is the owner.
*
* @param Company $company the company to check ownership of
*
* @return bool returns true if the user is the company owner, false otherwise
*/
public function isCompanyOwner(Company $company): bool
{
return $this->uuid === $company->owner_uuid;
}
/**
* Assigns the user to a company based on a company ID or public ID.
*
* This method checks if the provided ID is a valid UUID or public ID.
* If a company is found with the given ID, the user is assigned to that company.
*
* @param string|null $id the UUID or public ID of the company to assign the user to
*
* @return self returns the current User instance
*/
public function assignCompanyFromId(?string $id): self
{
if (!Str::isUuid($id) && !Utils::isPublicId($id)) {
return $this;
}
// Get company record
$company = Company::where('uuid', $id)->orWhere('public_id', $id)->first();
if ($company) {
return $this->assignCompany($company);
}
return $this;
}
/**
* Accessor for the user's role.
*
* This method retrieves the first role assigned to the user in the current company context.
*
* @return Role|null the first Role instance associated with the user, or null if no role is found
*/
public function getRoleAttribute(): ?Role
{
$this->loadCompanyUser();
if (!$this->companyUser) {
return null;
}
return $this->companyUser->roles()->first();
}
/**
* Accessor for the user's roles.
*
* This method retrieves all roles assigned to the user in the current company context.
*
* @return Collection a collection of Role instances associated with the user, or null if no roles are found
*/
public function getRolesAttribute(): Collection
{
$this->loadCompanyUser();
if (!$this->companyUser) {
return collect();
}
return $this->companyUser->roles()->get();
}
/**
* Accessor for the user's policies.
*
* This method retrieves all policies assigned to the user in the current company context.
*
* @return Collection a collection of Policy instances associated with the user, or null if no policies are found
*/
public function getPoliciesAttribute(): Collection
{
$this->loadCompanyUser();
if (!$this->companyUser) {
return collect();
}
return $this->companyUser->policies()->get();
}
/**
* Accessor for the user's permissions.
*
* This method retrieves all permissions assigned to the user in the current company context.
*
* @return Collection a collection of Permission instances associated with the user, or null if no permissions are found
*/
public function getPermissionsAttribute(): Collection
{
$this->loadCompanyUser();
if (!$this->companyUser) {
return collect();
}
return $this->companyUser->permissions()->get();
}
/**
* Accessor for the user's session status.
*
* This method retrieves the user's status in the current company context.
* If no status is found, it defaults to 'pending'.
*
* @return string the user's session status, or 'pending' if not set
*/
public function getSessionStatusAttribute(): string
{
$this->loadCompanyUser();
return $this->companyUser ? $this->companyUser->status : 'pending';
}
/**
* Finds and sets the user's session status.
*
* This method retrieves the user's status in the current company context
* and sets it as an attribute on the user model. If no status is found, it defaults to 'pending'.
*
* @return string the user's session status, or 'pending' if not set
*/
public function findSessionStatus(): string
{
$this->loadCompanyUser();
$status = $this->companyUser ? $this->companyUser->status : 'pending';
$this->setAttribute('session_status', $status);
return $status;
}
/**
* Specifies the user's FCM tokens.
*/
public function routeNotificationForFcm(): array
{
$this->loadMissing('devices');
return $this->devices->where('platform', 'android')->map(
function ($userDevice) {
return $userDevice->token;
}
)->toArray();
}
/**
* Specifies the user's APNS tokens.
*/
public function routeNotificationForApn(): array
{
$this->loadMissing('devices');
return $this->devices->where('platform', 'ios')->map(
function ($userDevice) {
return $userDevice->token;
}
)->toArray();
}
/**
* Get avatar URL attribute.
*/
public function getAvatarUrlAttribute(): string
{
if ($this->avatar instanceof File) {
return $this->avatar->url;
}
return data_get($this, 'avatar.url', 'https://s3.ap-southeast-1.amazonaws.com/flb-assets/static/no-avatar.png');
}
/**
* Get the users's company name.
*/
public function getCompanyNameAttribute(): ?string
{
return data_get($this, 'company.name');
}
/**
* Get the users's company onboard completed.
*/
public function getCompanyOnboardingCompletedAttribute(): bool
{
return data_get($this, 'company.onboarding_completed_at') !== null;
}
/**
* Get the users's company name.
*/
public function getDriverUuidAttribute(): ?string
{
return data_get($this, 'driver.uuid');
}
/**
* Checks if the user is admin.
*/
public function isAdmin(): bool
{
return $this->type === 'admin';
}
/**
* Checks if the user is NOT admin.
*/
public function isNotAdmin(): bool
{
return $this->type !== 'admin';
}
/**
* Checks if the user is NOT admin.
*/
public function isType(string|array $type): bool
{
if (is_array($type)) {
return in_array($this->type, $type);
}
return $this->type === $type;
}
/**
* Checks if the user is NOT admin.
*/
public function isNotType(string|array $type): bool
{
return !$this->isType($type);
}
/**
* Adds a boolean dynamic property to check if user is an admin.
*
* @return void
*/
public function getIsAdminAttribute(): bool
{
return $this->isAdmin();
}
/**
* Set the user type.
*/
public function setType(string $type): self
{
static::unguarded(function () use ($type) {
$this->type = $type;
$this->save();
});
return $this;
}
/**
* Get the user type.
*/
public function getType(): ?string
{
return $this->getAttribute('type');
}
/**
* Set and hash password.
*/
public function setPasswordAttribute($value): void
{
$this->attributes['password'] = Hash::make($value);
}
/**
* Set the default status to `active`.
*/
public function setStatusAttribute($value = 'active'): void
{
$this->attributes['status'] = $value ?? 'active';
}
/**
* Retrieves the user's timezone.
*
* This method returns the timezone associated with the user. If no timezone is set,
* it defaults to 'Asia/Singapore'.
*
* @return string the user's timezone, or 'Asia/Singapore' if not set
*/
public function getTimezone(): string
{
return data_get($this, 'timezone', 'Asia/Singapore');
}
/**
* Retrieves the company associated with the user.
*
* This method first attempts to load the company relationship. If the relationship
* is not found, it attempts to locate the company using the user's `company_uuid` attribute.
*
* @return Company|null the associated Company instance, or null if no company is found
*/
public function getCompany(): Company
{
// Get company relationship
$company = $this->load(['company'])->company;
// Attempt to find company using `uuid`
if (empty($company) && Str::isUuid($this->getAttribute('company_uuid'))) {
$company = Company::where('uuid', $this->company_uuid)->first();
}
return $company;
}
/**
* Updates the user's last login timestamp.
*
* This method sets the user's `last_login` attribute to the current date and time
* and then saves the model.
*
* @return self returns the current User instance
*/
public function updateLastLogin(): self
{
$this->last_login = Carbon::now()->toDateTimeString();
$this->save();
return $this;
}
/**
* Changes the user's password.
*
* This method updates the user's password to the provided new password and saves the model.
*
* @param string $newPassword the new password for the user
*
* @return self returns the current User instance
*/
public function changePassword($newPassword): self
{
$this->password = $newPassword;
$this->save();
return $this;
}
/**
* Verifies the given password against the user's stored password.
*
* This method checks if the provided password matches the user's current password.
*
* @param string $password the plain text password to verify
*
* @return bool returns true if the password matches, false otherwise
*/
public function checkPassword(string $password): bool
{
return Hash::check($password, $this->password);
}
/**
* Deactivates the user.
*
* This method sets the user's status to 'inactive' and saves the model.
*
* @return self returns the current User instance
*/
public function deactivate(): self
{
$this->status = 'inactive';
$this->save();
$this->loadCompanyUser();
if ($this->companyUser) {
$this->companyUser->status = 'inactive';
$this->companyUser->save();
}
return $this;
}
/**
* Activates the user.
*
* This method sets the user's status to 'active' and saves the model.
*
* @return self returns the current User instance
*/
public function activate(): self
{
$this->status = 'active';
$this->save();
$this->loadCompanyUser();
if ($this->companyUser) {
$this->companyUser->status = 'active';
$this->companyUser->save();
}
return $this;
}
/**
* Retrieve the verification code for the given type and code.
*
* @param string $code the verification code to verify
* @param array $types The types of verification to check (e.g., 'email_verification', 'phone_verification').
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
*/
public function getVerificationCodeOrFail(string $code, array $types = ['email_verification', 'phone_verification']): VerificationCode
{
$verifyCode = VerificationCode::where('subject_uuid', $this->uuid)
->whereIn('for', $types)
->where('code', $code)
->firstOrFail();
return $verifyCode;
}
/**
* Verify the user's email or phone based on the verification code.
*