Failed Conditions
Push — master ( 037a94...88fa06 )
by Maximo
30s queued 12s
created

Users::generateDefaultDisplayname()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 2
nop 0
dl 0
loc 12
ccs 0
cts 0
cp 0
crap 12
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Canvas\Models;
5
6
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...
7
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...
8
use Canvas\Auth\App as AppAuth;
9
use Canvas\Contracts\Auth\UserInterface;
10
use Canvas\Contracts\Notifications\NotifiableTrait;
11
use Canvas\Hashing\Password;
12
use Canvas\Traits\EventManagerAwareTrait;
13
use Canvas\Traits\FileSystemModelTrait;
14
use Canvas\Traits\PermissionsTrait;
15
use Canvas\Traits\SubscriptionPlanLimitTrait;
16
use Canvas\Validations\PasswordValidation;
17
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...
18
use Exception;
19
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...
20
use Phalcon\Di;
21
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...
22
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...
23
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...
24
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...
25
use Phalcon\Validation\Validator\Uniqueness;
26
27
/**
28
 * Class Users.
29
 *
30
 * @package Canvas\Models
31
 *
32
 * @property Users $user
33
 * @property Config $config
34
 * @property Apps $app
35
 * @property Companies $defaultCompany
36
 * @property \Phalcon\Di $di
37
 */
