Failed Conditions
Pull Request — master (#10)
by Maximo
03:34
created

api/controllers/UsersController.php (1 issue)

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gewaer\Api\Controllers;
6
7
use Gewaer\Models\Users;
8
use Gewaer\Models\UserLinkedSources;
9
use Baka\Auth\Models\Sources;
10
use Phalcon\Http\Response;
11
use Phalcon\Validation;
12
use Phalcon\Validation\Validator\PresenceOf;
13
use Gewaer\Exception\BadRequestHttpException;
14
use Gewaer\Exception\UnprocessableEntityHttpException;
15
use Baka\Http\QueryParser;
16
use Gewaer\Exception\ModelException;
17
use Gewaer\Exception\NotFoundHttpException;
18
19
/**
20
 * Class UsersController
21
 *
22
 * @package Gewaer\Api\Controllers
23
 *
24
 * @property Users $userData
25
 * @property Request $request
26
 */
27
class UsersController extends \Baka\Auth\UsersController
28
{
29
    /*
30
     * fields we accept to create
31
     *
32
     * @var array
33
     */
34
    protected $createFields = ['name', 'firstname', 'lastname', 'displayname', 'email', 'password', 'created_at', 'updated_at', 'default_company', 'family'];
35
36
    /*
37
     * fields we accept to create
38
     *
39
     * @var array
40
     */
41
    protected $updateFields = ['name', 'firstname', 'lastname', 'displayname', 'email', 'password', 'created_at', 'updated_at', 'default_company'];
42
43
    /**
44
     * set objects
45
     *
46
     * @return void
47
     */
48
    public function onConstruct()
49
    {
50
        $this->model = new Users();
51
52
        //if you are not a admin you cant see all the users
53
        if (!$this->userData->hasRole('Default.Admins')) {
54
            $this->additionalSearchFields = [
55
                ['id', ':', $this->userData->getId()],
56
            ];
57
        } else {
58
            //admin get all the users for this company
59
            $this->additionalSearchFields = [
60
                ['default_company', ':', $this->userData->default_company],
61
            ];
62
        }
63
    }
64
65
    /**
66
     * Get Uer
67
     *
68
     * @param mixed $id
69
     *
70
     * @method GET
71
     * @url /v1/users/{id}
72
     *
73
     * @return Response
74
     */
75
    public function getById($id) : Response
76
    {
77
        //find the info
78
        $user = $this->model->findFirst([
79
            'id = ?0 AND is_deleted = 0',
80
            'bind' => [$this->userData->getId()],
81
        ]);
82
83
        $user->password = null;
84
85
        //get relationship
86
        if ($this->request->hasQuery('relationships')) {
87
            $relationships = $this->request->getQuery('relationships', 'string');
88
89
            $user = QueryParser::parseRelationShips($relationships, $user);
90
        }
91
92
        if ($user) {
93
            return $this->response($user);
94
        } else {
95
            throw new ModelException('Record not found');
96
        }
97
    }
98
99
    /**
100
     * Update a User Info
101
     *
102
     * @method PUT
103
     * @url /v1/users/{id}
104
     *
105
     * @return Response
106
     */
107
    public function edit($id) : Response
108
    {
109
        if ($user = $this->model->findFirst($this->userData->getId())) {
110
            $request = $this->request->getPut();
111
112
            if (empty($request)) {
113
                $request = $this->request->getJsonRawBody(true);
114
            }
115
116
            //clean pass
117
            if (array_key_exists('password', $request) && !empty($request['password'])) {
118
                $user->password = Users::passwordHash($request['password']);
119
                unset($request['password']);
120
            }
121
122
            //clean default company
123
            if (array_key_exists('default_company', $request)) {
124
                //@todo check if I belong to this company
125
                if ($company = Companies::findFirst($request['default_company'])) {
126
                    $user->default_company = $company->getId();
127
                    unset($request['default_company']);
128
                }
129
            }
130
131
            //update
132
            if ($user->update($request, $this->updateFields)) {
133
                $user->password = null;
134
                return $this->response($user);
135
            } else {
136
                //didnt work
137
                throw new ModelException((string) current($user->getMessages()));
138
            }
139
        } else {
140
            throw new NotFoundHttpException('Record not found');
141
        }
142
    }
143
144
    /**
145
     * Add users notifications
146
     *
147
     * @param int $id
148
     * @return void
149
     */
150
    public function updateNotifications($id): Response
151
    {
152
        //get the notification array
153
        //delete the current ones
154
        //iterate and save into users
155
156
        return $this->response(['OK']);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->response(array('OK')) returns the type Phalcon\Http\Response which is incompatible with the documented return type void.
Loading history...
157
    }
158
159
    /**
160
     * Associate a Device with the corrent loggedin user
161
     *
162
     * @url /users/{id}/device
163
     * @method POST
164
     * @return Response
165
     */
166
    public function devices(): Response
167
    {
168
        //Ok let validate user password
169
        $validation = new Validation();
170
        $validation->add('app', new PresenceOf(['message' => _('App name is required.')]));
171
        $validation->add('deviceId', new PresenceOf(['message' => _('device ID is required.')]));
172
173
        //validate this form for password
174
        $messages = $validation->validate($this->request->getPost());
175
        if (count($messages)) {
176
            foreach ($messages as $message) {
177
                throw new BadRequestHttpException((string) $message);
178
            }
179
        }
180
181
        $app = $this->request->getPost('app', 'string');
182
        $deviceId = $this->request->getPost('deviceId', 'string');
183
184
        //get the app source
185
        if ($source = Sources::getByTitle($app)) {
186
            if (!$userSource = UserLinkedSources::findFirst(['conditions' => 'users_id = ?0 and source_users_id_text =?1', 'bind' => [$this->userData->getId(), $deviceId]])) {
187
                $userSource = new UserLinkedSources();
188
                $userSource->users_id = $this->userData->getId();
189
                $userSource->source_id = $source->getId();
190
                $userSource->source_users_id = $this->userData->getId();
191
                $userSource->source_users_id_text = $deviceId;
192
                $userSource->source_username = $this->userData->displayname . ' ' . $app;
193
194
                if (!$userSource->save()) {
195
                    throw new UnprocessableEntityHttpException((string) current($userSource->getMessages()));
196
                }
197
198
                $msg = 'User Device Associated';
199
            } else {
200
                $msg = 'User Device Already Associated';
201
            }
202
        }
203
204
        //clean password @todo move this to a better place
205
        $this->userData->password = null;
206
207
        return $this->response([
208
            'msg' => $msg,
209
            'user' => $this->userData
210
        ]);
211
    }
212
}
213