UserController.php
8.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
<?php
namespace App\Controllers;
use App\Auth\UsernameAccountType;
use App\Constants\AclRoles;
use App\Model\Project;
use App\Model\User;
use App\Model\UserProject;
use App\Transformers\UserTransformer;
use PhalconApi\Constants\ErrorCodes;
use PhalconApi\Exception;
use PhalconRest\Mvc\Controllers\CrudResourceController;
class UserController extends CrudResourceController
{
/**
* Accessible fields
*
* @return array
*/
public function whitelist()
{
return [
'username',
'password',
'email',
'role'
];
}
/**
* Возвращает всех зарегистрированных пользователей c ролью AclRoles::EDITOR
*
* @return mixed
*/
public function editorsAction()
{
$current_projects = $this->userService->getDetails()->projects;
$editors = [];
foreach ($current_projects as $project)
{
foreach ($project->users as $user) {
if ($user->role == AclRoles::EDITOR)
{
$editors[$project->id][] = $this->createItemResponse($user, new UserTransformer());
}
}
}
return $this->createResponse($editors);
}
/**
* Возвращает всех зарегистрированных пользователей c ролью AclRoles::AUTHOR
*
* @return mixed
*/
public function authorsAction()
{
$current_projects = $this->userService->getDetails()->projects;
$authors = [];
foreach ($current_projects as $project)
{
foreach ($project->users as $user) {
if ($user->role == AclRoles::AUTHOR)
{
$authors[$project->id][] = $this->createItemResponse($user, new UserTransformer());
}
}
}
return $this->createResponse($authors);
}
/**
* Возвращает текущего залогиненного пользователя
*
* @return mixed
*/
public function meAction()
{
return $this->createResourceResponse($this->userService->getDetails());
}
/**
* Изменение данных пользователя
*
* @param $id
* @throws Exception
*/
public function updateAction($id)
{
if ($this->userService->getRole() == AclRoles::ADMINISTRATOR || $id == $this->userService->getIdentity())
{
return $this->update($id);
}
else
{
throw new Exception(ErrorCodes::ACCESS_DENIED, 'Operation is not allowed');
}
}
/**
* Удаление пользователя
*
* @param $id
* @throws Exception
*/
public function removeAction($id)
{
$user_role = $this->userService->getRole();
$user_id = $this->userService->getIdentity();
$role_to_delete = User::findFirst($id)->role;
if (AclRoles::access_user_delete($user_role, $role_to_delete) || $user_id == $id)
{
return $this->remove($id);
}
else
{
throw new Exception(ErrorCodes::ACCESS_DENIED, 'Operation is not allowed');
}
}
/**
* Авторизация пользователя через BasicAuth и возвращает токен доступа
*
* @return mixed
*/
public function authenticateAction()
{
$username = $this->request->getUsername();
$password = $this->request->getPassword();
$session = $this->authManager->loginWithUsernamePassword(UsernameAccountType::NAME, $username,
$password);
$transformer = new UserTransformer;
$transformer->setModelClass('App\Model\User');
$user = $this->createItemResponse(User::findFirst($session->getIdentity()), $transformer);
$response = [
'token' => $session->getToken(),
'expires' => $session->getExpirationTime(),
'user' => $user
];
return $this->createArrayResponse($response, 'data');
}
/**
* Регистрация нового пользователя
*
* @return mixed
*/
public function registerAction()
{
$this->beforeHandle();
$this->beforeHandleWrite();
$this->beforeHandleCreate();
$data = $this->getPostedData();
if (!$data || count($data) == 0) {
return $this->onNoDataProvided();
}
if (!$this->postDataValid($data, false)) {
return $this->onDataInvalid($data);
}
if (!$this->saveAllowed($data) || !$this->createAllowed($data)) {
return $this->onNotAllowed();
}
$data = $this->transformPostData($data);
$item = $this->createModelInstance();
$newItem = $this->createItem($item, $data);
if (!$newItem) {
return $this->onCreateFailed($item, $data);
}
$last_id = $newItem->getWriteConnection()->lastInsertId();
$responseData = $this->getFindData($last_id);
$response = $this->getCreateResponse($responseData, $data);
$this->afterHandleCreate($newItem, $data, $response);
$this->afterHandleWrite();
$this->afterHandle();
return $response;
}
/**
* Приглашение существующего пользователя в проэкт
*
* @throws Exception
*/
public function inviteAction()
{
$user_id = $this->request->get('user_id');
$project_id = $this->request->get('project_id');
if (empty($user_id) || empty($project_id))
{
throw new Exception(ErrorCodes::DATA_NOT_FOUND, 'Empty post-data');
}
elseif (!User::findFirst($user_id))
{
throw new Exception(ErrorCodes::GENERAL_NOT_FOUND, 'User with requested id not found');
}
elseif (!Project::findFirst($project_id))
{
throw new Exception(ErrorCodes::GENERAL_NOT_FOUND, 'Project with requested id not found');
}
elseif (UserProject::findFirst(["user_id = '$user_id' AND project_id = '$project_id'"]))
{
throw new Exception(ErrorCodes::POST_DATA_INVALID, 'User already invited');
}
else
{
$userProject = new UserProject();
$data = ['project_id' => $project_id, 'user_id' => $user_id];
$userProject->user_id = $user_id;
$userProject->project_id = $project_id;
if (!$userProject->save())
{
return $this->onCreateFailed($userProject, $data);
}
else
{
return $this->createResponse($data);
}
}
}
/**
* Переопределение входных данных
*
* @param $data
* @return array
* @throws Exception
*/
protected function transformPostData($data)
{
$result = [];
foreach ($data as $key => $value)
{
/** --- Менять роли может только админ ---- **/
if ($this->userService->getRole() !== AclRoles::ADMINISTRATOR && $key == 'role')
{
$msg = 'You have not access for field `role`';
throw new Exception(
ErrorCodes::POST_DATA_INVALID,
$msg,
['post data field' => $key, 'value' => $value]
);
}
/** -------------------------------------- **/
$result[$key] = $this->transformPostDataValue($key, $value, $data);
}
return $result;
}
/**
* Хеширование пароля
*
* @param $key
* @param $value
* @param $data
* @return string
*/
protected function transformPostDataValue($key, $value, $data)
{
if ($key == 'password') {
return $this->security->hash($value);
} else {
return $value;
}
}
/**
* Сопутствующее удаление из перелинковочной таблицы проэкт-пользователь
*
* @param $id
*/
protected function beforeHandleRemove($id)
{
$junctions = UserProject::findFirst("user_id = '$id'");
if ($junctions)
{
$junctions->delete();
}
}
}