Passed
Pull Request — master (#37)
by Rafael
06:12
created

UsersInviteController::insertInvite()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 48
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 6.1844

Importance

Changes 0
Metric Value
cc 6
eloc 28
nc 9
nop 0
dl 0
loc 48
ccs 24
cts 29
cp 0.8276
crap 6.1844
rs 8.8497
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gewaer\Api\Controllers;
6
7
use Gewaer\Models\UsersInvite;
8
use Gewaer\Models\Users;
9
use Gewaer\Models\UsersAssociatedCompany;
10
use Gewaer\Models\Roles;
11
use Phalcon\Security\Random;
12
use Phalcon\Validation;
13
use Phalcon\Validation\Validator\PresenceOf;
14
use Phalcon\Validation\Validator\StringLength;
15
use Gewaer\Exception\UnprocessableEntityHttpException;
16
use Gewaer\Exception\NotFoundHttpException;
17
use Gewaer\Exception\ServerErrorHttpException;
18
use Phalcon\Http\Response;
19
use Exception;
20
use Gewaer\Exception\ModelException;
21
use Gewaer\Traits\AuthTrait;
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 Gewaer\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 4
    public function onConstruct()
61
    {
62 4
        $this->model = new UsersInvite();
63 4
        $this->additionalSearchFields = [
64 4
            ['is_deleted', ':', '0'],
65 4
            ['companies_id', ':', $this->userData->currentCompanyId()],
66
        ];
67 4
    }
68
69
    /**
70
     * Get users invite by hash
71
     * @param string $hash
72
     * @return Response
73
     */
74 1
    public function getByHash(string $hash):Response
75
    {
76 1
        $userInvite = $this->model::findFirst([
77 1
            'conditions' => 'invite_hash =  ?0 and is_deleted = 0',
78 1
            'bind' => [$hash]
79
        ]);
80
81 1
        if (!is_object($userInvite)) {
82
            throw new NotFoundHttpException('Users Invite not found');
83
        }
84
85 1
        return $this->response($userInvite);
86
    }
87
88
    /**
89
     * Sets up invitation information for a would be user
90
     * @return Response
91
     */
92 4
    public function insertInvite(): Response
93
    {
94 4
        $request = $this->request->getPost();
95 4
        $random = new Random();
96
97 4
        $validation = new Validation();
98 4
        $validation->add('email', new PresenceOf(['message' => _('The email is required.')]));
99 4
        $validation->add('role_id', new PresenceOf(['message' => _('The role is required.')]));
100
101
        //validate this form for password
102 4
        $messages = $validation->validate($this->request->getPost());
103 4
        if (count($messages)) {
104
            foreach ($messages as $message) {
105
                throw new ServerErrorHttpException((string)$message);
106
            }
107
        }
108
109
        //Check if user was already was invited to current company and return message
110 4
        $invitedUser = $this->model::findFirst([
111 4
            'conditions' => 'email = ?0 and companies_id = ?1 and role_id = ?2',
112 4
            'bind' => [$request['email'], $this->userData->default_company, $request['role_id']]
113
        ]);
114
115 4
        if (is_object($invitedUser)) {
116
            throw new ModelException('User already invited to this company and added with this role');
117
        }
118
119 4
        $role = Roles::getById((int)$request['role_id']);
120
121 4
        if (!is_object($role)) {
122
            throw new ModelException('Role does not exist');
123
        }
124
125
        //Save data to users_invite table and generate a hash for the invite
126 4
        $userInvite = $this->model;
127 4
        $userInvite->companies_id = $this->userData->default_company;
128 4
        $userInvite->app_id = $this->app->getId();
129 4
        $userInvite->role_id = $role->id;
130 4
        $userInvite->email = $request['email'];
131 4
        $userInvite->invite_hash = $random->base58();
132 4
        $userInvite->created_at = date('Y-m-d H:m:s');
133
134 4
        if (!$userInvite->save()) {
135
            throw new UnprocessableEntityHttpException((string) current($userInvite->getMessages()));
136
        }
137
138 4
        $this->sendInviteEmail($request['email'], $userInvite->invite_hash);
139 4
        return $this->response($userInvite);
140
    }
141
142
    /**
143
     * Send users invite email
144
     * @param string $email
145
     * @return void
146
     */
147 4
    private function sendInviteEmail(string $email, string $hash): void
148
    {
149 4
        $userExists = Users::findFirst([
150 4
            'conditions' => 'email = ?0 and is_deleted = 0',
151 4
            'bind' => [$email]
152
        ]);
153
154 4
        $invitationUrl = $this->config->app->frontEndUrl . '/users/invites/' . $hash;
155
156 4
        if (is_object($userExists)) {
157
            $invitationUrl = $this->config->app->frontEndUrl . '/users/link/' . $hash;
158
        }
159
160 4
        if (!defined('API_TESTS')) {
161
            $subject = _('You have been invited!');
162
            $this->mail
163
            ->to($email)
164
            ->subject($subject)
165
            ->content($invitationUrl)
166
            ->sendNow();
167
        }
168 4
    }
169
170
    /**
171
     * Add invited user to our system
172
     * @return Response
173
     */
174 2
    public function processUserInvite(string $hash): Response
175
    {
176 2
        $request = $this->request->getPost();
177 2
        $password = ltrim(trim($request['password']));
178
179 2
        if (empty($request)) {
180
            $request = $this->request->getJsonRawBody(true);
181
        }
182
183
        //Ok let validate user password
184 2
        $validation = new Validation();
185 2
        $validation->add('password', new PresenceOf(['message' => _('The password is required.')]));
186
187 2
        $validation->add(
188 2
            'password',
189 2
            new StringLength([
190 2
                'min' => 8,
191 2
                'messageMinimum' => _('Password is too short. Minimum 8 characters.'),
192
            ])
193
        );
194
195
        //validate this form for password
196 2
        $messages = $validation->validate($request);
197 2
        if (count($messages)) {
198
            foreach ($messages as $message) {
199
                throw new ServerErrorHttpException((string)$message);
200
            }
201
        }
202
203
        //Lets find users_invite by hash on our database
204 2
        $usersInvite = $this->model::findFirst([
205 2
                'conditions' => 'invite_hash = ?0 and is_deleted = 0',
206 2
                'bind' => [$hash]
207
            ]);
208
209 2
        if (!is_object($usersInvite)) {
210
            throw new NotFoundHttpException('Users Invite not found');
211
        }
212
213
        //Check if user already exists
214 2
        $userExists = Users::findFirst([
215 2
            'conditions' => 'email = ?0 and is_deleted = 0',
216 2
            'bind' => [$usersInvite->email]
217
        ]);
218
219 2
        if (is_object($userExists)) {
220 1
            $newUser = new UsersAssociatedCompany;
221 1
            $newUser->users_id = (int)$userExists->id;
222 1
            $newUser->companies_id = (int)$usersInvite->companies_id;
223 1
            $newUser->identify_id = $usersInvite->role_id;
224 1
            $newUser->user_active = 1;
225 1
            $newUser->user_role = Roles::getById((int)$userExists->roles_id)->name;
226
227 1
            if (!$newUser->save()) {
228 1
                throw new UnprocessableEntityHttpException((string) current($newUser->getMessages()));
229
            }
230
        } else {
231 2
            $newUser = new Users();
232 2
            $newUser->firstname = $request['firstname'];
233 2
            $newUser->lastname = $request['lastname'];
234 2
            $newUser->displayname = $request['displayname'];
235 2
            $newUser->password = $password;
236 2
            $newUser->email = $usersInvite->email;
237 2
            $newUser->user_active = 1;
238 2
            $newUser->roles_id = $usersInvite->role_id;
239 2
            $newUser->created_at = date('Y-m-d H:m:s');
240 2
            $newUser->default_company = $usersInvite->companies_id;
241 2
            $newUser->default_company_branch = $usersInvite->company->branch->getId();
242
243
            try {
244 2
                $this->db->begin();
245
246
                //signup
247 2
                $newUser->signup();
248
249 2
                $this->db->commit();
250
            } catch (Exception $e) {
251
                $this->db->rollback();
252
253
                throw new UnprocessableEntityHttpException($e->getMessage());
254
            }
255
        }
256
257
        //Lets login the new user
258 2
        $authInfo = $this->loginUsers($usersInvite->email, $password);
259
260 2
        if (!defined('API_TESTS')) {
261
            $usersInvite->is_deleted = 1;
262
            $usersInvite->update();
263
264
            return $this->response($authInfo);
265
        }
266
267 2
        return $this->response($newUser);
268
    }
269
}
270