Test Failed
Branch add-core-tests (a060d8)
by Rafael
05:48
created

UsersInviteController::insertInvite()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 41
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 25
c 1
b 0
f 0
nc 5
nop 0
dl 0
loc 41
ccs 0
cts 30
cp 0
crap 20
rs 9.52
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Canvas\Api\Controllers;
6
7
use Canvas\Models\UsersInvite;
8
use Canvas\Models\Users;
9
use Canvas\Models\Roles;
10
use Phalcon\Security\Random;
0 ignored issues
show
Bug introduced by
The type Phalcon\Security\Random was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use Phalcon\Validation;
12
use Phalcon\Validation\Validator\PresenceOf;
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\PresenceOf was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
use Phalcon\Validation\Validator\StringLength;
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\StringLength was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
use Canvas\Exception\UnprocessableEntityHttpException;
15
use Canvas\Exception\NotFoundHttpException;
16
use Canvas\Exception\ServerErrorHttpException;
17
use Phalcon\Http\Response;
18
use Exception;
19
use Canvas\Exception\ModelException;
20
use Canvas\Traits\AuthTrait;
21
use Canvas\Notifications\Invitation;
22
23
/**
24
 * Class LanguagesController.
25
 * @property Users $userData
26
 * @property Request $request
27
 * @property Config $config
28
 * @property Apps $app
29
 * @property Mail $mail
30
 * @property Auth $auth
31
 * @property Payload $payload
32
 * @property Exp $exp
33
 * @property JWT $jwt
34
 * @package Canvas\Api\Controllers
35
 *
36
 */
