Failed Conditions
Push — master ( b60474...c2ee02 )
by Maximo
01:06 queued 11s
created

Users::getByUserActivationEmail()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 7
ccs 0
cts 5
cp 0
crap 2
rs 10
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 Canvas\Exception\ServerErrorHttpException;
10
use Carbon\Carbon;
11
use Phalcon\Validation;
12
use Phalcon\Validation\Validator\Email;
13
use Phalcon\Validation\Validator\PresenceOf;
14
use Phalcon\Validation\Validator\Regex;
15
use Phalcon\Validation\Validator\Uniqueness;
16
use Canvas\Traits\FileSystemModelTrait;
17
use Phalcon\Security\Random;
18
use Baka\Database\Contracts\HashTableTrait;
19
use Canvas\Contracts\Notifications\NotifiableTrait;
20
use Canvas\Traits\EventManagerAwareTrait;
21
use Phalcon\Di;
22
use Canvas\Auth\App as AppAuth;
23
use Exception;
24
use Canvas\Validations\PasswordValidation;
25
use Baka\Auth\Models\Users as BakUser;
26
use Canvas\Hashing\Password;
27
28
/**
29
 * Class Users.
30
 *
31
 * @package Canvas\Models
32
 *
33
 * @property Users $user
34
 * @property Config $config
35
 * @property Apps $app
36
 * @property Companies $defaultCompany
37
 * @property \Phalcon\Di $di
38
 */
