Passed
Push — master ( 577268...d73137 )
by Maximo
02:32
created

UsersInviteController::insertInvite()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 44
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 5.8299

Importance

Changes 0
Metric Value
cc 5
eloc 27
nc 7
nop 0
dl 0
loc 44
ccs 19
cts 28
cp 0.6786
crap 5.8299
rs 9.1768
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\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
20
/**
21
 * Class LanguagesController
22
 * @property Users $userData
23
 * @property Request $request
24
 * @property Config $config
25
 * @property Apps $app
26
 * @property Mail $mail
27
 * @package Gewaer\Api\Controllers
28
 *
29
 */
30
class UsersInviteController extends BaseController
31
{
32
    /*
33
     * fields we accept to create
34
     *
35
     * @var array
36
     */
37
    protected $createFields = ['invite_hash', 'companies_id', 'role_id', 'app_id', 'email'];
38
39
    /*
40
     * fields we accept to create
41
     *
42
     * @var array
43
     */
44
    protected $updateFields = ['invite_hash', 'companies_id', 'role_id', 'app_id', 'email'];
45
46
    /**
47
     * set objects
48
     *
49
     * @return void
50
     */
51 4
    public function onConstruct()
52
    {
53 4
        $this->model = new UsersInvite();
54 4
        $this->additionalSearchFields = [
55 4
            ['is_deleted', ':', '0'],
56 4
            ['companies_id', ':', $this->userData->currentCompanyId()],
57
        ];
58 4
    }
59
60
    /**
61
     * Get users invite by hash
62
     * @param string $hash
63
     * @return Response
64
     */
65 1
    public function getByHash(string $hash):Response
66
    {
67 1
        $userInvite = $this->model::findFirst([
68 1
            'conditions' => 'invite_hash =  ?0 and is_deleted = 0',
69 1
            'bind' => [$hash]
70
        ]);
71
72 1
        if (!is_object($userInvite)) {
73
            throw new NotFoundHttpException('Users Invite not found');
74
        }
75
76 1
        return $this->response($userInvite);
77
    }
78
79
    /**
80
     * Sets up invitation information for a would be user
81
     * @return Response
82
     */
83 4
    public function insertInvite(): Response
84
    {
85 4
        $request = $this->request->getPost();
86 4
        $random = new Random();
87
88 4
        $validation = new Validation();
89 4
        $validation->add('email', new PresenceOf(['message' => _('The email is required.')]));
90 4
        $validation->add('role_id', new PresenceOf(['message' => _('The role is required.')]));
91
92
        //validate this form for password
93 4
        $messages = $validation->validate($this->request->getPost());
94 4
        if (count($messages)) {
95
            foreach ($messages as $message) {
96
                throw new ServerErrorHttpException((string)$message);
97
            }
98
        }
99
100
        //Save data to users_invite table and generate a hash for the invite
101 4
        $userInvite = $this->model;
102 4
        $userInvite->companies_id = $this->userData->default_company;
103 4
        $userInvite->app_id = $this->app->getId();
104 4
        $userInvite->role_id = Roles::getById((int)$request['role_id']);
105 4
        $userInvite->email = $request['email'];
106 4
        $userInvite->invite_hash = $random->base58();
107 4
        $userInvite->created_at = date('Y-m-d H:m:s');
108
109 4
        if (!$userInvite->save()) {
110
            throw new UnprocessableEntityHttpException((string) current($userInvite->getMessages()));
111
        }
112
113
        // Lets send the mail
114
115 4
        $invitationUrl = $this->config->app->frontEndUrl . '/users/invites/' . $userInvite->invite_hash;
116
117 4
        if (!defined('API_TESTS')) {
118
            $subject = _('You have been invited!');
119
            $this->mail
120
            ->to($userInvite->email)
121
            ->subject($subject)
122
            ->content($invitationUrl)
123
            ->sendNow();
124
        }
125
126 4
        return $this->response($userInvite);
127
    }
128
129
    /**
130
     * Add invited user to our system
131
     * @return Response
132
     */
133 2
    public function processUserInvite(string $hash): Response
134
    {
135 2
        $request = $this->request->getPost();
136
137 2
        if (empty($request)) {
138
            $request = $this->request->getJsonRawBody(true);
139
        }
140
141
        //Ok let validate user password
142 2
        $validation = new Validation();
143 2
        $validation->add('password', new PresenceOf(['message' => _('The password is required.')]));
144
145 2
        $validation->add(
146 2
            'password',
147 2
            new StringLength([
148 2
                'min' => 8,
149 2
                'messageMinimum' => _('Password is too short. Minimum 8 characters.'),
150
            ])
151
        );
152
153
        //validate this form for password
154 2
        $messages = $validation->validate($request);
155 2
        if (count($messages)) {
156
            foreach ($messages as $message) {
157
                throw new ServerErrorHttpException((string)$message);
158
            }
159
        }
160
161
        //Lets find users_invite by hash on our database
162 2
        $usersInvite = $this->model::findFirst([
163 2
                'conditions' => 'invite_hash = ?0 and is_deleted = 0',
164 2
                'bind' => [$hash]
165
            ]);
166
167 2
        if (!is_object($usersInvite)) {
168
            throw new NotFoundHttpException('Users Invite not found');
169
        }
170
171 2
        $newUser = new Users();
172 2
        $newUser->firstname = $request['firstname'];
173 2
        $newUser->lastname = $request['lastname'];
174 2
        $newUser->displayname = $request['displayname'];
175 2
        $newUser->password = ltrim(trim($request['password']));
176 2
        $newUser->email = $usersInvite->email;
177 2
        $newUser->user_active = 1;
178 2
        $newUser->roles_id = $usersInvite->role_id;
179 2
        $newUser->created_at = date('Y-m-d H:m:s');
180 2
        $newUser->default_company = $usersInvite->companies_id;
181 2
        $newUser->default_company_branch = $usersInvite->company->branch->getId();
182
183
        try {
184 2
            $this->db->begin();
185
186
            //signup
187 2
            $newUser->signup();
188 2
            if (!defined('API_TESTS')) {
189
                $usersInvite->is_deleted = 1;
190
                $usersInvite->update();
191
            }
192
193 2
            $this->db->commit();
194
        } catch (Exception $e) {
195
            $this->db->rollback();
196
197
            throw new UnprocessableEntityHttpException($e->getMessage());
198
        }
199
200 2
        return $this->response($newUser);
201
    }
202
}
203