FOSSology  4.4.0
Open Source License Compliance by Open Source Software
UserController.php
Go to the documentation of this file.
1 <?php
2 /*
3  SPDX-FileCopyrightText: © 2018, 2021 Siemens AG
4  Author: Gaurav Mishra <mishra.gaurav@siemens.com>
5 
6  SPDX-License-Identifier: GPL-2.0-only
7 */
13 namespace Fossology\UI\Api\Controllers;
14 
30 use Psr\Http\Message\ServerRequestInterface;
31 
37 {
47  public function getUsers($request, $response, $args)
48  {
49  $apiVersion = ApiVersion::getVersion($request);
50  $id = null;
51  if (isset($args['pathParam'])) {
52  $id = $apiVersion == ApiVersion::V2 ? intval($this->restHelper->getUserDao()->getUserByName($args['pathParam'])['user_pk']) : intval($args['pathParam']);
53  if (! $this->dbHelper->doesIdExist("users", "user_pk", $id)) {
54  throw new HttpNotFoundException("UserId doesn't exist");
55  }
56  }
57  $users = $this->dbHelper->getUsers($id);
58 
59  $allUsers = array();
60  foreach ($users as $user) {
61  $allUsers[] = $user->getArray($apiVersion);
62  }
63  if ($id !== null) {
64  $allUsers = $allUsers[0];
65  }
66  return $response->withJson($allUsers, 200);
67  }
68 
78  public function addUser($request, $response, $args)
79  {
80  $apiVersion = ApiVersion::getVersion($request);
81  $userDetails = $this->getParsedBody($request);
82  $userHelper = new UserHelper();
83  // creating symphony request
84  $symfonyRequest = new \Symfony\Component\HttpFoundation\Request();
85  $symfonyRequest->request->set('username', $userDetails['name']);
86  $symfonyRequest->request->set('pass1', $userDetails[$apiVersion == ApiVersion::V2 ? 'userPass' : 'user_pass']);
87  $symfonyRequest->request->set('pass2', $userDetails[$apiVersion == ApiVersion::V2 ? 'userPass' : 'user_pass']);
88  $symfonyRequest->request->set('description', $userDetails['description']);
89  $symfonyRequest->request->set('permission', $userHelper->getEquivalentValueForPermission($userDetails['accessLevel']));
90  $symfonyRequest->request->set('folder', $userDetails['rootFolderId']);
91  $symfonyRequest->request->set('enote', $userDetails['emailNotification'] ? 'y' : 'n');
92  $symfonyRequest->request->set('email', $userDetails['email']);
93  $symfonyRequest->request->set('public', $userDetails['defaultVisibility']);
94  $symfonyRequest->request->set('default_bucketpool_fk', $userDetails['defaultBucketpool'] ?? 2);
95 
96  $agents = array();
97  if (isset($userDetails['agents'])) {
98  if (is_string($userDetails['agents'])) { // If 'x-www-form-urlencoded', inner elements are not decoded
99  $userDetails['agents'] = json_decode($userDetails['agents'], true);
100  }
101  $agents['Check_agent_mimetype'] = isset($userDetails['agents']['mime']) && $userDetails['agents']['mime'] ? 1 : 0;
102  $agents['Check_agent_monk'] = isset($userDetails['agents']['monk']) && $userDetails['agents']['monk'] ? 1 : 0;
103  $agents['Check_agent_ojo'] = isset($userDetails['agents']['ojo']) && $userDetails['agents']['ojo'] ? 1 : 0;
104  $agents['Check_agent_bucket'] = isset($userDetails['agents']['bucket']) && $userDetails['agents']['bucket'] ? 1 : 0 ;
105  $agents['Check_agent_copyright'] = isset($userDetails['agents'][$apiVersion == ApiVersion::V2 ? 'copyrightEmailAuthor' : 'copyright_email_author']) && $userDetails['agents'][$apiVersion == ApiVersion::V2 ? 'copyrightEmailAuthor' : 'copyright_email_author'] ? 1 : 0;
106  $agents['Check_agent_ecc'] = isset($userDetails['agents']['ecc']) && $userDetails['agents']['ecc'] ? 1 : 0;
107  $agents['Check_agent_keyword'] = isset($userDetails['agents']['keyword']) && $userDetails['agents']['keyword'] ? 1 : 0;
108  $agents['Check_agent_nomos'] = isset($userDetails['agents']['nomos']) && $userDetails['agents']['nomos'] ? 1 : 0;
109  $agents['Check_agent_pkgagent'] = isset($userDetails['agents']['package']) && $userDetails['agents']['package'] ? 1 : 0;
110  $agents['Check_agent_reso'] = isset($userDetails['agents']['reso']) && $userDetails['agents']['reso'] ? 1 : 0;
111  $agents['Check_agent_shagent'] = isset($userDetails['agents']['heritage']) && $userDetails['agents']['heritage'] ? 1 : 0 ;
112  }
113 
114  $symfonyRequest->request->set('user_agent_list', userAgents($agents));
115 
116  // initialising the user_add object
117  global $container;
118  $restHelper = $container->get('helper.restHelper');
119  $userAddObj = $restHelper->getPlugin('user_add');
120 
121  // calling the add function
122  $ErrMsg = $userAddObj->add($symfonyRequest);
123 
124  if ($ErrMsg != '') {
125  throw new HttpInternalServerErrorException($ErrMsg);
126  }
127 
128  $returnVal = new Info(201, "User created successfully", InfoType::INFO);
129  return $response->withJson($returnVal->getArray(), $returnVal->getCode());
130  }
131 
141  public function deleteUser($request, $response, $args)
142  {
143  $apiVersion = ApiVersion::getVersion($request);
144  $id = $apiVersion == ApiVersion::V2 ? intval($this->restHelper->getUserDao()->getUserByName($args['pathParam'])['user_pk']) : intval($args['pathParam']);
145  if (!$this->dbHelper->doesIdExist("users","user_pk", $id)) {
146  throw new HttpNotFoundException("UserId doesn't exist");
147  }
148 
149  $this->dbHelper->deleteUser($id);
150  $returnVal = new Info(202, "User will be deleted", InfoType::INFO);
151  return $response->withJson($returnVal->getArray(), $returnVal->getCode());
152  }
153 
162  public function getCurrentUser($request, $response, $args)
163  {
164  $apiVersion = ApiVersion::getVersion($request);
165  $user = $this->dbHelper->getUsers($this->restHelper->getUserId())[0]->getArray($apiVersion);
166  if ($apiVersion == ApiVersion::V2) {
167  return $response->withJson($user, 200);
168  }
169  $userDao = $this->restHelper->getUserDao();
170  $defaultGroup = $userDao->getUserAndDefaultGroupByUserName($user["name"])["group_name"];
171  $user['default_group'] = $defaultGroup;
172  return $response->withJson($user, 200);
173  }
174 
184  public function updateUser($request, $response, $args)
185  {
186  $apiVersion = ApiVersion::getVersion($request);
187  $id = $apiVersion == ApiVersion::V2 ? intval($this->restHelper->getUserDao()->getUserByName($args['pathParam'])['user_pk']) : intval($args['pathParam']);
188  if (!$this->dbHelper->doesIdExist("users","user_pk", $id)) {
189  throw new HttpNotFoundException("UserId doesn't exist");
190  }
191  $reqBody = $this->getParsedBody($request);
192  $userHelper = new UserHelper($id);
193  $returnVal = $userHelper->modifyUserDetails($reqBody, $apiVersion);
194  return $response->withJson($returnVal->getArray(), $returnVal->getCode());
195  }
196 
206  public function createRestApiToken($request, $response, $args)
207  {
208  $reqBody = $this->getParsedBody($request);
209  $tokenRequest = TokenRequest::fromArray($reqBody,
210  ApiVersion::getVersion($request));
211  $symfonyRequest = new \Symfony\Component\HttpFoundation\Request();
212 
213  // translating values for symfony request
214  $symfonyRequest->request->set('pat_name', $tokenRequest->getTokenName());
215  $symfonyRequest->request->set('pat_expiry', $tokenRequest->getTokenExpire());
216  $symfonyRequest->request->set('pat_scope', $tokenRequest->getTokenScope());
217 
218  // initialising the user_edit plugin
219  global $container;
221  $restHelper = $container->get('helper.restHelper');
223  $userEditObj = $restHelper->getPlugin('user_edit');
224 
225  // creating the REST token
226  try {
227  $token = $userEditObj->generateNewToken($symfonyRequest);
228  } catch (DuplicateTokenKeyException $e) {
229  throw new HttpTooManyRequestException("Please try again later.", $e);
230  } catch (DuplicateTokenNameException $e) {
231  throw new HttpConflictException($e->getMessage(), $e);
232  } catch (\UnexpectedValueException $e) {
233  throw new HttpBadRequestException($e->getMessage(), $e);
234  }
235 
236  $returnVal = new Info(201, "Token created successfully", InfoType::INFO);
237  $res = $returnVal->getArray();
238  $res['token'] = $token;
239  return $response->withJson($res, $returnVal->getCode());
240  }
241 
251  public function getTokens($request, $response, $args)
252  {
253  $apiVersion = ApiVersion::getVersion($request);
254  $tokenType = $args['type'];
255  if ($tokenType != "active" && $tokenType != "expired") {
256  throw new HttpBadRequestException("Invalid request!");
257  }
258  // initialising the user_edit plugin
259  global $container;
260  $restHelper = $container->get('helper.restHelper');
261  $userEditObj = $restHelper->getPlugin('user_edit');
262 
263  // getting the list of tokens based on the type of token requested
264  $tokens = $tokenType == "active" ? $userEditObj->getListOfActiveTokens() : $userEditObj->getListOfExpiredTokens();
265  $manageTokenObj = $restHelper->getPlugin('manage-token');
266 
267  $finalTokens = array();
268  foreach ($tokens as $token) {
269  list($tokenPk) = explode(".", $token['id']);
270  $tokenVal = $manageTokenObj->revealToken($tokenPk);
271  $finalTokens[] = array_merge($token, ['token' => $tokenVal['token']]);
272  }
273 
274  $returnVal = new Info(200, "Success", InfoType::INFO);
275  $res = $returnVal->getArray();
276  $res[$tokenType . ($apiVersion == ApiVersion::V2 ? 'Tokens' : '_tokens')] = $finalTokens;
277  return $response->withJson($res, $returnVal->getCode());
278  }
279 }
Exception when a token has duplicate key for same user.
Exception when a token has duplicate name for same user.
Base controller for REST calls.
getParsedBody(ServerRequestInterface $request)
Parse request body as JSON and return associative PHP array.
getCurrentUser($request, $response, $args)
Override Slim response for withJson function.
Provides various DAO helper functions for REST api.
Definition: RestHelper.php:32
Handle user related queries.
Definition: UserHelper.php:28
static getVersion(ServerRequestInterface $request)
Definition: ApiVersion.php:29
Different type of infos provided by REST.
Definition: InfoType.php:16
Info model to contain general error and return values.
Definition: Info.php:19
static fromArray(array $input, int $version)
userAgents($agents=null)
Read the UI form and format the user selected agents into a comma separated list.