Passed
Pull Request — master (#354)
by
unknown
01:27
created

Users::getAssociatedCompanies()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
nc 2
nop 0
dl 0
loc 11
ccs 0
cts 4
cp 0
crap 6
rs 10
c 1
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Canvas\Models;
5
6
use Canvas\Traits\PermissionsTrait;
7
use Canvas\Traits\SubscriptionPlanLimitTrait;
8
use Phalcon\Cashier\Billable;
0 ignored issues
show
Bug introduced by
The type Phalcon\Cashier\Billable was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
use Carbon\Carbon;
0 ignored issues
show
Bug introduced by
The type Carbon\Carbon was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
10
use Phalcon\Validation;
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use Phalcon\Validation\Validator\Email;
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\Email was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
use Phalcon\Validation\Validator\PresenceOf;
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\PresenceOf was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
use Phalcon\Validation\Validator\Uniqueness;
14
use Canvas\Traits\FileSystemModelTrait;
15
use Phalcon\Security\Random;
0 ignored issues
show
Bug introduced by
The type Phalcon\Security\Random was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
16
use Baka\Database\Contracts\HashTableTrait;
0 ignored issues
show
Bug introduced by
The type Baka\Database\Contracts\HashTableTrait was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
17
use Canvas\Contracts\Notifications\NotifiableTrait;
18
use Canvas\Traits\EventManagerAwareTrait;
19
use Phalcon\Di;
20
use Canvas\Auth\App as AppAuth;
21
use Exception;
22
use Canvas\Validations\PasswordValidation;
23
use Baka\Auth\Models\Users as BakUser;
0 ignored issues
show
Bug introduced by
The type Baka\Auth\Models\Users was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
24
use Canvas\Hashing\Password;
25
26
/**
27
 * Class Users.
28
 *
29
 * @package Canvas\Models
30
 *
31
 * @property Users $user
32
 * @property Config $config
33
 * @property Apps $app
34
 * @property Companies $defaultCompany
35
 * @property \Phalcon\Di $di
36
 */
37
class Users extends \Baka\Auth\Models\Users
38
{
39
    use PermissionsTrait;
40
    use Billable;
41
    use SubscriptionPlanLimitTrait;
42
    use FileSystemModelTrait;
43
    use HashTableTrait;
44
    use NotifiableTrait;
45
    use EventManagerAwareTrait;
46
47
    /**
48
     * Default Company Branch.
49
     *
50
     * @var integer
51
     */
52
    public $default_company_branch;
53
54
    /**
55
     * Roles id.
56
     *
57
     * @var integer
58
     */
59
    public $roles_id;
60
61
    /**
62
     * Stripe id.
63
     *
64
     * @var string
65
     */
66
    public $stripe_id;
67
68
    /**
69
     * Card last four numbers.
70
     *
71
     * @var integer
72
     */
73
    public $card_last_four;
74
75
    /**
76
     * Card Brand.
77
     *
78
     * @var integer
79
     */
80
    public $card_brand;
81
82
    /**
83
     * Trial end date.
84
     *
85
     * @var string
86
     */
87
    public $trial_ends_at;
88
89
    /**
90
     * Provide the app plan id
91
     * if the user is signing up a new company.
92
     *
93
     * @var integer
94
     */
95
    public $appPlanId = null;
96
97
    /**
98
     * Active subscription id.Not an actual table field, used temporarily.
99
     * @var string
100
     */
101
    public $active_subscription_id;
102
103
    /**
104
     * System Module Id.
105
     * @var integer
106
     */
107
    public $system_modules_id = 2;
108
109
    /**
110
     * User email activation code.
111
     *
112
     * @var string
113
     */
114
    public $user_activation_email;
115
116
    /**
117
     * Initialize method for model.
118
     */
119
    public function initialize()
120
    {
121
        $this->setSource('users');
122
123
        //overwrite parent relationships
124
        $this->hasOne('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'session']);
125
        $this->hasMany('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'sessions']);
126
        $this->hasMany('id', 'Baka\Auth\Models\SessionKeys', 'users_id', ['alias' => 'sessionKeys']);
127
        $this->hasMany('id', 'Baka\Auth\Models\Banlist', 'users_id', ['alias' => 'bans']);
128
        $this->hasMany('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'sessions']);
129
        $this->hasMany('id', 'Canvas\Models\UserConfig', 'users_id', ['alias' => 'config']);
130
        $this->hasMany('id', 'Canvas\Models\UserLinkedSources', 'users_id', ['alias' => 'sources']);
131
132
        $this->hasOne(
133
            'default_company',
134
            'Canvas\Models\Companies',
135
            'id',
136
            ['alias' => 'defaultCompany']
137
        );
138
139
        $this->hasOne(
140
            'default_company',
141
            'Canvas\Models\Companies',
142
            'id',
143
            ['alias' => 'currentCompany']
144
        );
145
146
        $this->hasMany(
147
            'id',
148
            'Canvas\Models\Subscription',
149
            'user_id',
150
            [
151
                'alias' => 'allSubscriptions',
152
                'params' => [
153
                    'conditions' => 'apps_id = ?0',
154
                    'bind' => [$this->di->getApp()->getId()],
155
                    'order' => 'id DESC'
156
                ]
157
            ]
158
        );
159
160
        $this->hasMany(
161
            'id',
162
            'Canvas\Models\UsersAssociatedApps',
163
            'users_id',
164
            [
165
                'alias' => 'companies',
166
                'params' => [
167
                    'conditions' => 'apps_id = ?0',
168
                    'bind' => [$this->di->getApp()->getId()],
169
                ]
170
            ]
171
        );
172
173
        $this->hasMany(
174
            'id',
175
            'Canvas\Models\UsersAssociatedApps',
176
            'users_id',
177
            [
178
                'alias' => 'apps',
179
            ]
180
        );
181
182
        $this->hasOne(
183
            'id',
184
            'Canvas\Models\UsersAssociatedApps',
185
            'users_id',
186
            [
187
                'alias' => 'app',
188
                'params' => [
189
                    'conditions' => 'apps_id = ?0',
190
                    'bind' => [Di::getDefault()->getApp()->getId()]
191
                ]
192
            ]
193
        );
194
195
        $this->hasMany(
196
            'id',
197
            'Canvas\Models\UserWebhooks',
198
            'users_id',
199
            ['alias' => 'userWebhook']
200
        );
201
202
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
0 ignored issues
show
Deprecated Code introduced by
The function Canvas\Models\SystemModu...stemModuleByModelName() has been deprecated: v2 ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

202
        $systemModule = /** @scrutinizer ignore-deprecated */ SystemModules::getSystemModuleByModelName(self::class);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
203
        $this->hasOne(
204
            'id',
205
            'Canvas\Models\FileSystemEntities',
206
            'entity_id',
207
            [
208
                'alias' => 'files',
209
                'params' => [
210
                    'conditions' => 'system_modules_id = ?0',
211
                    'bind' => [$systemModule->getId()]
212
                ]
213
            ]
214
        );
215
    }
216
217
    /**
218
     * Initialize relationshit after fetch
219
     * since we need company id info.
220
     *
221
     * @return void
222
     */
223
    public function afterFetch()
224
    {
225
        $this->hasManyToMany(
226
            'id',
227
            'Canvas\Models\UserRoles',
228
            'users_id',
229
            'roles_id',
230
            'Canvas\Models\Roles',
231
            'id',
232
            [
233
                'alias' => 'roles',
234
                'params' => [
235
                    'limit' => 1,
236
                    'conditions' => 'Canvas\Models\UserRoles.apps_id = ' . $this->di->getApp()->getId() . ' AND Canvas\Models\UserRoles.companies_id = ' . $this->currentCompanyId(),
237
                    'order' => 'Canvas\Models\UserRoles.apps_id desc',
238
                ]
239
            ]
240
        );
241
242
        $this->hasOne(
243
            'id',
244
            'Canvas\Models\UserRoles',
245
            'users_id',
246
            [
247
                'alias' => 'userRole',
248
                'params' => [
249
                    'limit' => 1,
250
                    'conditions' => 'Canvas\Models\UserRoles.apps_id in (?0, ?1) AND Canvas\Models\UserRoles.companies_id = ' . $this->currentCompanyId(),
251
                    'bind' => [$this->di->getApp()->getId(), Roles::DEFAULT_ACL_APP_ID],
252
                    'order' => 'apps_id desc',
253
                ]
254
            ]
255
        );
256
257
        $this->hasMany(
258
            'id',
259
            'Canvas\Models\UserRoles',
260
            'users_id',
261
            [
262
                'alias' => 'permissions',
263
                'params' => [
264
                    'conditions' => 'Canvas\Models\UserRoles.apps_id = ' . $this->di->getApp()->getId() . ' AND Canvas\Models\UserRoles.companies_id = ' . $this->currentCompanyId(),
265
                ]
266
            ]
267
        );
268
    }
269
270
    /**
271
     * Validations and business logic.
272
     */
273
    public function validation()
274
    {
275
        $validator = new Validation();
276
        $validator->add(
277
            'email',
278
            new Email([
279
                'field' => 'email',
280
                'required' => true,
281
            ])
282
        );
283
284
        $validator->add(
285
            'displayname',
286
            new PresenceOf([
287
                'field' => 'displayname',
288
                'required' => true,
289
            ])
290
        );
291
292
        // Unique values
293
        $validator->add(
294
            'email',
295
            new Uniqueness([
296
                'field' => 'email',
297
                'message' => _('This email already has an account.'),
298
            ])
299
        );
300
301
        return $this->validate($validator);
302
    }
303
304
    /**
305
     * Returns table name mapped in the model.
306
     *
307
     * @return string
308
     */
309
    public function getSource() : string
310
    {
311
        return 'users';
312
    }
313
314
    /**
315
    * Set hashtable settings table, userConfig ;).
316
    *
317
    * @return void
318
    */
319
    private function createSettingsModel(): void
0 ignored issues
show
Unused Code introduced by
The method createSettingsModel() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
320
    {
321
        $this->settingsModel = new UserConfig();
0 ignored issues
show
Bug Best Practice introduced by
The property settingsModel does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
322
    }
323
324
    /**
325
     * Get the User key for redis.
326
     *
327
     * @return string
328
     */
329
    public function getKey() : int
330
    {
331
        return $this->id;
332
    }
333
334
    /**
335
     * A company owner is the first person that register this company
336
     * This only ocurres when signing up the first time, after that all users invites
337
     * come with a default_company id attached.
338
     *
339
     * @return boolean
340
     */
341
    public function isFirstSignup(): bool
342
    {
343
        return empty($this->default_company);
344
    }
345
346
347
    /**
348
     * Get all of the subscriptions for the user.
349
     */
350
    public function subscriptions()
351
    {
352
        $this->hasMany(
353
            'id',
354
            'Canvas\Models\Subscription',
355
            'user_id',
356
            [
357
                'alias' => 'subscriptions',
358
                'params' => [
359
                    'conditions' => 'apps_id = ?0 and companies_id = ?1',
360
                    'bind' => [$this->di->getApp()->getId(), $this->default_company],
361
                    'order' => 'id DESC'
362
                ]
363
            ]
364
        );
365
366
        return $this->getRelated('subscriptions');
367
    }
368
369
    /**
370
     * Strat a free trial.
371
     *
372
     * @param Users $user
373
     * @return Subscription
374
     */
375
    public function startFreeTrial() : Subscription
376
    {
377
        $defaultPlan = AppsPlans::getDefaultPlan();
378
        $trialEndsAt = Carbon::now()->addDays($this->di->getApp()->plan->free_trial_dates);
379
380
        $subscription = new Subscription();
381
        $subscription->user_id = $this->getId();
382
        $subscription->companies_id = $this->default_company;
383
        $subscription->apps_id = $this->di->getApp()->getId();
384
        $subscription->apps_plans_id = $this->di->getApp()->default_apps_plan_id;
385
        $subscription->name = $defaultPlan->name;
386
        $subscription->stripe_id = $defaultPlan->stripe_id;
387
        $subscription->stripe_plan = $defaultPlan->stripe_plan;
388
        $subscription->quantity = 1;
389
        $subscription->trial_ends_at = $trialEndsAt->toDateTimeString();
390
        $subscription->trial_ends_days = $trialEndsAt->diffInDays(Carbon::now());
391
        $subscription->is_freetrial = 1;
392
        $subscription->is_active = 1;
393
        $subscription->saveOrFail();
394
395
        $this->trial_ends_at = $subscription->trial_ends_at;
396
        $this->updateOrFail();
397
398
        return $subscription;
399
    }
400
401
    /**
402
     * Before create.
403
     *
404
     * @return void
405
     */
406
    public function beforeCreate()
407
    {
408
        parent::beforeCreate();
409
        $random = new Random();
410
        $this->user_activation_email = $random->uuid();
411
412
        //this is only empty when creating a new user
413
        if (!$this->isFirstSignup()) {
414
            //confirm if the app reach its limit
415
            $this->isAtLimit();
416
        }
417
        
418
        $role = Roles::getByName('Admins');
419
        $this->roles_id = $role->getId();
420
    }
421
422
    /**
423
     * What the current company the users is logged in with
424
     * in this current session?
425
     *
426
     * @return integer
427
     */
428
    public function currentCompanyId(): int
429
    {
430
        $defaultCompanyId = $this->get(Companies::cacheKey());
431
        return !is_null($defaultCompanyId) ? (int) $defaultCompanyId : (int) $this->default_company;
432
    }
433
434
    /**
435
     * Overwrite the user relationship.
436
     * use Phalcon Registry to assure we mantian the same instance accross the request.
437
     */
438
    public function getDefaultCompany(): Companies
439
    {
440
        $registry = Di::getDefault()->getRegistry();
441
        $key = 'company_' . Di::getDefault()->getApp()->getId() . '_' . $this->getId();
442
        if (!isset($registry[$key])) {
443
            $registry[$key] = Companies::findFirstOrFail($this->currentCompanyId());
444
        }
445
        return  $registry[$key];
446
    }
447
448
    /**
449
     * What the current company brach the users is logged in with
450
     * in this current session?
451
     *
452
     * @return integer
453
     */
454
    public function currentCompanyBranchId(): int
455
    {
456
        return (int) $this->default_company_branch;
457
    }
458
459
    /**
460
     * What to do after the creation of a new users
461
     *  - Assign default role.
462
     *
463
     * @return void
464
     */
465
    public function afterCreate()
466
    {
467
        //need to run it here, since we overwirte the default_company id and null this function objective
468
        $isFirstSignup = $this->isFirstSignup();
469
470
        /**
471
         * if we dont find the userdata di lets create it.
472
         * @todo this is not ideal lets fix it later
473
         */
474
        if (!$this->di->has('userData')) {
475
            $this->di->setShared('userData', $this);
476
        }
477
478
        $this->fire('user:afterSignup', $this, $isFirstSignup);
479
480
        //update user activity when its not a empty user
481
        if (!$isFirstSignup) {
482
            $this->updateAppActivityLimit();
483
        }
484
    }
485
486
    /**
487
     * Upload Files.
488
     *
489
     * @todo move this to the baka class
490
     *
491
     * @return void
492
     */
493
    public function afterSave()
494
    {
495
        $this->associateFileSystem();
496
        //$this->updatePermissionRoles();
497
    }
498
499
    /**
500
     * update user role for the specific app.
501
     *
502
     * @return void
503
     */
504
    protected function updatePermissionRoles(): bool
505
    {
506
        if ($permission = $this->getPermission()) {
507
            $permission->roles_id = $this->roles_id;
508
            return $permission->updateOrFail();
509
        }
510
511
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type void.
Loading history...
512
    }
513
514
    /**
515
     * Overwrite the permission relationship to force the user of company id.
516
     *
517
     * @return UserRoles
518
     */
519
    public function getPermission()
520
    {
521
        return $this->getUserRole();
522
    }
523
524
    /**
525
     * Get the list of all the associated apps this users has.
526
     *:w.
527
     * @return array
528
     */
529
    public function getAssociatedApps(): array
530
    {
531
        $apps = $this->getApps(['columns' => 'apps_id', 'group' => 'apps_id']);
532
533
        if ($apps->count()) {
534
            return array_map(function ($apps) {
535
                return $apps['apps_id'];
536
            }, $apps->toArray());
537
        }
538
539
        return [0];
540
    }
541
542
    /**
543
     * Get an array of the associates companies Ids.
544
     *
545
     * @return array
546
     */
547
    public function getAssociatedCompanies(): array
548
    {
549
        $companies = $this->getCompanies(['columns' => 'companies_id']);
550
551
        if ($companies->count()) {
552
            return array_map(function ($company) {
553
                return $company['companies_id'];
554
            }, $companies->toArray());
555
        }
556
557
        return [0];
558
    }
559
560
    /**
561
     * Get user by key.
562
     * @param string $userActivationEmail
563
     * @return Users
564
     */
565
    public static function getByUserActivationEmail(string $userActivationEmail): Users
566
    {
567
        return self::findFirst([
568
            'conditions' => 'user_activation_email = ?0 and user_active =?1 and is_deleted = 0',
569
            'bind' => [$userActivationEmail, 1],
570
        ]);
571
    }
572
573
    /**
574
     * Overwrite the relationship.
575
     *
576
     * @return void
577
     */
578
    public function getPhoto()
579
    {
580
        return $this->getFileByName('photo');
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->getFileByName('photo') targeting Canvas\Models\Users::getFileByName() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
581
    }
582
583
    /**
584
     * Update the user current default company.
585
     *
586
     * @param integer $companyId
587
     * @return void
588
     */
589
    public function switchDefaultCompanyByBranch(int $branchId): void
590
    {
591
        if ($branch = CompaniesBranches::findFirst($branchId)) {
592
            if ($branch->company) {
593
                if ($branch->company->userAssociatedToCompany($this)) {
594
                    $this->default_company = $branch->company->getId();
0 ignored issues
show
Bug Best Practice introduced by
The property default_company does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
595
                    $this->default_company_branch = $branch->getId();
596
                    //set the default company id per the specific app , we do this so we can have multip default companies per diff apps
597
                    $this->set(Companies::cacheKey(), $this->default_company);
598
                }
599
            }
600
        }
601
    }
602
603
    /**
604
     * Update the password for a current user.
605
     *
606
     * @param string $newPassword
607
     * @return boolean
608
     */
609
    public function updatePassword(string $currentPassword, string $newPassword, string $verifyPassword) : bool
610
    {
611
        $currentPassword = trim($currentPassword);
612
        $newPassword = trim($newPassword);
613
        $verifyPassword = trim($verifyPassword);
614
615
        $app = Di::getDefault()->getApp();
616
617
        if (!$app->ecosystemAuth()) {
618
            $userAppData = $this->getApp([
619
                'conditions' => 'companies_id = :id:',
620
                'bind' => [
621
                    'id' => $this->currentCompanyId()
622
                ]
623
            ]);
624
625
            $password = $userAppData->password;
626
        } else {
627
            $password = $this->password;
628
        }
629
630
        // First off check that the current password matches the current password
631
        if (Password::check($currentPassword, $password)) {
632
            PasswordValidation::validate($newPassword, $verifyPassword);
633
634
            return $this->resetPassword($newPassword);
635
        }
636
637
        throw new Exception(_(' Your current password is incorrect .'));
638
    }
639
640
    /**
641
     * Reset the user passwrod.
642
     *
643
     * @param string $newPassword
644
     * @return bool
645
     */
646
    public function resetPassword(string $newPassword): bool
647
    {
648
        $app = Di::getDefault()->getApp();
649
650
        if (!$app->ecosystemAuth()) {
651
            //update all companies password for the current user app
652
            AppAuth::updatePassword($this, Password::make($newPassword));
653
        } else {
654
            $this->password = Password::make($newPassword);
0 ignored issues
show
Bug Best Practice introduced by
The property password does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
655
        }
656
657
        return true;
658
    }
659
660
    /**
661
     * user signup to the service.
662
     *
663
     * did we find the email?
664
     * does it have access to this app?
665
     * no?
666
     * ok lets register / associate to this app
667
     * yes?
668
     * it meas he was invites so get the fuck out?
669
     *
670
     * @return Users
671
     */
672
    public function signUp() : BakUser
673
    {
674
        $app = Di::getDefault()->getApp();
675
676
        if (!$app->ecosystemAuth()) {
677
            try {
678
                $user = self::getByEmail($this->email);
679
680
                $userAppData = $user->countApps('apps_id = ' . $this->getDI()->getDefault()->getApp()->getId());
681
682
                if ($userAppData > 0) {
683
                    throw new Exception('This email already has an account.');
684
                }
685
686
                //assign user role for the current app
687
                $user->roles_id = Roles::getByName(Roles::DEFAULT)->getId();
688
689
                $this->fire('user:afterSignup', $user, true);
690
691
                //update the passwords for the current app
692
                AppAuth::updatePassword($user, Password::make($this->password));
693
694
                //overwrite the current user object
695
                $this->id = $user->getId();
0 ignored issues
show
Bug Best Practice introduced by
The property id does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
696
                $this->email = $user->getEmail();
0 ignored issues
show
Bug Best Practice introduced by
The property email does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
697
            } catch (Exception $e) {
698
                //if we cant find the user normal signup
699
                $user = parent::signUp();
700
701
                //update all the password for the apps
702
                AppAuth::updatePassword($user, $this->password);
703
            }
704
        } else {
705
            $user = parent::signUp();
706
        }
707
708
        return $user;
709
    }
710
711
    /**
712
     * Generate new forgot password hash.
713
     *
714
     * @return string
715
     */
716
    public function generateForgotHash(): string
717
    {
718
        $this->user_activation_forgot = $this->generateActivationKey();
0 ignored issues
show
Bug Best Practice introduced by
The property user_activation_forgot does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
719
        $this->updateOrFail();
720
721
        return $this->user_activation_forgot;
722
    }
723
}
724