Failed Conditions
Pull Request — master (#317)
by Rafael
02:57
created

Users::getAssociatedApps()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 12
ccs 0
cts 8
cp 0
crap 6
rs 9.8666
c 0
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;
9
use Carbon\Carbon;
10
use Phalcon\Validation;
11
use Phalcon\Validation\Validator\Email;
12
use Phalcon\Validation\Validator\PresenceOf;
13
use Phalcon\Validation\Validator\Regex;
14
use Phalcon\Validation\Validator\Uniqueness;
15
use Canvas\Traits\FileSystemModelTrait;
16
use Phalcon\Security\Random;
17
use Baka\Database\Contracts\HashTableTrait;
18
use Canvas\Contracts\Notifications\NotifiableTrait;
19
use Canvas\Traits\EventManagerAwareTrait;
20
use Phalcon\Di;
21
use Canvas\Auth\App as AppAuth;
22
use Exception;
23
use Canvas\Validations\PasswordValidation;
24
use Baka\Auth\Models\Users as BakUser;
25
use Canvas\Hashing\Password;
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 \Baka\Auth\Models\Users
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
     * Default Company Branch.
50
     *
51
     * @var integer
52
     */
53
    public $default_company_branch;
0 ignored issues
show
Coding Style introduced by
$default_company_branch does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
54
55
    /**
56
     * Roles id.
57
     *
58
     * @var integer
59
     */
60
    public $roles_id;
0 ignored issues
show
Coding Style introduced by
$roles_id does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
61
62
    /**
63
     * Stripe id.
64
     *
65
     * @var string
66
     */
67
    public $stripe_id;
0 ignored issues
show
Coding Style introduced by
$stripe_id does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
68
69
    /**
70
     * Card last four numbers.
71
     *
72
     * @var integer
73
     */
74
    public $card_last_four;
0 ignored issues
show
Coding Style introduced by
$card_last_four does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
75
76
    /**
77
     * Card Brand.
78
     *
79
     * @var integer
80
     */
81
    public $card_brand;
0 ignored issues
show
Coding Style introduced by
$card_brand does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
82
83
    /**
84
     * Trial end date.
85
     *
86
     * @var string
87
     */
88
    public $trial_ends_at;
0 ignored issues
show
Coding Style introduced by
$trial_ends_at does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
89
90
    /**
91
     * Provide the app plan id
92
     * if the user is signing up a new company.
93
     *
94
     * @var integer
95
     */
96
    public $appPlanId = null;
97
98
    /**
99
     * Active subscription id.Not an actual table field, used temporarily.
100
     * @var string
101
     */
102
    public $active_subscription_id;
0 ignored issues
show
Coding Style introduced by
$active_subscription_id does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
103
104
    /**
105
     * System Module Id.
106
     * @var integer
107
     */
108
    public $system_modules_id = 2;
0 ignored issues
show
Coding Style introduced by
$system_modules_id does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
109
110
    /**
111
     * User email activation code.
112
     *
113
     * @var string
114
     */
115
    public $user_activation_email;
0 ignored issues
show
Coding Style introduced by
$user_activation_email does not seem to conform to the naming convention (^[a-z][a-zA-Z0-9]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
116
117
    /**
118
     * Initialize method for model.
119
     */
120
    public function initialize()
121
    {
122
        $this->setSource('users');
123
124
        //overwrite parent relationships
125
        $this->hasOne('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'session']);
126
        $this->hasMany('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'sessions']);
127
        $this->hasMany('id', 'Baka\Auth\Models\SessionKeys', 'users_id', ['alias' => 'sessionKeys']);
128
        $this->hasMany('id', 'Baka\Auth\Models\Banlist', 'users_id', ['alias' => 'bans']);
129
        $this->hasMany('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'sessions']);
130
        $this->hasMany('id', 'Canvas\Models\UserConfig', 'users_id', ['alias' => 'config']);
131
        $this->hasMany('id', 'Canvas\Models\UserLinkedSources', 'users_id', ['alias' => 'sources']);
132
133
        $this->hasOne(
134
            'default_company',
135
            'Canvas\Models\Companies',
136
            'id',
137
            ['alias' => 'defaultCompany']
138
        );
139
140
        $this->hasOne(
141
            'default_company',
142
            'Canvas\Models\Companies',
143
            'id',
144
            ['alias' => 'currentCompany']
145
        );
146
147
        $this->hasMany(
148
            'id',
149
            'Canvas\Models\Subscription',
150
            'user_id',
151
            [
152
                'alias' => 'allSubscriptions',
153
                'params' => [
154
                    'conditions' => 'apps_id = ?0',
155
                    'bind' => [$this->di->getApp()->getId()],
156
                    'order' => 'id DESC'
157
                ]
158
            ]
159
        );
160
161
        $this->hasMany(
162
            'id',
163
            'Canvas\Models\UsersAssociatedApps',
164
            'users_id',
165
            [
166
                'alias' => 'companies',
167
                'params' => [
168
                    'conditions' => 'apps_id = ?0',
169
                    'bind' => [$this->di->getApp()->getId()],
170
                ]
171
            ]
172
        );
173
174
        $this->hasMany(
175
            'id',
176
            'Canvas\Models\UsersAssociatedApps',
177
            'users_id',
178
            [
179
                'alias' => 'apps',
180
            ]
181
        );
182
183
        $this->hasOne(
184
            'id',
185
            'Canvas\Models\UsersAssociatedApps',
186
            'users_id',
187
            [
188
                'alias' => 'app',
189
                'params' => [
190
                    'conditions' => 'apps_id = ?0',
191
                    'bind' => [Di::getDefault()->getApp()->getId()]
192
                ]
193
            ]
194
        );
195
196
        $this->hasMany(
197
            'id',
198
            'Canvas\Models\UserWebhooks',
199
            'users_id',
200
            ['alias' => 'userWebhook']
201
        );
202
203
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
0 ignored issues
show
Deprecated Code introduced by
The method Canvas\Models\SystemModu...stemModuleByModelName() has been deprecated with message: v2

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

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

Loading history...
204
        $this->hasOne(
205
            'id',
206
            'Canvas\Models\FileSystemEntities',
207
            'entity_id',
208
            [
209
                'alias' => 'files',
210
                'params' => [
211
                    'conditions' => 'system_modules_id = ?0',
212
                    'bind' => [$systemModule->getId()]
213
                ]
214
            ]
215
        );
216
217
        $this->hasOne(
218
            'id',
219
            'Canvas\Models\FileSystemEntities',
220
            'entity_id',
221
            [
222
                'alias' => 'photo',
223
                'params' => [
224
                    'conditions' => 'system_modules_id = ?0',
225
                    'bind' => [$systemModule->getId()]
226
                ]
227
            ]
228
        );
229
    }
230
231
    /**
232
     * Initialize relationshit after fetch
233
     * since we need company id info.
234
     *
235
     * @return void
236
     */
237
    public function afterFetch()
238
    {
239
        $this->hasManyToMany(
240
            'id',
241
            'Canvas\Models\UserRoles',
242
            'users_id',
243
            'roles_id',
244
            'Canvas\Models\Roles',
245
            'id',
246
            [
247
                'alias' => 'roles',
248
                'params' => [
249
                    'limit' => 1,
250
                    'conditions' => 'Canvas\Models\UserRoles.apps_id = ' . $this->di->getApp()->getId() . ' AND Canvas\Models\UserRoles.companies_id = ' . $this->currentCompanyId(),
251
                    'order' => 'Canvas\Models\UserRoles.apps_id desc',
252
                ]
253
            ]
254
        );
255
256
        $this->hasOne(
257
            'id',
258
            'Canvas\Models\UserRoles',
259
            'users_id',
260
            [
261
                'alias' => 'userRole',
262
                'params' => [
263
                    'limit' => 1,
264
                    'conditions' => 'Canvas\Models\UserRoles.apps_id in (?0, ?1) AND Canvas\Models\UserRoles.companies_id = ' . $this->currentCompanyId(),
265
                    'bind' => [$this->di->getApp()->getId(), Roles::DEFAULT_ACL_APP_ID],
266
                    'order' => 'apps_id desc',
267
                ]
268
            ]
269
        );
270
271
        $this->hasMany(
272
            'id',
273
            'Canvas\Models\UserRoles',
274
            'users_id',
275
            [
276
                'alias' => 'permissions',
277
                'params' => [
278
                    'conditions' => 'Canvas\Models\UserRoles.apps_id = ' . $this->di->getApp()->getId() . ' AND Canvas\Models\UserRoles.companies_id = ' . $this->currentCompanyId(),
279
                ]
280
            ]
281
        );
282
    }
283
284
    /**
285
     * Validations and business logic.
286
     */
287
    public function validation()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
288
    {
289
        $validator = new Validation();
290
        $validator->add(
291
            'email',
292
            new Email([
293
                'field' => 'email',
294
                'required' => true,
295
            ])
296
        );
297
298
        $validator->add(
299
            'displayname',
300
            new PresenceOf([
301
                'field' => 'displayname',
302
                'required' => true,
303
            ])
304
        );
305
306
        // Unique values
307
        $validator->add(
308
            'email',
309
            new Uniqueness([
310
                'field' => 'email',
311
                'message' => _('This email already has an account.'),
312
            ])
313
        );
314
315
        return $this->validate($validator);
316
    }
317
318
    /**
319
     * Returns table name mapped in the model.
320
     *
321
     * @return string
322
     */
323
    public function getSource() : string
324
    {
325
        return 'users';
326
    }
327
328
    /**
329
    * Set hashtable settings table, userConfig ;).
330
    *
331
    * @return void
332
    */
333
    private function createSettingsModel(): void
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
334
    {
335
        $this->settingsModel = new UserConfig();
336
    }
337
338
    /**
339
     * Get the User key for redis.
340
     *
341
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be integer?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
342
     */
343
    public function getKey() : int
344
    {
345
        return $this->id;
346
    }
347
348
    // /**
349
    //  * A company owner is the first person that register this company
350
    //  * This only ocurres when signing up the first time, after that all users invites
351
    //  * come with a default_company id attached.
352
    //  *
353
    //  * @return boolean
354
    //  */
355
    // public function isFirstSignup(): bool
356
    // {
357
    //     return empty($this->default_company);
358
    // }
359
360
    /**
361
     * Does the user have a role assign to him?
362
     *
363
     * @return boolean
364
     */
365
    public function hasRole(): bool
366
    {
367
        return !empty($this->roles_id);
368
    }
369
370
    /**
371
     * Get all of the subscriptions for the user.
372
     */
373
    public function subscriptions()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
374
    {
375
        $this->hasMany(
376
            'id',
377
            'Canvas\Models\Subscription',
378
            'user_id',
379
            [
380
                'alias' => 'subscriptions',
381
                'params' => [
382
                    'conditions' => 'apps_id = ?0 and companies_id = ?1',
383
                    'bind' => [$this->di->getApp()->getId(), $this->default_company],
384
                    'order' => 'id DESC'
385
                ]
386
            ]
387
        );
388
389
        return $this->getRelated('subscriptions');
390
    }
391
392
    /**
393
     * Strat a free trial.
394
     *
395
     * @param Users $user
0 ignored issues
show
Bug introduced by
There is no parameter named $user. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
396
     * @return Subscription
397
     */
398
    public function startFreeTrial() : Subscription
399
    {
400
        $defaultPlan = AppsPlans::getDefaultPlan();
401
        $trialEndsAt = Carbon::now()->addDays($this->di->getApp()->plan->free_trial_dates);
402
403
        $subscription = new Subscription();
404
        $subscription->user_id = $this->getId();
405
        $subscription->companies_id = $this->default_company;
406
        $subscription->apps_id = $this->di->getApp()->getId();
407
        $subscription->apps_plans_id = $this->di->getApp()->default_apps_plan_id;
408
        $subscription->name = $defaultPlan->name;
409
        $subscription->stripe_id = $defaultPlan->stripe_id;
410
        $subscription->stripe_plan = $defaultPlan->stripe_plan;
411
        $subscription->quantity = 1;
412
        $subscription->trial_ends_at = $trialEndsAt->toDateTimeString();
413
        $subscription->trial_ends_days = $trialEndsAt->diffInDays(Carbon::now());
414
        $subscription->is_freetrial = 1;
415
        $subscription->is_active = 1;
416
        $subscription->saveOrFail();
417
418
        $this->trial_ends_at = $subscription->trial_ends_at;
419
        $this->updateOrFail();
420
421
        return $subscription;
422
    }
423
424
    /**
425
     * Before create.
426
     *
427
     * @return void
428
     */
429
    public function beforeCreate()
430
    {
431
        parent::beforeCreate();
432
        $random = new Random();
433
        $this->user_activation_email = $random->uuid();
434
435
        //this is only empty when creating a new user
436
        if (!$this->isFirstSignup()) {
437
            //confirm if the app reach its limit
438
            $this->isAtLimit();
439
        }
440
441
        //Assign admin role to the system if we dont get a specify role
442
        if (!$this->hasRole()) {
443
            $role = Roles::getByName('Admins');
444
            $this->roles_id = $role->getId();
445
        }
446
    }
447
448
    /**
449
     * What the current company the users is logged in with
450
     * in this current session?
451
     *
452
     * @return integer
453
     */
454
    public function currentCompanyId(): int
455
    {
456
        $defaultCompanyId = $this->get(Companies::cacheKey());
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $defaultCompanyId is correct as $this->get(\Canvas\Models\Companies::cacheKey()) (which targets Baka\Database\Contracts\HashTableTrait::get()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

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

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

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

Loading history...
457
        return !is_null($defaultCompanyId) ? (int) $defaultCompanyId : (int) $this->default_company;
458
    }
459
460
    /**
461
     * Overwrite the user relationship.
462
     * use Phalcon Registry to assure we mantian the same instance accross the request.
463
     */
464
    public function getDefaultCompany(): Companies
465
    {
466
        $registry = Di::getDefault()->getRegistry();
467
        $key = 'company_' . Di::getDefault()->getApp()->getId() . '_' . $this->getId();
468
        if (!isset($registry[$key])) {
469
            $registry[$key] = Companies::findFirstOrFail($this->currentCompanyId());
470
        }
471
        return  $registry[$key];
472
    }
473
474
    /**
475
     * What the current company brach the users is logged in with
476
     * in this current session?
477
     *
478
     * @return integer
479
     */
480
    public function currentCompanyBranchId(): int
481
    {
482
        return (int) $this->default_company_branch;
483
    }
484
485
    /**
486
     * What to do after the creation of a new users
487
     *  - Assign default role.
488
     *
489
     * @return void
490
     */
491
    public function afterCreate()
492
    {
493
        //need to run it here, since we overwirte the default_company id and null this function objective
494
        $isFirstSignup = $this->isFirstSignup();
495
496
        /**
497
         * if we dont find the userdata di lets create it.
498
         * @todo this is not ideal lets fix it later
499
         */
500
        if (!$this->di->has('userData')) {
501
            $this->di->setShared('userData', $this);
502
        }
503
504
        $this->fire('user:afterSignup', $this, $isFirstSignup);
505
506
        //update user activity when its not a empty user
507
        if (!$isFirstSignup) {
508
            $this->updateAppActivityLimit();
509
        }
510
    }
511
512
    /**
513
     * Upload Files.
514
     *
515
     * @todo move this to the baka class
516
     *
517
     * @return void
518
     */
519
    public function afterSave()
520
    {
521
        $this->associateFileSystem();
522
        //$this->updatePermissionRoles();
523
    }
524
525
    /**
526
     * update user role for the specific app.
527
     *
528
     * @return void
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
529
     */
530
    protected function updatePermissionRoles(): bool
0 ignored issues
show
Coding Style introduced by
function updatePermissionRoles() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
531
    {
532
        if ($permission = $this->getPermission()) {
533
            $permission->roles_id = $this->roles_id;
534
            return $permission->updateOrFail();
535
        }
536
537
        return false;
538
    }
539
540
    /**
541
     * Overwrite the permission relationship to force the user of company id.
542
     *
543
     * @return UserRoles
544
     */
545
    public function getPermission()
546
    {
547
        return $this->getUserRole();
548
    }
549
550
    /**
551
     * Get the list of all the associated apps this users has.
552
     *:w.
553
     * @return array
554
     */
555
    public function getAssociatedApps(): array
556
    {
557
        $apps = $this->getApps(['columns' => 'apps_id', 'group' => 'apps_id']);
558
559
        if ($apps->count()) {
560
            return array_map(function ($apps) {
561
                return $apps['apps_id'];
562
            }, $apps->toArray());
563
        }
564
565
        return [0];
566
    }
567
568
    /**
569
     * Get an array of the associates companies Ids.
570
     *
571
     * @return array
572
     */
573
    public function getAssociatedCompanies(): array
574
    {
575
        $companies = $this->getCompanies(['columns' => 'companies_id']);
576
577
        if ($companies->count()) {
578
            return array_map(function ($company) {
579
                return $company['companies_id'];
580
            }, $companies->toArray());
581
        }
582
583
        return [0];
584
    }
585
586
    /**
587
     * Get user by key.
588
     * @param string $userActivationEmail
589
     * @return Users
590
     */
591
    public static function getByUserActivationEmail(string $userActivationEmail): Users
592
    {
593
        return self::findFirst([
594
            'conditions' => 'user_activation_email = ?0 and user_active =?1 and is_deleted = 0',
595
            'bind' => [$userActivationEmail, 1],
596
        ]);
597
    }
598
599
    /**
600
     * Overwrite the relationship.
601
     *
602
     * @return void
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
603
     */
604
    public function getPhoto()
605
    {
606
        return $this->getFileByName('photo');
607
    }
608
609
    /**
610
     * Update the user current default company.
611
     *
612
     * @param integer $companyId
0 ignored issues
show
Bug introduced by
There is no parameter named $companyId. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
613
     * @return void
614
     */
615
    public function switchDefaultCompanyByBranch(int $branchId): void
616
    {
617
        if ($branch = CompaniesBranches::findFirst($branchId)) {
618
            if ($branch->company) {
619
                if ($branch->company->userAssociatedToCompany($this)) {
620
                    $this->default_company = $branch->company->getId();
621
                    $this->default_company_branch = $branch->getId();
622
                    //set the default company id per the specific app , we do this so we can have multip default companies per diff apps
623
                    $this->set(Companies::cacheKey(), $this->default_company);
624
                }
625
            }
626
        }
627
    }
628
629
    /**
630
     * Update the password for a current user.
631
     *
632
     * @param string $newPassword
633
     * @return boolean
634
     */
635
    public function updatePassword(string $currentPassword, string $newPassword, string $verifyPassword) : bool
0 ignored issues
show
Coding Style introduced by
function updatePassword() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
636
    {
637
        $currentPassword = trim($currentPassword);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $currentPassword. This often makes code more readable.
Loading history...
638
        $newPassword = trim($newPassword);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $newPassword. This often makes code more readable.
Loading history...
639
        $verifyPassword = trim($verifyPassword);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $verifyPassword. This often makes code more readable.
Loading history...
640
641
        $app = Di::getDefault()->getApp();
642
643
        if (!$app->ecosystemAuth()) {
644
            $userAppData = $this->getApp([
645
                'conditions' => 'companies_id = :id:',
646
                'bind' => [
647
                    'id' => $this->currentCompanyId()
648
                ]
649
            ]);
650
651
            $password = $userAppData->password;
652
        } else {
653
            $password = $this->password;
654
        }
655
656
        // First off check that the current password matches the current password
657
        if (Password::check($currentPassword, $password)) {
658
            PasswordValidation::validate($newPassword, $verifyPassword);
659
660
            return $this->resetPassword($newPassword);
661
        }
662
663
        throw new Exception(_(' Your current password is incorrect .'));
664
    }
665
666
    /**
667
     * Reset the user passwrod.
668
     *
669
     * @param string $newPassword
670
     * @return bool
671
     */
672
    public function resetPassword(string $newPassword): bool
0 ignored issues
show
Coding Style introduced by
function resetPassword() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
673
    {
674
        $app = Di::getDefault()->getApp();
675
676
        if (!$app->ecosystemAuth()) {
677
            //update all companies password for the current user app
678
            AppAuth::updatePassword($this, Password::make($newPassword));
679
        } else {
680
            $this->password = Password::make($newPassword);
681
        }
682
683
        return true;
684
    }
685
686
    /**
687
     * user signup to the service.
688
     *
689
     * did we find the email?
690
     * does it have access to this app?
691
     * no?
692
     * ok lets register / associate to this app
693
     * yes?
694
     * it meas he was invites so get the fuck out?
695
     *
696
     * @return Users
697
     */
698
    public function signUp() : BakUser
699
    {
700
        $app = Di::getDefault()->getApp();
701
702
        if (!$app->ecosystemAuth()) {
703
            try {
704
                $user = self::getByEmail($this->email);
705
706
                $userAppData = $user->countApps('apps_id = ' . $this->getDI()->getDefault()->getApp()->getId());
707
708
                if ($userAppData > 0) {
709
                    throw new Exception('This email already has an account.');
710
                }
711
712
                //assign user role for the current app
713
                $user->roles_id = Roles::getByName(Roles::DEFAULT)->getId();
714
715
                $this->fire('user:afterSignup', $user, true);
716
717
                //update the passwords for the current app
718
                AppAuth::updatePassword($user, Password::make($this->password));
719
720
                //overwrite the current user object
721
                $this->id = $user->getId();
722
                $this->email = $user->getEmail();
723
            } catch (Exception $e) {
724
                //if we cant find the user normal signup
725
                $user = parent::signUp();
726
727
                //update all the password for the apps
728
                AppAuth::updatePassword($user, $this->password);
729
            }
730
        } else {
731
            $user = parent::signUp();
732
        }
733
734
        return $user;
735
    }
736
737
    /**
738
     * Generate new forgot password hash.
739
     *
740
     * @return string
741
     */
742
    public function generateForgotHash(): string
743
    {
744
        $this->user_activation_forgot = $this->generateActivationKey();
745
        $this->updateOrFail();
746
747
        return $this->user_activation_forgot;
748
    }
749
}
750