15479603
Alex Savenko
initialize
|
1
2
3
4
|
<?php
namespace App\Controllers;
|
0b8d4ffc
Alex Savenko
Add Roles.
|
5
6
7
8
9
10
11
12
|
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;
|
15479603
Alex Savenko
initialize
|
13
14
15
16
|
use PhalconRest\Mvc\Controllers\CrudResourceController;
class UserController extends CrudResourceController
{
|
84125667
Alex Savenko
изменение пользов...
|
17
18
19
20
21
|
/**
* Accessible fields
*
* @return array
*/
|
a85cc509
Alex Savenko
registration
|
22
23
24
25
26
|
public function whitelist()
{
return [
'username',
'password',
|
84125667
Alex Savenko
изменение пользов...
|
27
28
|
'email',
'role'
|
a85cc509
Alex Savenko
registration
|
29
30
31
|
];
}
|
84125667
Alex Savenko
изменение пользов...
|
32
|
/**
|
0b8d4ffc
Alex Savenko
Add Roles.
|
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
|
* Возвращает всех зарегистрированных пользователей 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);
}
/**
|
84125667
Alex Savenko
изменение пользов...
|
75
76
77
78
|
* Возвращает текущего залогиненного пользователя
*
* @return mixed
*/
|
c4e1ecec
Alex Savenko
delete action for...
|
79
|
public function meAction()
|
15479603
Alex Savenko
initialize
|
80
81
82
83
|
{
return $this->createResourceResponse($this->userService->getDetails());
}
|
84125667
Alex Savenko
изменение пользов...
|
84
|
/**
|
0b8d4ffc
Alex Savenko
Add Roles.
|
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
|
* Изменение данных пользователя
*
* @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');
}
}
/**
|
84125667
Alex Savenko
изменение пользов...
|
125
126
127
128
|
* Авторизация пользователя через BasicAuth и возвращает токен доступа
*
* @return mixed
*/
|
c4e1ecec
Alex Savenko
delete action for...
|
129
|
public function authenticateAction()
|
15479603
Alex Savenko
initialize
|
130
131
132
133
|
{
$username = $this->request->getUsername();
$password = $this->request->getPassword();
|
0b8d4ffc
Alex Savenko
Add Roles.
|
134
|
$session = $this->authManager->loginWithUsernamePassword(UsernameAccountType::NAME, $username,
|
15479603
Alex Savenko
initialize
|
135
136
|
$password);
|
0b8d4ffc
Alex Savenko
Add Roles.
|
137
|
$transformer = new UserTransformer;
|
15479603
Alex Savenko
initialize
|
138
139
|
$transformer->setModelClass('App\Model\User');
|
0b8d4ffc
Alex Savenko
Add Roles.
|
140
|
$user = $this->createItemResponse(User::findFirst($session->getIdentity()), $transformer);
|
15479603
Alex Savenko
initialize
|
141
142
143
144
145
146
147
148
149
150
|
$response = [
'token' => $session->getToken(),
'expires' => $session->getExpirationTime(),
'user' => $user
];
return $this->createArrayResponse($response, 'data');
}
|
84125667
Alex Savenko
изменение пользов...
|
151
152
153
154
155
|
/**
* Регистрация нового пользователя
*
* @return mixed
*/
|
0b8d4ffc
Alex Savenko
Add Roles.
|
156
157
|
public function registerAction()
{
|
95d1b70c
Alex Savenko
registration
|
158
|
|
3754fbeb
Alex Savenko
registration
|
159
160
161
162
163
164
165
166
167
|
$this->beforeHandle();
$this->beforeHandleWrite();
$this->beforeHandleCreate();
$data = $this->getPostedData();
if (!$data || count($data) == 0) {
return $this->onNoDataProvided();
}
|
3754fbeb
Alex Savenko
registration
|
168
169
170
171
172
173
174
175
176
177
178
|
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();
|
bb6147e1
Alex Savenko
registration
|
179
|
|
3754fbeb
Alex Savenko
registration
|
180
|
$newItem = $this->createItem($item, $data);
|
3754fbeb
Alex Savenko
registration
|
181
182
183
184
185
|
if (!$newItem) {
return $this->onCreateFailed($item, $data);
}
|
3412fb9f
Alex Savenko
registration
|
186
187
|
$last_id = $newItem->getWriteConnection()->lastInsertId();
$responseData = $this->getFindData($last_id);
|
c23be67b
Alex Savenko
registration
|
188
|
|
3754fbeb
Alex Savenko
registration
|
189
190
191
192
193
194
195
196
|
$response = $this->getCreateResponse($responseData, $data);
$this->afterHandleCreate($newItem, $data, $response);
$this->afterHandleWrite();
$this->afterHandle();
return $response;
|
3582f649
Alex Savenko
registration
|
197
198
|
}
|
84125667
Alex Savenko
изменение пользов...
|
199
|
/**
|
0b8d4ffc
Alex Savenko
Add Roles.
|
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
|
* Приглашение существующего пользователя в проэкт
*
* @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);
}
}
}
/**
|
84125667
Alex Savenko
изменение пользов...
|
243
244
245
246
|
* Переопределение входных данных
*
* @param $data
* @return array
|
0b8d4ffc
Alex Savenko
Add Roles.
|
247
|
* @throws Exception
|
84125667
Alex Savenko
изменение пользов...
|
248
|
*/
|
6c48a95f
Alex Savenko
registration
|
249
250
251
252
|
protected function transformPostData($data)
{
$result = [];
|
0b8d4ffc
Alex Savenko
Add Roles.
|
253
254
255
256
257
258
259
260
261
262
263
264
265
|
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]
);
}
/** -------------------------------------- **/
|
6c48a95f
Alex Savenko
registration
|
266
267
268
|
$result[$key] = $this->transformPostDataValue($key, $value, $data);
}
|
6c48a95f
Alex Savenko
registration
|
269
270
271
|
return $result;
}
|
84125667
Alex Savenko
изменение пользов...
|
272
273
274
275
276
277
278
279
|
/**
* Хеширование пароля
*
* @param $key
* @param $value
* @param $data
* @return string
*/
|
11e41ecb
Alex Savenko
registration
|
280
281
282
283
284
285
286
287
288
|
protected function transformPostDataValue($key, $value, $data)
{
if ($key == 'password') {
return $this->security->hash($value);
} else {
return $value;
}
}
|
0b8d4ffc
Alex Savenko
Add Roles.
|
289
290
291
292
293
294
295
296
297
298
299
300
301
|
/**
* Сопутствующее удаление из перелинковочной таблицы проэкт-пользователь
*
* @param $id
*/
protected function beforeHandleRemove($id)
{
$junctions = UserProject::findFirst("user_id = '$id'");
if ($junctions)
{
$junctions->delete();
}
}
|
b15debd3
Alex Savenko
user errors response
|
302
|
}
|