Passed
Pull Request — master (#35)
by Rafael
04:12
created

UsersInviteController   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 174
Duplicated Lines 0 %

Test Coverage

Coverage 77.11%

Importance

Changes 0
Metric Value
eloc 82
dl 0
loc 174
ccs 64
cts 83
cp 0.7711
rs 10
c 0
b 0
f 0
wmc 15

4 Methods

Rating   Name   Duplication   Size   Complexity  
A onConstruct() 0 6 1
A getByHash() 0 12 2
A insertInvite() 0 47 5
B processUserInvite() 0 68 7
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 Gewaer\Models\EmailTemplates;
19
use Exception;
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
        //Fetch email template of user
115 4
        $emailTemplate = EmailTemplates::getByName('users-invite');
0 ignored issues
show
Unused Code introduced by
The assignment to $emailTemplate is dead and can be removed.
Loading history...
116
117
        // Lets send the mail
118
119 4
        $invitationUrl = $this->config->app->frontEndUrl . '/users/invites/' . $userInvite->invite_hash;
120
121 4
        if (!defined('API_TESTS')) {
122
            $subject = _('You have been invited!');
123
            $this->mail
124
            ->to($userInvite->email)
125
            ->subject($subject)
126
            ->content($invitationUrl)
127
            ->sendNow();
128
        }
129
130 4
        return $this->response($userInvite);
131
    }
132
133
    /**
134
     * Add invited user to our system
135
     * @return Response
136
     */
137 2
    public function processUserInvite(string $hash): Response
138
    {
139 2
        $request = $this->request->getPost();
140
141 2
        if (empty($request)) {
142
            $request = $this->request->getJsonRawBody(true);
143
        }
144
145
        //Ok let validate user password
146 2
        $validation = new Validation();
147 2
        $validation->add('password', new PresenceOf(['message' => _('The password is required.')]));
148
149 2
        $validation->add(
150 2
            'password',
151 2
            new StringLength([
152 2
                'min' => 8,
153 2
                'messageMinimum' => _('Password is too short. Minimum 8 characters.'),
154
            ])
155
        );
156
157
        //validate this form for password
158 2
        $messages = $validation->validate($request);
159 2
        if (count($messages)) {
160
            foreach ($messages as $message) {
161
                throw new ServerErrorHttpException((string)$message);
162
            }
163
        }
164
165
        //Lets find users_invite by hash on our database
166 2
        $usersInvite = $this->model::findFirst([
167 2
                'conditions' => 'invite_hash = ?0 and is_deleted = 0',
168 2
                'bind' => [$hash]
169
            ]);
170
171 2
        if (!is_object($usersInvite)) {
172
            throw new NotFoundHttpException('Users Invite not found');
173
        }
174
175 2
        $newUser = new Users();
176 2
        $newUser->firstname = $request['firstname'];
177 2
        $newUser->lastname = $request['lastname'];
178 2
        $newUser->displayname = $request['displayname'];
179 2
        $newUser->password = ltrim(trim($request['password']));
180 2
        $newUser->email = $usersInvite->email;
181 2
        $newUser->user_active = 1;
182 2
        $newUser->roles_id = $usersInvite->role_id;
183 2
        $newUser->created_at = date('Y-m-d H:m:s');
184 2
        $newUser->default_company = $usersInvite->companies_id;
185 2
        $newUser->default_company_branch = $usersInvite->company->branch->getId();
186
187
        try {
188 2
            $this->db->begin();
189
190
            //signup
191 2
            $newUser->signup();
192 2
            if (!defined('API_TESTS')) {
193
                $usersInvite->is_deleted = 1;
194
                $usersInvite->update();
195
            }
196
197 2
            $this->db->commit();
198
        } catch (Exception $e) {
199
            $this->db->rollback();
200
201
            throw new UnprocessableEntityHttpException($e->getMessage());
202
        }
203
204 2
        return $this->response($newUser);
205
    }
206
}
207