Failed Conditions
Pull Request — master (#18)
by
unknown
08:00
created

UsersInviteController::onConstruct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
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 Phalcon\Http\Response;
16
17
/**
18
 * Class LanguagesController
19
 *
20
 * @package Gewaer\Api\Controllers
21
 *
22
 */
23
class UsersInviteController extends BaseController
24
{
25
    /*
26
     * fields we accept to create
27
     *
28
     * @var array
29
     */
30
    protected $createFields = ['invite_hash', 'company_id', 'role_id', 'app_id', 'email'];
31
32
    /*
33
     * fields we accept to create
34
     *
35
     * @var array
36
     */
37
    protected $updateFields = ['invite_hash', 'company_id', 'role_id', 'app_id', 'email'];
38
39
    /**
40
     * set objects
41
     *
42
     * @return void
43
     */
44 1
    public function onConstruct()
45
    {
46 1
        $this->model = new UsersInvite();
47 1
    }
48
49
    /**
50
     * Sets up invitation information for a would be user
51
     * @return Response
52
     */
53 1
    public function insertInvite(): Response
54
    {
55 1
        $request = $this->request->getPost();
56 1
        $random = new Random();
57
58 1
        $validation = new Validation();
59 1
        $validation->add('email', new PresenceOf(['message' => _('The email is required.')]));
60 1
        $validation->add('role', new PresenceOf(['message' => _('The role is required.')]));
61
62
        //validate this form for password
63 1
        $messages = $validation->validate($this->request->getPost());
64 1
        if (count($messages)) {
65
            foreach ($messages as $message) {
66
                throw new ServerErrorHttpException((string)$message);
0 ignored issues
show
Bug introduced by
The type Gewaer\Api\Controllers\ServerErrorHttpException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
67
            }
68
        }
69
70
        //Save data to users_invite table and generate a hash for the invite
71 1
        $userInvite = $this->model;
72 1
        $userInvite->company_id = $this->userData->default_company;
0 ignored issues
show
Bug Best Practice introduced by
The property userData does not exist on Gewaer\Api\Controllers\UsersInviteController. Since you implemented __get, consider adding a @property annotation.
Loading history...
73 1
        $userInvite->app_id = $this->app->getId();
0 ignored issues
show
Bug Best Practice introduced by
The property app does not exist on Gewaer\Api\Controllers\UsersInviteController. Since you implemented __get, consider adding a @property annotation.
Loading history...
74 1
        $userInvite->role_id = $request['role'] == 'Admins' ? 1 : 2;
75 1
        $userInvite->email = $request['email'];
76 1
        $userInvite->invite_hash = $random->base58();
77 1
        $userInvite->created_at = date('Y-m-d H:m:s');
78
79 1
        if (!$userInvite->save()) {
80
            throw new UnprocessableEntityHttpException((string) current($userInvite->getMessages()));
81
        }
82
83 1
        $userInviteArray = $userInvite->toArray();
84
85 1
        return $this->response($userInviteArray);
86
    }
87
88
    /**
89
     * Add invited user to our system
90
     * @return Response
91
     */
92 1
    public function processUserInvite(string $hash): Response
93
    {
94 1
        $request = $this->request->getPost();
95
96 1
        if (empty($request)) {
97
            $request = $this->request->getJsonRawBody(true);
98
        }
99
100
        //Ok let validate user password
101 1
        $validation = new Validation();
102 1
        $validation->add('password', new PresenceOf(['message' => _('The password is required.')]));
103
104 1
        $validation->add(
105 1
            'password',
106 1
            new StringLength([
107 1
                'min' => 8,
108 1
                'messageMinimum' => _('Password is too short. Minimum 8 characters.'),
109
            ])
110
        );
111
112
        //validate this form for password
113 1
        $messages = $validation->validate($request);
0 ignored issues
show
Bug introduced by
It seems like $request can also be of type boolean; however, parameter $data of Phalcon\Validation::validate() does only seem to accept array|object, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

113
        $messages = $validation->validate(/** @scrutinizer ignore-type */ $request);
Loading history...
114 1
        if (count($messages)) {
115
            foreach ($messages as $message) {
116
                throw new ServerErrorHttpException((string)$message);
117
            }
118
        }
119
120
        //Lets find users_invite by hash on our database
121 1
        $usersInvite = $this->model::findFirst([
122 1
                'conditions' => 'invite_hash = ?0 and is_deleted = 0',
123 1
                'bind' => [$hash]
124
            ]);
125
126 1
        if (!$usersInvite) {
127
            throw new NotFoundHttpException('Users Invite not found');
128
        }
129 1
        $newUser = new Users();
130 1
        $newUser->firstname = $request['firstname'];
131 1
        $newUser->lastname = $request['lastname'];
132 1
        $newUser->displayname = $request['displayname'];
133 1
        $newUser->password = $request['password'];
134 1
        $newUser->email = $usersInvite->email;
135 1
        $newUser->user_active = 1;
136 1
        $newUser->roles_id = $usersInvite->role_id;
137 1
        $newUser->created_at = date('Y-m-d H:m:s');
138
        // $newUser->name = $this->userData->defaultCompany; //Como puedo agregar este campo si es de una relacion ?
139 1
        $newUser->default_company = $this->userData->default_company;
0 ignored issues
show
Bug Best Practice introduced by
The property userData does not exist on Gewaer\Api\Controllers\UsersInviteController. Since you implemented __get, consider adding a @property annotation.
Loading history...
140
141
        //Lets insert the new user to our system.
142
143 1
        if ($newUser->save()) {
144 1
            return $this->response($newUser->toArray());
145
        } else {
146
            //if not thorw exception
147
            throw new UnprocessableEntityHttpException((string) current($newUser->getMessages()));
148
        }
149
    }
150
}
151