Failed Conditions
Pull Request — master (#36)
by Rafael
04:02
created

UsersInviteController   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 203
Duplicated Lines 0 %

Test Coverage

Coverage 75.51%

Importance

Changes 0
Metric Value
eloc 98
dl 0
loc 203
ccs 74
cts 98
cp 0.7551
rs 10
c 0
b 0
f 0
wmc 16

4 Methods

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