37
class UsersInviteController extends BaseController
38
{
39
    use AuthTrait;
40
41
    /*
42
     * fields we accept to create
43
     *
44
     * @var array
45
     */
46
    protected $createFields = ['invite_hash', 'companies_id', 'role_id', 'app_id', 'email'];
47
48
    /*
49
     * fields we accept to create
50
     *
51
     * @var array
52
     */
53
    protected $updateFields = ['invite_hash', 'companies_id', 'role_id', 'app_id', 'email'];
54
55
    /**
56
     * set objects.
57
     *
58
     * @return void
59
     */
60
    public function onConstruct()
61
    {
62
        $this->model = new UsersInvite();
63
        $additionaFields = [
64
            ['is_deleted', ':', '0'],
65
        ];
66
67
        if ($this->di->has('userData')) {
68
            $additionaFields[] = ['companies_id', ':', $this->userData->currentCompanyId()];
69
        }
70
71
        $this->additionalSearchFields = $additionaFields;
72
    }
73
74
    /**
75
     * Get users invite by hash.
76
     * @param string $hash
77
     * @return Response
78
     */
79
    public function getByHash(string $hash):Response
80
    {
81
        $userInvite = $this->model::findFirst([
82
            'conditions' => 'invite_hash =  ?0 and is_deleted = 0',
83
            'bind' => [$hash]
84
        ]);
85
86
        if (!is_object($userInvite)) {
87
            throw new NotFoundHttpException('Users Invite not found');
88
        }
89
90
        return $this->response($userInvite);
91
    }
92
93
    /**
94
     * Sets up invitation information for a would be user.
95
     * @return Response
96
     */
97
    public function insertInvite(): Response
98
    {
99
        $request = $this->request->getPost();
100
        $random = new Random();
101
102
        $validation = new Validation();
103
        $validation->add('email', new PresenceOf(['message' => _('The email is required.')]));
104
        $validation->add('role_id', new PresenceOf(['message' => _('The role is required.')]));
105
106
        //validate this form for password
107
        $messages = $validation->validate($this->request->getPost());
108
        if (count($messages)) {
109
            foreach ($messages as $message) {
110
                throw new ServerErrorHttpException((string)$message);
111
            }
112
        }
113
114
        //Check if user was already was invited to current company and return message
115
        UsersInvite::isValid($request['email'], (int) $request['role_id']);
116
117
        //Save data to users_invite table and generate a hash for the invite
118
        $userInvite = $this->model;
119
        $userInvite->companies_id = $this->userData->default_company;
120
        $userInvite->users_id = $this->userData->getId();
121
        $userInvite->app_id = $this->app->getId();
122
        $userInvite->role_id = Roles::existsById((int)$request['role_id'])->id;
123
        $userInvite->email = $request['email'];
124
        $userInvite->invite_hash = $random->base58();
125
        $userInvite->created_at = date('Y-m-d H:m:s');
126
127
        if (!$userInvite->save()) {
128
            throw new UnprocessableEntityHttpException((string) current($userInvite->getMessages()));
129
        }
130
131
        //create temp invite users
132
        $tempUser = new Users();
133
        $tempUser->id = 0;
134
        $tempUser->email = $request['email'];
135
        $tempUser->notify(new Invitation($userInvite));
136
137
        return $this->response($userInvite);
138
    }
139
140
    /**
141
     * Add invited user to our system.
142
     * @return Response
143
     */
144
    public function processUserInvite(string $hash): Response
145
    {
146
        $request = $this->request->getPost();
147
        $password = ltrim(trim($request['password']));
148
149
        if (empty($request)) {
150
            $request = $this->request->getJsonRawBody(true);
151
        }
152
153
        //Ok let validate user password
154
        $validation = new Validation();
155
        $validation->add('password', new PresenceOf(['message' => _('The password is required.')]));
156
157
        $validation->add(
158
            'password',
159
            new StringLength([
160
                'min' => 8,
161
                'messageMinimum' => _('Password is too short. Minimum 8 characters.'),
162
            ])
163
        );
164
165
        //validate this form for password
166
        $messages = $validation->validate($request);
167
        if (count($messages)) {
168
            foreach ($messages as $message) {
169
                throw new ServerErrorHttpException((string)$message);
170
            }
171
        }
172
173
        //Lets find users_invite by hash on our database
174
        $usersInvite = $this->model::findFirst([
175
            'conditions' => 'invite_hash = ?0 and is_deleted = 0',
176
            'bind' => [$hash]
177
        ]);
178
179
        if (!is_object($usersInvite)) {
180
            throw new NotFoundHttpException('Users Invite not found');
181
        }
182
183
        $this->setUserDataById((int)$usersInvite->users_id);
184
185
        //Check if user already exists
186
        $userExists = Users::findFirst([
187
            'conditions' => 'email = ?0 and is_deleted = 0',
188
            'bind' => [$usersInvite->email]
189
        ]);
190
191
        if (is_object($userExists)) {
192
            $newUser = $userExists;
193
            $this->userData->defaultCompany->associate($userExists, $this->userData->defaultCompany);
194
        } else {
195
            $newUser = new Users();
196
            $newUser->firstname = $request['firstname'];
197
            $newUser->lastname = $request['lastname'];
198
            $newUser->displayname = $request['displayname'];
199
            $newUser->password = $password;
200
            $newUser->email = $usersInvite->email;
201
            $newUser->user_active = 1;
202
            $newUser->roles_id = $usersInvite->role_id;
203
            $newUser->created_at = date('Y-m-d H:m:s');
204
            $newUser->default_company = $usersInvite->companies_id;
205
            $newUser->default_company_branch = $usersInvite->company->branch->getId();
206
207
            try {
208
                $this->db->begin();
209
210
                //signup
211
                $newUser->signup();
212
213
                $this->db->commit();
214
            } catch (Exception $e) {
215
                $this->db->rollback();
216
217
                throw new UnprocessableEntityHttpException($e->getMessage());
218
            }
219
        }
220
221
        //associate the user and the app + company
222
        $this->app->associate($newUser, $usersInvite->company);
223
224
        //Lets login the new user
225
        $authInfo = $this->loginUsers($usersInvite->email, $password);
226
227
        if (!defined('API_TESTS')) {
228
            $usersInvite->is_deleted = 1;
229
            $usersInvite->update();
230
231
            return $this->response($authInfo);
232
        }
233
234
        return $this->response($newUser);
235
    }
236
}
237