39
class Users extends \Baka\Auth\Models\Users
40
{
41
    use PermissionsTrait;
42
    use Billable;
43
    use SubscriptionPlanLimitTrait;
44
    use FileSystemModelTrait;
45
    use HashTableTrait;
46
    use NotifiableTrait;
47
    use EventManagerAwareTrait;
48
49
    /**
50
     * Default Company Branch.
51
     *
52
     * @var integer
53
     */
54
    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...
55
56
    /**
57
     * Roles id.
58
     *
59
     * @var integer
60
     */
61
    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...
62
63
    /**
64
     * Stripe id.
65
     *
66
     * @var string
67
     */
68
    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...
69
70
    /**
71
     * Card last four numbers.
72
     *
73
     * @var integer
74
     */
75
    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...
76
77
    /**
78
     * Card Brand.
79
     *
80
     * @var integer
81
     */
82
    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...
83
84
    /**
85
     * Trial end date.
86
     *
87
     * @var string
88
     */
89
    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...
90
91
    /**
92
     * Provide the app plan id
93
     * if the user is signing up a new company.
94
     *
95
     * @var integer
96
     */
97
    public $appPlanId = null;
98
99
    /**
100
     * Active subscription id.Not an actual table field, used temporarily.
101
     * @var string
102
     */
103
    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...
104
105
    /**
106
     * System Module Id.
107
     * @var integer
108
     */
109
    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...
110
111
    /**
112
     * User email activation code.
113
     *
114
     * @var string
115
     */
116
    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...
117
118
    /**
119
     * Initialize method for model.
120
     */
121
    public function initialize()
122
    {
123
        $this->setSource('users');
124
125
        //overwrite parent relationships
126
        $this->hasOne('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'session']);
127
        $this->hasMany('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'sessions']);
128
        $this->hasMany('id', 'Baka\Auth\Models\SessionKeys', 'users_id', ['alias' => 'sessionKeys']);
129
        $this->hasMany('id', 'Baka\Auth\Models\Banlist', 'users_id', ['alias' => 'bans']);
130
        $this->hasMany('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'sessions']);
131
        $this->hasMany('id', 'Canvas\Models\UserConfig', 'users_id', ['alias' => 'config']);
132
        $this->hasMany('id', 'Canvas\Models\UserLinkedSources', 'users_id', ['alias' => 'sources']);
133
134
        $this->hasOne(
135
            'default_company',
136
            'Canvas\Models\Companies',
137
            'id',
138
            ['alias' => 'defaultCompany']
139
        );
140
141
        $this->hasOne(
142
            'default_company',
143
            'Canvas\Models\Companies',
144
            'id',
145
            ['alias' => 'currentCompany']
146
        );
147
148
        $this->hasOne(
149
            'id',
150
            'Canvas\Models\UserRoles',
151
            'users_id',
152
            [
153
                'alias' => 'userRole',
154
                'params' => [
155
                    'limit' => 1,
156
                    'conditions' => 'Canvas\Models\UserRoles.apps_id = ?0',
157
                    'bind' => [$this->di->getApp()->getId()],
158
                ]
159
            ]
160
        );
161
162
        $this->hasMany(
163
            'id',
164
            'Canvas\Models\UserRoles',
165
            'users_id',
166
            [
167
                'alias' => 'permissions',
168
                'params' => [
169
                    'conditions' => 'Canvas\Models\UserRoles.apps_id = ' . $this->di->getApp()->getId(),
170
                ]
171
            ]
172
        );
173
174
        $this->hasManyToMany(
175
            'id',
176
            'Canvas\Models\UserRoles',
177
            'users_id',
178
            'roles_id',
179
            'Canvas\Models\Roles',
180
            'id',
181
            [
182
                'alias' => 'roles',
183
                'params' => [
184
                    'limit' => 1,
185
                    'conditions' => 'Canvas\Models\UserRoles.apps_id = ' . $this->di->getApp()->getId(),
186
                ]
187
            ]
188
        );
189
190
        $this->hasMany(
191
            'id',
192
            'Canvas\Models\Subscription',
193
            'user_id',
194
            [
195
                'alias' => 'allSubscriptions',
196
                'params' => [
197
                    'conditions' => 'apps_id = ?0',
198
                    'bind' => [$this->di->getApp()->getId()],
199
                    'order' => 'id DESC'
200
                ]
201
            ]
202
        );
203
204
        $this->hasMany(
205
            'id',
206
            'Canvas\Models\UsersAssociatedApps',
207
            'users_id',
208
            [
209
                'alias' => 'companies',
210
                'params' => [
211
                    'conditions' => 'apps_id = ?0',
212
                    'bind' => [$this->di->getApp()->getId()],
213
                ]
214
            ]
215
        );
216
217
        $this->hasMany(
218
            'id',
219
            'Canvas\Models\UsersAssociatedApps',
220
            'users_id',
221
            [
222
                'alias' => 'apps',
223
            ]
224
        );
225
226
        $this->hasOne(
227
            'id',
228
            'Canvas\Models\UsersAssociatedApps',
229
            'users_id',
230
            [
231
                'alias' => 'app',
232
                'params' => [
233
                    'conditions' => 'apps_id = ?0',
234
                    'bind' => [Di::getDefault()->getApp()->getId()]
235
                ]
236
            ]
237
        );
238
239
        $this->hasMany(
240
            'id',
241
            'Canvas\Models\UserWebhooks',
242
            'users_id',
243
            ['alias' => 'userWebhook']
244
        );
245
246
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
247
        $this->hasOne(
248
            'id',
249
            'Canvas\Models\FileSystemEntities',
250
            'entity_id',
251
            [
252
                'alias' => 'files',
253
                'params' => [
254
                    'conditions' => 'system_modules_id = ?0',
255
                    'bind' => [$systemModule->getId()]
256
                ]
257
            ]
258
        );
259
260
        $this->hasOne(
261
            'id',
262
            'Canvas\Models\FileSystemEntities',
263
            'entity_id',
264
            [
265
                'alias' => 'photo',
266
                'params' => [
267
                    'conditions' => 'system_modules_id = ?0',
268
                    'bind' => [$systemModule->getId()]
269
                ]
270
            ]
271
        );
272
    }
273
274
    /**
275
     * Validations and business logic.
276
     */
277
    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...
278
    {
279
        $validator = new Validation();
280
        $validator->add(
281
            'email',
282
            new Email([
283
                'field' => 'email',
284
                'required' => true,
285
            ])
286
        );
287
288
        $validator->add(
289
            'displayname',
290
            new PresenceOf([
291
                'field' => 'displayname',
292
                'required' => true,
293
            ])
294
        );
295
296
        // Unique values
297
        $validator->add(
298
            'email',
299
            new Uniqueness([
300
                'field' => 'email',
301
                'message' => _('This email already has an account.'),
302
            ])
303
        );
304
305
        return $this->validate($validator);
306
    }
307
308
    /**
309
     * Returns table name mapped in the model.
310
     *
311
     * @return string
312
     */
313
    public function getSource() : string
314
    {
315
        return 'users';
316
    }
317
318
    /**
319
    * Set hashtable settings table, userConfig ;).
320
    *
321
    * @return void
322
    */
323
    private function createSettingsModel(): void
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
324
    {
325
        $this->settingsModel = new UserConfig();
326
    }
327
328
    /**
329
     * Get the User key for redis.
330
     *
331
     * @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...
332
     */
333
    public function getKey() : int
334
    {
335
        return $this->id;
336
    }
337
338
    /**
339
     * A company owner is the first person that register this company
340
     * This only ocurres when signing up the first time, after that all users invites
341
     * come with a default_company id attached.
342
     *
343
     * @return boolean
344
     */
345
    public function isFirstSignup(): bool
346
    {
347
        return empty($this->default_company);
348
    }
349
350
    /**
351
     * Does the user have a role assign to him?
352
     *
353
     * @return boolean
354
     */
355
    public function hasRole(): bool
356
    {
357
        return !empty($this->roles_id);
358
    }
359
360
    /**
361
     * Get all of the subscriptions for the user.
362
     */
363
    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...
364
    {
365
        $this->hasMany(
366
            'id',
367
            'Canvas\Models\Subscription',
368
            'user_id',
369
            [
370
                'alias' => 'subscriptions',
371
                'params' => [
372
                    'conditions' => 'apps_id = ?0 and companies_id = ?1',
373
                    'bind' => [$this->di->getApp()->getId(), $this->default_company],
374
                    'order' => 'id DESC'
375
                ]
376
            ]
377
        );
378
379
        return $this->getRelated('subscriptions');
380
    }
381
382
    /**
383
     * Strat a free trial.
384
     *
385
     * @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...
386
     * @return Subscription
387
     */
388
    public function startFreeTrial() : Subscription
389
    {
390
        $defaultPlan = AppsPlans::getDefaultPlan();
391
        $trialEndsAt = Carbon::now()->addDays($this->di->getApp()->plan->free_trial_dates);
392
393
        $subscription = new Subscription();
394
        $subscription->user_id = $this->getId();
395
        $subscription->companies_id = $this->default_company;
396
        $subscription->apps_id = $this->di->getApp()->getId();
397
        $subscription->apps_plans_id = $this->di->getApp()->default_apps_plan_id;
398
        $subscription->name = $defaultPlan->name;
399
        $subscription->stripe_id = $defaultPlan->stripe_id;
400
        $subscription->stripe_plan = $defaultPlan->stripe_plan;
401
        $subscription->quantity = 1;
402
        $subscription->trial_ends_at = $trialEndsAt->toDateTimeString();
403
        $subscription->trial_ends_days = $trialEndsAt->diffInDays(Carbon::now());
404
        $subscription->is_freetrial = 1;
405
        $subscription->is_active = 1;
406
        $subscription->saveOrFail();
407
408
        $this->trial_ends_at = $subscription->trial_ends_at;
409
        $this->updateOrFail();
410
411
        return $subscription;
412
    }
413
414
    /**
415
     * Before create.
416
     *
417
     * @return void
418
     */
419
    public function beforeCreate()
420
    {
421
        parent::beforeCreate();
422
        $random = new Random();
423
        $this->user_activation_email = $random->uuid();
424
425
        //this is only empty when creating a new user
426
        if (!$this->isFirstSignup()) {
427
            //confirm if the app reach its limit
428
            $this->isAtLimit();
429
        }
430
431
        //Assign admin role to the system if we dont get a specify role
432
        if (!$this->hasRole()) {
433
            $role = Roles::getByName('Admins');
434
            $this->roles_id = $role->getId();
435
        }
436
    }
437
438
    /**
439
     * What the current company the users is logged in with
440
     * in this current session?
441
     *
442
     * @return integer
443
     */
444
    public function currentCompanyId(): int
445
    {
446
        $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...
447
        return !is_null($defaultCompanyId) ? (int) $defaultCompanyId : (int) $this->default_company;
448
    }
449
450
    /**
451
     * Overwrite the user relationship.
452
     * use Phalcon Registry to assure we mantian the same instance accross the request.
453
     */
454
    public function getDefaultCompany(): Companies
455
    {
456
        $registry = Di::getDefault()->getRegistry();
457
        $key = 'company_' . Di::getDefault()->getApp()->getId() . '_' . $this->getId();
458
        if (!isset($registry[$key])) {
459
            $registry[$key] = Companies::findFirstOrFail($this->currentCompanyId());
460
        }
461
        return  $registry[$key];
462
    }
463
464
    /**
465
     * What the current company brach the users is logged in with
466
     * in this current session?
467
     *
468
     * @return integer
469
     */
470
    public function currentCompanyBranchId(): int
471
    {
472
        return (int) $this->default_company_branch;
473
    }
474
475
    /**
476
     * What to do after the creation of a new users
477
     *  - Assign default role.
478
     *
479
     * @return void
480
     */
481
    public function afterCreate()
482
    {
483
        //need to run it here, since we overwirte the default_company id and null this function objective
484
        $isFirstSignup = $this->isFirstSignup();
485
486
        /**
487
         * if we dont find the userdata di lets create it.
488
         * @todo this is not ideal lets fix it later
489
         */
490
        if (!$this->di->has('userData')) {
491
            $this->di->setShared('userData', $this);
492
        }
493
494
        $this->fire('user:afterSignup', $this, $isFirstSignup);
495
496
        //update user activity when its not a empty user
497
        if (!$isFirstSignup) {
498
            $this->updateAppActivityLimit();
499
        }
500
    }
501
502
    /**
503
     * Upload Files.
504
     *
505
     * @todo move this to the baka class
506
     *
507
     * @return void
508
     */
509
    public function afterSave()
510
    {
511
        $this->associateFileSystem();
512
        $this->updatePermissionRoles();
513
    }
514
515
    /**
516
     * update user role for the specific app.
517
     *
518
     * @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...
519
     */
520
    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...
521
    {
522
        if ($permission = $this->getPermission()) {
523
            $permission->roles_id = $this->roles_id;
524
            return $permission->updateOrFail();
525
        }
526
527
        return false;
528
    }
529
530
    /**
531
     * Overwrite the permission relationship to force the user of company id
532
     * 
533
     * @return UserRoles
534
     */
535
    public function getPermission()
536
    {
537
        return $this->getUserRole('companies_id =' . $this->currentCompanyId());
538
    }
539
540
    /**
541
     * Get the list of all the associated apps this users has.
542
     *:w
543
544
     * @return array
545
     */
546
    public function getAssociatedApps(): array
547
    {
548
        $apps = $this->getApps(['columns' => 'apps_id', 'group' => 'apps_id']);
549
550
        if ($apps->count()) {
551
            return array_map(function ($apps) {
552
                return $apps['apps_id'];
553
            }, $apps->toArray());
554
        }
555
556
        return [0];
557
    }
558
559
    /**
560
     * Get an array of the associates companies Ids.
561
     *
562
     * @return array
563
     */
564
    public function getAssociatedCompanies(): array
565
    {
566
        $companies = $this->getCompanies(['columns' => 'companies_id']);
567
568
        if ($companies->count()) {
569
            return array_map(function ($company) {
570
                return $company['companies_id'];
571
            }, $companies->toArray());
572
        }
573
574
        return [0];
575
    }
576
577
    /**
578
     * Get user by key.
579
     * @param string $userActivationEmail
580
     * @return Users
581
     */
582
    public static function getByUserActivationEmail(string $userActivationEmail): Users
583
    {
584
        return self::findFirst([
585
            'conditions' => 'user_activation_email = ?0 and user_active =?1 and is_deleted = 0',
586
            'bind' => [$userActivationEmail, 1],
587
        ]);
588
    }
589
590
    /**
591
     * Overwrite the relationship.
592
     *
593
     * @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...
594
     */
595
    public function getPhoto()
596
    {
597
        return $this->getFileByName('photo');
598
    }
599
600
    /**
601
     * Update the user current default company.
602
     *
603
     * @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...
604
     * @return void
605
     */
606
    public function switchDefaultCompanyByBranch(int $branchId): void
607
    {
608
        if ($branch = CompaniesBranches::findFirst($branchId)) {
609
            if ($branch->company) {
610
                if ($branch->company->userAssociatedToCompany($this)) {
611
                    $this->default_company = $branch->company->getId();
612
                    $this->default_company_branch = $branch->getId();
613
                    //set the default company id per the specific app , we do this so we can have multip default companies per diff apps
614
                    $this->set(Companies::cacheKey(), $this->default_company);
615
                }
616
            }
617
        }
618
    }
619
620
    /**
621
     * Update the password for a current user.
622
     *
623
     * @param string $newPassword
624
     * @return boolean
625
     */
626
    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...
627
    {
628
        $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...
629
        $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...
630
        $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...
631
632
        $app = Di::getDefault()->getApp();
633
634
        if (!$app->ecosystemAuth()) {
635
            $userAppData = $this->getApp([
636
                'conditions' => 'companies_id = :id:',
637
                'bind' => [
638
                    'id' => $this->currentCompanyId()
639
                ]
640
            ]);
641
642
            $password = $userAppData->password;
643
        } else {
644
            $password = $this->password;
645
        }
646
647
        // First off check that the current password matches the current password
648
        if (Password::check($currentPassword, $password)) {
649
            PasswordValidation::validate($newPassword, $verifyPassword);
650
651
            return $this->resetPassword($newPassword);
652
        }
653
654
        throw new Exception(_(' Your current password is incorrect .'));
655
    }
656
657
    /**
658
     * Reset the user passwrod.
659
     *
660
     * @param string $newPassword
661
     * @return bool
662
     */
663
    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...
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);
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();
713
                $this->email = $user->getEmail();
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();
736
        $this->updateOrFail();
737
738
        return $this->user_activation_forgot;
739
    }
740
}
741