Test Failed
Pull Request — master (#20)
by
unknown
04:23
created

UsersInviteController::onConstruct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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