Failed Conditions
Pull Request — master (#317)
by Rafael
04:35
created

Users::isFirstSignup()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 4
ccs 0
cts 4
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 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
     * 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();
538
    }
539
540
    /**
541
     * Get the list of all the associated apps this users has.
542
     *:w.
543
     * @return array
544
     */
545
    public function getAssociatedApps(): array
546
    {
547
        $apps = $this->getApps(['columns' => 'apps_id', 'group' => 'apps_id']);
548
549
        if ($apps->count()) {
550
            return array_map(function ($apps) {
551
                return $apps['apps_id'];
552
            }, $apps->toArray());
553
        }
554
555
        return [0];
556
    }
557
558
    /**
559
     * Get an array of the associates companies Ids.
560
     *
561
     * @return array
562
     */
563
    public function getAssociatedCompanies(): array
564
    {
565
        $companies = $this->getCompanies(['columns' => 'companies_id']);
566
567
        if ($companies->count()) {
568
            return array_map(function ($company) {
569
                return $company['companies_id'];
570
            }, $companies->toArray());
571
        }
572
573
        return [0];
574
    }
575
576
    /**
577
     * Get user by key.
578
     * @param string $userActivationEmail
579
     * @return Users
580
     */
581
    public static function getByUserActivationEmail(string $userActivationEmail): Users
582
    {
583
        return self::findFirst([
584
            'conditions' => 'user_activation_email = ?0 and user_active =?1 and is_deleted = 0',
585
            'bind' => [$userActivationEmail, 1],
586
        ]);
587
    }
588
589
    /**
590
     * Overwrite the relationship.
591
     *
592
     * @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...
593
     */
594
    public function getPhoto()
595
    {
596
        return $this->getFileByName('photo');
597
    }
598
599
    /**
600
     * Update the user current default company.
601
     *
602
     * @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...
603
     * @return void
604
     */
605
    public function switchDefaultCompanyByBranch(int $branchId): void
606
    {
607
        if ($branch = CompaniesBranches::findFirst($branchId)) {
608
            if ($branch->company) {
609
                if ($branch->company->userAssociatedToCompany($this)) {
610
                    $this->default_company = $branch->company->getId();
611
                    $this->default_company_branch = $branch->getId();
612
                    //set the default company id per the specific app , we do this so we can have multip default companies per diff apps
613
                    $this->set(Companies::cacheKey(), $this->default_company);
614
                }
615
            }
616
        }
617
    }
618
619
    /**
620
     * Update the password for a current user.
621
     *
622
     * @param string $newPassword
623
     * @return boolean
624
     */
625
    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...
626
    {
627
        $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...
628
        $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...
629
        $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...
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
     * @return bool
661
     */
662
    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...
663
    {
664
        $app = Di::getDefault()->getApp();
665
666
        if (!$app->ecosystemAuth()) {
667
            //update all companies password for the current user app
668
            AppAuth::updatePassword($this, Password::make($newPassword));
669
        } else {
670
            $this->password = Password::make($newPassword);
671
        }
672
673
        return true;
674
    }
675
676
    /**
677
     * user signup to the service.
678
     *
679
     * did we find the email?
680
     * does it have access to this app?
681
     * no?
682
     * ok lets register / associate to this app
683
     * yes?
684
     * it meas he was invites so get the fuck out?
685
     *
686
     * @return Users
687
     */
688
    public function signUp() : BakUser
689
    {
690
        $app = Di::getDefault()->getApp();
691
692
        if (!$app->ecosystemAuth()) {
693
            try {
694
                $user = self::getByEmail($this->email);
695
696
                $userAppData = $user->countApps('apps_id = ' . $this->getDI()->getDefault()->getApp()->getId());
697
698
                if ($userAppData > 0) {
699
                    throw new Exception('This email already has an account.');
700
                }
701
702
                //assign user role for the current app
703
                $user->roles_id = Roles::getByName(Roles::DEFAULT)->getId();
704
705
                $this->fire('user:afterSignup', $user, true);
706
707
                //update the passwords for the current app
708
                AppAuth::updatePassword($user, Password::make($this->password));
709
710
                //overwrite the current user object
711
                $this->id = $user->getId();
712
                $this->email = $user->getEmail();
713
            } catch (Exception $e) {
714
                //if we cant find the user normal signup
715
                $user = parent::signUp();
716
717
                //update all the password for the apps
718
                AppAuth::updatePassword($user, $this->password);
719
            }
720
        } else {
721
            $user = parent::signUp();
722
        }
723
724
        return $user;
725
    }
726
727
    /**
728
     * Generate new forgot password hash.
729
     *
730
     * @return string
731
     */
732
    public function generateForgotHash(): string
733
    {
734
        $this->user_activation_forgot = $this->generateActivationKey();
735
        $this->updateOrFail();
736
737
        return $this->user_activation_forgot;
738
    }
739
}
740