Failed Conditions
Pull Request — master (#293)
by Maximo
02:53
created

Users::assignRole()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

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