38
class Users extends BakUser implements UserInterface
39
{
40
    use PermissionsTrait;
41
    use Billable;
42
    use SubscriptionPlanLimitTrait;
43
    use FileSystemModelTrait;
44
    use HashTableTrait;
45
    use NotifiableTrait;
46
    use EventManagerAwareTrait;
47
48
    /**
49
     * Description.
50
     *
51
     * @var integer
52
     */
53
    public $description;
54
55
    /**
56
     * Default Company Branch.
57
     *
58
     * @var integer
59
     */
60
    public $default_company_branch;
61
62
    /**
63
     * Roles id.
64
     *
65
     * @var integer
66
     */
67
    public $roles_id;
68
69
    /**
70
     * Stripe id.
71
     *
72
     * @var string
73
     */
74
    public $stripe_id;
75
76
    /**
77
     * Card last four numbers.
78
     *
79
     * @var integer
80
     */
81
    public $card_last_four;
82
83
    /**
84
     * Card Brand.
85
     *
86
     * @var integer
87
     */
88
    public $card_brand;
89
90
    /**
91
     * Trial end date.
92
     *
93
     * @var string
94
     */
95
    public $trial_ends_at;
96
97
    /**
98
     * Provide the app plan id
99
     * if the user is signing up a new company.
100
     *
101
     * @var integer
102
     */
103
    public $appPlanId = null;
104
105
    /**
106
     * Active subscription id.Not an actual table field, used temporarily.
107
     *
108
     * @var string
109
     */
110
    public $active_subscription_id;
111
112
    /**
113
     * System Module Id.
114
     *
115
     * @var integer
116
     */
117
    public $system_modules_id = 2;
118
119
    /**
120
     * User email activation code.
121
     *
122
     * @var string
123
     */
124
    public $user_activation_email;
125
126
    /**
127
     * Initialize method for model.
128
     */
129
    public function initialize()
130
    {
131
        $this->setSource('users');
132
133
        //overwrite parent relationships
134
        $this->hasOne('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'session']);
135
        $this->hasMany('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'sessions']);
136
        $this->hasMany('id', 'Baka\Auth\Models\SessionKeys', 'users_id', ['alias' => 'sessionKeys']);
137
        $this->hasMany('id', 'Baka\Auth\Models\Banlist', 'users_id', ['alias' => 'bans']);
138
        $this->hasMany('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'sessions']);
139
        $this->hasMany('id', 'Canvas\Models\UserConfig', 'users_id', ['alias' => 'config']);
140
        $this->hasMany('id', 'Canvas\Models\UserLinkedSources', 'users_id', ['alias' => 'sources']);
141
142
        $this->hasOne(
143
            'default_company',
144
            'Canvas\Models\Companies',
145
            'id',
146
            ['alias' => 'defaultCompany']
147
        );
148
149
        $this->hasOne(
150
            'default_company',
151
            'Canvas\Models\Companies',
152
            'id',
153
            ['alias' => 'currentCompany']
154
        );
155
156
        $this->hasMany(
157
            'id',
158
            'Canvas\Models\Subscription',
159
            'user_id',
160
            [
161
                'alias' => 'allSubscriptions',
162
                'params' => [
163
                    'conditions' => 'apps_id = ?0',
164
                    'bind' => [$this->di->getApp()->getId()],
165
                    'order' => 'id DESC'
166
                ]
167
            ]
168
        );
169
170
        $this->hasMany(
171
            'id',
172
            'Canvas\Models\UsersAssociatedApps',
173
            'users_id',
174
            [
175
                'alias' => 'companies',
176
                'params' => [
177
                    'conditions' => 'apps_id = ?0',
178
                    'bind' => [$this->di->getApp()->getId()],
179
                ]
180
            ]
181
        );
182
183
        $this->hasMany(
184
            'id',
185
            'Canvas\Models\UsersAssociatedApps',
186
            'users_id',
187
            [
188
                'alias' => 'apps',
189
            ]
190
        );
191
192
        $this->hasOne(
193
            'id',
194
            'Canvas\Models\UsersAssociatedApps',
195
            'users_id',
196
            [
197
                'alias' => 'app',
198
                'params' => [
199
                    'conditions' => 'apps_id = ?0',
200
                    'bind' => [Di::getDefault()->getApp()->getId()]
201
                ]
202
            ]
203
        );
204
205
        $this->hasMany(
206
            'id',
207
            'Canvas\Models\UserWebhooks',
208
            'users_id',
209
            ['alias' => 'userWebhook']
210
        );
211
212
        $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

212
        $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...
213
        $this->hasOne(
214
            'id',
215
            'Canvas\Models\FileSystemEntities',
216
            'entity_id',
217
            [
218
                'alias' => 'files',
219
                'params' => [
220
                    'conditions' => 'system_modules_id = ?0',
221
                    'bind' => [$systemModule->getId()]
222
                ]
223
            ]
224
        );
225
    }
226
227
    /**
228
     * Initialize relationshit after fetch
229
     * since we need company id info.
230
     *
231
     * @return void
232
     */
233
    public function afterFetch()
234
    {
235
        $this->hasManyToMany(
236
            'id',
237
            'Canvas\Models\UserRoles',
238
            'users_id',
239
            'roles_id',
240
            'Canvas\Models\Roles',
241
            'id',
242
            [
243
                'alias' => 'roles',
244
                'params' => [
245
                    'limit' => 1,
246
                    'conditions' => 'Canvas\Models\UserRoles.apps_id = ' . $this->di->getApp()->getId() . ' AND Canvas\Models\UserRoles.companies_id = ' . $this->currentCompanyId(),
247
                    'order' => 'Canvas\Models\UserRoles.apps_id desc',
248
                ]
249
            ]
250
        );
251
252
        $this->hasOne(
253
            'id',
254
            'Canvas\Models\UserRoles',
255
            'users_id',
256
            [
257
                'alias' => 'userRole',
258
                'params' => [
259
                    'limit' => 1,
260
                    'conditions' => 'Canvas\Models\UserRoles.apps_id in (?0, ?1) AND Canvas\Models\UserRoles.companies_id = ' . $this->currentCompanyId(),
261
                    'bind' => [$this->di->getApp()->getId(), Roles::DEFAULT_ACL_APP_ID],
262
                    'order' => 'apps_id desc',
263
                ]
264
            ]
265
        );
266
267
        $this->hasMany(
268
            'id',
269
            'Canvas\Models\UserRoles',
270
            'users_id',
271
            [
272
                'alias' => 'permissions',
273
                'params' => [
274
                    'conditions' => 'Canvas\Models\UserRoles.apps_id = ' . $this->di->getApp()->getId() . ' AND Canvas\Models\UserRoles.companies_id = ' . $this->currentCompanyId(),
275
                ]
276
            ]
277
        );
278
    }
279
280
    /**
281
     * Validations and business logic.
282
     */
283
    public function validation()
284
    {
285
        $validator = new Validation();
286
        $validator->add(
287
            'email',
288
            new Email([
289
                'field' => 'email',
290
                'required' => true,
291
            ])
292
        );
293
294
        $validator->add(
295
            'displayname',
296
            new PresenceOf([
297
                'field' => 'displayname',
298
                'required' => true,
299
            ])
300
        );
301
302
        // Unique values
303
        $validator->add(
304
            'email',
305
            new Uniqueness([
306
                'field' => 'email',
307
                'message' => _('This email already has an account.'),
308
            ])
309
        );
310
311
        return $this->validate($validator);
312
    }
313
314
    /**
315
     * Returns table name mapped in the model.
316
     *
317
     * @return string
318
     */
319
    public function getSource() : string
320
    {
321
        return 'users';
322
    }
323
324
    /**
325
     * Set hashtable settings table, userConfig ;).
326
     *
327
     * @return void
328
     */
329
    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...
330
    {
331
        $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...
332
    }
333
334
    /**
335
     * Get the User key for redis.
336
     *
337
     * @return string
338
     */
339
    public function getKey() : int
340
    {
341
        return $this->id;
342
    }
343
344
    /**
345
     * A company owner is the first person that register this company
346
     * This only ocurres when signing up the first time, after that all users invites
347
     * come with a default_company id attached.
348
     *
349
     * @return boolean
350
     */
351
    public function isFirstSignup() : bool
352
    {
353
        return empty($this->default_company);
354
    }
355
356
    /**
357
     * Get all of the subscriptions for the user.
358
     */
359
    public function subscriptions()
360
    {
361
        $this->hasMany(
362
            'id',
363
            'Canvas\Models\Subscription',
364
            'user_id',
365
            [
366
                'alias' => 'subscriptions',
367
                'params' => [
368
                    'conditions' => 'apps_id = ?0 and companies_id = ?1',
369
                    'bind' => [$this->di->getApp()->getId(), $this->default_company],
370
                    'order' => 'id DESC'
371
                ]
372
            ]
373
        );
374
375
        return $this->getRelated('subscriptions');
376
    }
377
378
    /**
379
     * Strat a free trial.
380
     *
381
     * @param Users $user
382
     *
383
     * @return Subscription
384
     */
385
    public function startFreeTrial() : Subscription
386
    {
387
        $defaultPlan = AppsPlans::getDefaultPlan();
388
        $trialEndsAt = Carbon::now()->addDays($this->di->getApp()->plan->free_trial_dates);
389
390
        $subscription = new Subscription();
391
        $subscription->user_id = $this->getId();
392
        $subscription->companies_id = $this->default_company;
393
        $subscription->apps_id = $this->di->getApp()->getId();
394
        $subscription->apps_plans_id = $this->di->getApp()->default_apps_plan_id;
395
        $subscription->name = $defaultPlan->name;
396
        $subscription->stripe_id = $defaultPlan->stripe_id;
397
        $subscription->stripe_plan = $defaultPlan->stripe_plan;
398
        $subscription->quantity = 1;
399
        $subscription->trial_ends_at = $trialEndsAt->toDateTimeString();
400
        $subscription->trial_ends_days = $trialEndsAt->diffInDays(Carbon::now());
401
        $subscription->is_freetrial = 1;
402
        $subscription->is_active = 1;
403
        $subscription->saveOrFail();
404
405
        $this->trial_ends_at = $subscription->trial_ends_at;
406
        $this->updateOrFail();
407
408
        return $subscription;
409
    }
410
411
    /**
412
     * Before create.
413
     *
414
     * @return void
415
     */
416
    public function beforeCreate()
417
    {
418
        parent::beforeCreate();
419
        $random = new Random();
420
        $this->user_activation_email = $random->uuid();
421
422
        //this is only empty when creating a new user
423
        if (!$this->isFirstSignup()) {
424
            //confirm if the app reach its limit
425
            $this->isAtLimit();
426
        }
427
428
        $role = Roles::getByName('Admins');
429
        $this->roles_id = $role->getId();
430
    }
431
432
    /**
433
     * What the current company the users is logged in with
434
     * in this current session?
435
     *
436
     * @return integer
437
     */
438
    public function currentCompanyId() : int
439
    {
440
        $defaultCompanyId = $this->get(Companies::cacheKey());
441
        return !is_null($defaultCompanyId) ? (int) $defaultCompanyId : (int) $this->default_company;
442
    }
443
444
    /**
445
     * Overwrite the user relationship.
446
     * use Phalcon Registry to assure we mantian the same instance accross the request.
447
     */
448
    public function getDefaultCompany() : Companies
449
    {
450
        $registry = Di::getDefault()->getRegistry();
451
        $key = 'company_' . Di::getDefault()->getApp()->getId() . '_' . $this->getId();
452
        if (!isset($registry[$key])) {
453
            $registry[$key] = Companies::findFirstOrFail($this->currentCompanyId());
454
        }
455
        return  $registry[$key];
456
    }
457
458
    /**
459
     * What the current company brach the users is logged in with
460
     * in this current session?
461
     *
462
     * @return integer
463
     */
464
    public function currentCompanyBranchId() : int
465
    {
466
        return (int) $this->default_company_branch;
467
    }
468
469
    /**
470
     * What to do after the creation of a new users
471
     *  - Assign default role.
472
     *
473
     * @return void
474
     */
475
    public function afterCreate()
476
    {
477
        //need to run it here, since we overwirte the default_company id and null this function objective
478
        $isFirstSignup = $this->isFirstSignup();
479
480
        /**
481
         * if we dont find the userdata di lets create it.
482
         *
483
         * @todo this is not ideal lets fix it later
484
         */
485
        if (!$this->di->has('userData')) {
486
            $this->di->setShared('userData', $this);
487
        }
488
489
        $this->fire('user:afterSignup', $this, $isFirstSignup);
490
491
        //update user activity when its not a empty user
492
        if (!$isFirstSignup) {
493
            $this->updateAppActivityLimit();
494
        }
495
    }
496
497
    /**
498
     * Upload Files.
499
     *
500
     * @todo move this to the baka class
501
     *
502
     * @return void
503
     */
504
    public function afterSave()
505
    {
506
        $this->associateFileSystem();
507
        //$this->updatePermissionRoles();
508
    }
509
510
    /**
511
     * update user role for the specific app.
512
     *
513
     * @return void
514
     */
515
    protected function updatePermissionRoles() : bool
516
    {
517
        if ($permission = $this->getPermission()) {
518
            $permission->roles_id = $this->roles_id;
519
            return $permission->updateOrFail();
520
        }
521
522
        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...
523
    }
524
525
    /**
526
     * Overwrite the permission relationship to force the user of company id.
527
     *
528
     * @return UserRoles
529
     */
530
    public function getPermission()
531
    {
532
        return $this->getUserRole();
533
    }
534
535
    /**
536
     * Get the list of all the associated apps this users has.
537
     *:w.
538
     *
539
     * @return array
540
     */
541
    public function getAssociatedApps() : array
542
    {
543
        $apps = $this->getApps(['columns' => 'apps_id', 'group' => 'apps_id']);
544
545
        if ($apps->count()) {
546
            return array_map(function ($apps) {
547
                return $apps['apps_id'];
548
            }, $apps->toArray());
549
        }
550
551
        return [0];
552
    }
553
554
    /**
555
     * Get an array of the associates companies Ids.
556
     *
557
     * @return array
558
     */
559
    public function getAssociatedCompanies() : array
560
    {
561
        $companies = $this->getCompanies(['columns' => 'companies_id']);
562
563
        if ($companies->count()) {
564
            return array_map(function ($company) {
565
                return $company['companies_id'];
566
            }, $companies->toArray());
567
        }
568
569
        return [0];
570
    }
571
572
    /**
573
     * Get user by key.
574
     *
575
     * @param string $userActivationEmail
576
     *
577
     * @return Users
578
     */
579
    public static function getByUserActivationEmail(string $userActivationEmail) : Users
580
    {
581
        return self::findFirst([
582
            'conditions' => 'user_activation_email = ?0 and user_active =?1 and is_deleted = 0',
583
            'bind' => [$userActivationEmail, 1],
584
        ]);
585
    }
586
587
    /**
588
     * Overwrite the relationship.
589
     *
590
     * @return void
591
     */
592
    public function getPhoto()
593
    {
594
        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...
595
    }
596
597
    /**
598
     * Update the user current default company.
599
     *
600
     * @param int $companyId
601
     *
602
     * @return void
603
     */
604
    public function switchDefaultCompanyByBranch(int $branchId) : void
605
    {
606
        if ($branch = CompaniesBranches::findFirst($branchId)) {
607
            if ($branch->company) {
608
                if ($branch->company->userAssociatedToCompany($this)) {
609
                    $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...
610
                    $this->default_company_branch = $branch->getId();
611
                    //set the default company id per the specific app , we do this so we can have multip default companies per diff apps
612
                    $this->set(Companies::cacheKey(), $this->default_company);
613
                }
614
            }
615
        }
616
    }
617
618
    /**
619
     * Update the password for a current user.
620
     *
621
     * @param string $newPassword
622
     *
623
     * @return boolean
624
     */
625
    public function updatePassword(string $currentPassword, string $newPassword, string $verifyPassword) : bool
626
    {
627
        $currentPassword = trim($currentPassword);
628
        $newPassword = trim($newPassword);
629
        $verifyPassword = trim($verifyPassword);
630
631
        $app = Di::getDefault()->getApp();
632
633
        if (!$app->ecosystemAuth()) {
634
            $userAppData = $this->getApp([
635
                'conditions' => 'companies_id = :id:',
636
                'bind' => [
637
                    'id' => $this->currentCompanyId()
638
                ]
639
            ]);
640
641
            $password = $userAppData->password;
642
        } else {
643
            $password = $this->password;
644
        }
645
646
        // First off check that the current password matches the current password
647
        if (Password::check($currentPassword, $password)) {
648
            PasswordValidation::validate($newPassword, $verifyPassword);
649
650
            return $this->resetPassword($newPassword);
651
        }
652
653
        throw new Exception(_(' Your current password is incorrect .'));
654
    }
655
656
    /**
657
     * Reset the user passwrod.
658
     *
659
     * @param string $newPassword
660
     *
661
     * @return bool
662
     */
663
    public function resetPassword(string $newPassword) : bool
664
    {
665
        $app = Di::getDefault()->getApp();
666
667
        if (!$app->ecosystemAuth()) {
668
            //update all companies password for the current user app
669
            AppAuth::updatePassword($this, Password::make($newPassword));
670
        } else {
671
            $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...
672
        }
673
674
        return true;
675
    }
676
677
    /**
678
     * user signup to the service.
679
     *
680
     * did we find the email?
681
     * does it have access to this app?
682
     * no?
683
     * ok lets register / associate to this app
684
     * yes?
685
     * it meas he was invites so get the fuck out?
686
     *
687
     * @return Users
688
     */
689
    public function signUp() : BakUser
690
    {
691
        $app = Di::getDefault()->getApp();
692
693
        if (!$app->ecosystemAuth()) {
694
            try {
695
                $user = self::getByEmail($this->email);
696
697
                $userAppData = $user->countApps('apps_id = ' . $this->getDI()->getDefault()->getApp()->getId());
698
699
                if ($userAppData > 0) {
700
                    throw new Exception('This email already has an account.');
701
                }
702
703
                //assign user role for the current app
704
                $user->roles_id = Roles::getByName(Roles::DEFAULT)->getId();
705
706
                $this->fire('user:afterSignup', $user, true);
707
708
                //update the passwords for the current app
709
                AppAuth::updatePassword($user, Password::make($this->password));
710
711
                //overwrite the current user object
712
                $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...
713
                $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...
714
            } catch (Exception $e) {
715
                //if we cant find the user normal signup
716
                $user = parent::signUp();
717
718
                //update all the password for the apps
719
                AppAuth::updatePassword($user, $this->password);
720
            }
721
        } else {
722
            $user = parent::signUp();
723
        }
724
725
        return $user;
726
    }
727
728
    /**
729
     * Generate new forgot password hash.
730
     *
731
     * @return string
732
     */
733
    public function generateForgotHash() : string
734
    {
735
        $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...
736
        $this->updateOrFail();
737
738
        return $this->user_activation_forgot;
739
    }
740
741
    /**
742
     * Generate a default displayname by firstname and lastname.
743
     * If firstname is set to the name of app then generate a random displayname.
744
     *
745
     * @return string
746
     */
747
    public function generateDefaultDisplayname() : string
748
    {
749
        if (empty($this->firstname) && empty($this->lastname)) {
750
            $appName = Di::getDefault()->getApp()->name;
751
            $random = new Random();
752
            $this->lastname = 'User';
0 ignored issues
show
Bug Best Practice introduced by
The property lastname does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
753
            $this->firstname = $appName;
0 ignored issues
show
Bug Best Practice introduced by
The property firstname does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
754
755
            return  $appName . $random->number(99999999);
756
        }
757
758
        return $this->firstname . '.' . $this->lastname;
759
    }
760
}
761