2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.servlets;
23 import java.io.UnsupportedEncodingException;
24 import java.net.URLDecoder;
25 import java.util.ArrayList;
26 import java.util.List;
28 import javax.inject.Singleton;
29 import javax.servlet.ServletContext;
30 import javax.servlet.http.HttpServletRequest;
31 import javax.ws.rs.Consumes;
32 import javax.ws.rs.DELETE;
33 import javax.ws.rs.GET;
34 import javax.ws.rs.HeaderParam;
35 import javax.ws.rs.POST;
36 import javax.ws.rs.Path;
37 import javax.ws.rs.PathParam;
38 import javax.ws.rs.Produces;
39 import javax.ws.rs.QueryParam;
40 import javax.ws.rs.core.Context;
41 import javax.ws.rs.core.MediaType;
42 import javax.ws.rs.core.Response;
44 import org.openecomp.sdc.be.config.BeEcompErrorManager;
45 import org.openecomp.sdc.be.dao.api.ActionStatus;
46 import org.openecomp.sdc.be.model.User;
47 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
48 import org.openecomp.sdc.be.user.UserBusinessLogic;
49 import org.openecomp.sdc.common.api.Constants;
50 import org.openecomp.sdc.common.config.EcompErrorName;
51 import org.openecomp.sdc.exception.ResponseFormat;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
55 import com.jcabi.aspects.Loggable;
57 import fj.data.Either;
58 import io.swagger.annotations.Api;
59 import io.swagger.annotations.ApiOperation;
60 import io.swagger.annotations.ApiParam;
61 import io.swagger.annotations.ApiResponse;
62 import io.swagger.annotations.ApiResponses;
64 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
66 @Api(value = "User Administration", description = "User admininstarator operations")
68 public class UserAdminServlet extends BeGenericServlet {
70 private static final String ROLE_DELIMITER = ",";
71 private static Logger log = LoggerFactory.getLogger(UserAdminServlet.class.getName());
73 /***************************************
75 *************************************************************/
77 /* User by userId CRUD start */
79 /////////////////////////////////////////////////////////////////////////////////////////////////////
80 // retrieve all user details
83 @Consumes(MediaType.APPLICATION_JSON)
84 @Produces(MediaType.APPLICATION_JSON)
85 @ApiOperation(value = "retrieve user details", httpMethod = "GET", notes = "Returns user details according to userId", response = User.class)
86 @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"),
87 @ApiResponse(code = 500, message = "Internal Server Error") })
88 public Response get(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request) {
90 String url = request.getMethod() + " " + request.getRequestURI();
91 log.debug("(get) Start handle request of {}", url);
93 UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext());
96 Either<User, ActionStatus> either = userAdminManager.getUser(userId, false);
98 if (either.isRight()) {
99 return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId));
101 if (either.left().value() != null) {
102 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
104 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
107 } catch (Exception e) {
108 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get User");
109 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User");
110 log.debug("get user failed with unexpected error: {}", e.getMessage(), e);
111 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
115 /////////////////////////////////////////////////////////////////////////////////////////////////////
116 // update user - internal API
122 * @Consumes(MediaType.APPLICATION_JSON)
124 * @Produces(MediaType.APPLICATION_JSON)
126 * @ApiOperation(value = "update user - internal API", notes = "Update user", response = User.class)
128 * @ApiResponses(value = {
130 * @ApiResponse(code = 200, message = "Update user OK"),
132 * @ApiResponse(code = 400, message = "Invalid Content."),
134 * @ApiResponse(code = 403, message = "Missing information/Restricted operation"),
136 * @ApiResponse(code = 404, message = "User not found"),
138 * @ApiResponse(code = 405, message = "Method Not Allowed"),
140 * @ApiResponse(code = 409, message = "User already exists"),
142 * @ApiResponse(code = 500, message = "Internal Server Error") }) public Response updateUser(@ApiParam(value="userId of user to get", required=true) @PathParam("userId") final String userIdUpdateUser,
144 * @Context final HttpServletRequest request,
146 * @ApiParam(value="json describe the update user", required=true) String data,
148 * @HeaderParam(value = Constants.USER_ID_HEADER) String modifierAttId) {
150 * ServletContext context = request.getSession().getServletContext();
152 * String url = request.getMethod() + " " + request.getRequestURI(); log.debug("Start handle request of {}", url);
154 * // get modifier id User modifier = new User(); modifier.setUserId(modifierAttId); log.debug("modifier id is {}", modifierAttId);
156 * Response response = null;
158 * try { UserAdminBuisinessLogic businessLogic = getUserAdminManager(context); User updateInfoUser = getComponentsUtils().convertJsonToObject(data, modifier, User.class, AuditingActionEnum.UPDATE_USER).left().value(); Either<User, ResponseFormat>
159 * updateUserResponse = null;// businessLogic.updateUser(modifier, userIdUpdateUser, updateInfoUser);
161 * if (updateUserResponse.isRight()) { log.debug("failed to update user metadata"); response = buildErrorResponse(updateUserResponse.right().value()); return response; } response =
162 * buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateUserResponse.left().value()); return response;
164 * } catch (Exception e) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeRestApiGeneralError, "Update User Metadata"); log.debug("Update User Metadata failed with exception", e); response =
165 * buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus. GENERAL_ERROR)); return response;
170 /* User userId CRUD end */
172 /* User role CRUD start */
173 /////////////////////////////////////////////////////////////////////////////////////////////////////
174 // retrieve user role
176 @Path("/{userId}/role")
177 @Consumes(MediaType.APPLICATION_JSON)
178 @Produces(MediaType.APPLICATION_JSON)
179 @ApiOperation(value = "retrieve user role", notes = "Returns user role according to userId", response = String.class)
180 @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user role Ok"), @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"),
181 @ApiResponse(code = 500, message = "Internal Server Error") })
182 public Response getRole(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request) {
184 String url = request.getMethod() + " " + request.getRequestURI();
185 log.debug("(getRole) Start handle request of {}", url);
187 UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext());
190 Either<User, ActionStatus> either = userAdminManager.getUser(userId, false);
191 if (either.isRight()) {
192 return buildErrorResponse(getComponentsUtils().getResponseFormatByUserId(either.right().value(), userId));
194 if (either.left().value() != null) {
195 String roleJson = ("{ \"role\" : \"" + either.left().value().getRole().toString() + "\" }");
196 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), roleJson);
198 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
201 } catch (Exception e) {
202 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get User Role");
203 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get User Role");
204 log.debug("Get user role failed with unexpected error: {}", e);
205 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
209 /////////////////////////////////////////////////////////////////////////////////////////////////////
212 @Path("/{userId}/role")
213 @Consumes(MediaType.APPLICATION_JSON)
214 @Produces(MediaType.APPLICATION_JSON)
215 @ApiOperation(value = "update user role", notes = "Update user role", response = User.class)
216 @ApiResponses(value = { @ApiResponse(code = 200, message = "Update user OK"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information/Restricted operation"),
217 @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "User already exists"), @ApiResponse(code = 500, message = "Internal Server Error") })
218 public Response updateUserRole(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userIdUpdateUser, @Context final HttpServletRequest request,
219 @ApiParam(value = "json describe the update role", required = true) String data, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierUserId) {
221 ServletContext context = request.getSession().getServletContext();
223 String url = request.getMethod() + " " + request.getRequestURI();
224 log.debug("Start handle request of {}", url);
227 User modifier = new User();
228 modifier.setUserId(modifierUserId);
229 log.debug("modifier id is {}", modifierUserId);
231 Response response = null;
234 UserBusinessLogic businessLogic = getUserAdminManager(context);
235 User updateInfoUser = getComponentsUtils().convertJsonToObject(data, modifier, User.class, AuditingActionEnum.UPDATE_USER).left().value();
236 Either<User, ResponseFormat> updateUserResponse = businessLogic.updateUserRole(modifier, userIdUpdateUser, updateInfoUser.getRole());
238 if (updateUserResponse.isRight()) {
239 log.debug("failed to update user role");
240 response = buildErrorResponse(updateUserResponse.right().value());
243 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateUserResponse.left().value());
246 } catch (Exception e) {
247 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update User Metadata");
248 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update User Metadata");
249 log.debug("Update User Role failed with exception", e);
250 response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
256 /* User role CRUD end */
258 /* New user CRUD start */
260 @Consumes(MediaType.APPLICATION_JSON)
261 @Produces(MediaType.APPLICATION_JSON)
262 @ApiOperation(value = "add user", httpMethod = "POST", notes = "Provision new user", response = User.class)
263 @ApiResponses(value = { @ApiResponse(code = 201, message = "New user created"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information"),
264 @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "User already exists"), @ApiResponse(code = 500, message = "Internal Server Error") })
265 public Response createUser(@Context final HttpServletRequest request, @ApiParam(value = "json describe the user", required = true) String newUserData, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierAttId) {
267 ServletContext context = request.getSession().getServletContext();
269 String url = request.getMethod() + " " + request.getRequestURI();
270 log.debug("Start handle request of {}", url);
273 User modifier = new User();
274 modifier.setUserId(modifierAttId);
275 log.debug("modifier id is {}", modifierAttId);
277 Response response = null;
280 UserBusinessLogic businessLogic = getUserAdminManager(context);
281 User newUserInfo = getComponentsUtils().convertJsonToObject(newUserData, modifier, User.class, AuditingActionEnum.ADD_USER).left().value();
282 Either<User, ResponseFormat> createUserResponse = businessLogic.createUser(modifier, newUserInfo);
284 if (createUserResponse.isRight()) {
285 log.debug("failed to create user");
286 response = buildErrorResponse(createUserResponse.right().value());
289 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), createUserResponse.left().value());
292 } catch (Exception e) {
293 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Update User Metadata");
294 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update User Metadata");
295 log.debug("Create User failed with exception", e);
296 response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
302 /* New user CRUD end */
304 /* User authorization start */
306 /////////////////////////////////////////////////////////////////////////////////////////////////////
307 // User Authorization
310 @Consumes(MediaType.APPLICATION_JSON)
311 @Produces(MediaType.APPLICATION_JSON)
313 @ApiOperation(value = "authorize", notes = "authorize user", response = User.class)
314 @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 403, message = "Restricted Access"), @ApiResponse(code = 500, message = "Internal Server Error") })
315 public Response authorize(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam("HTTP_CSP_FIRSTNAME") String firstName, @HeaderParam("HTTP_CSP_LASTNAME") String lastName,
316 @HeaderParam("HTTP_CSP_EMAIL") String email) {
319 userId = (userId != null ? URLDecoder.decode(userId, "UTF-8") : null);
320 firstName = (firstName != null ? URLDecoder.decode(firstName, "UTF-8") : null);
321 lastName = (lastName != null ? URLDecoder.decode(lastName, "UTF-8") : null);
322 email = (email != null ? URLDecoder.decode(email, "UTF-8") : null);
323 } catch (UnsupportedEncodingException e) {
324 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Authorize User - decode headers");
325 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Authorize User - decode headers");
326 ResponseFormat errorResponseWrapper = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
327 return buildErrorResponse(errorResponseWrapper);
330 ServletContext context = request.getSession().getServletContext();
331 String url = request.getMethod() + " " + request.getRequestURI();
332 log.debug("Start handle request of {}", url);
334 User authUser = new User();
335 authUser.setUserId(userId);
336 authUser.setFirstName(firstName);
337 authUser.setLastName(lastName);
338 authUser.setEmail(email);
339 log.debug("auth user id is {}", userId);
341 Response response = null;
343 UserBusinessLogic userAdminManager = getUserAdminManager(context);
344 Either<User, ResponseFormat> authorize = userAdminManager.authorize(authUser);
346 if (authorize.isRight()) {
347 log.debug("authorize user failed");
348 response = buildErrorResponse(authorize.right().value());
351 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), authorize.left().value());
354 } catch (Exception e) {
355 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get ASDC users");
356 log.debug("authorize user failed with unexpected error: {}", e);
357 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
361 /* User authorization end */
365 @Consumes(MediaType.APPLICATION_JSON)
366 @Produces(MediaType.APPLICATION_JSON)
367 @ApiOperation(value = "retrieve all administrators", httpMethod = "GET", notes = "Returns all administrators", response = User.class)
368 @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns user Ok"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 500, message = "Internal Server Error") })
369 public Response getAdminsUser(@PathParam("userId") final String userId, @Context final HttpServletRequest request) {
371 String url = request.getMethod() + " " + request.getRequestURI();
372 log.debug("(get) Start handle request of {}", url);
374 UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext());
377 Either<List<User>, ResponseFormat> either = userAdminManager.getAllAdminUsers(request.getSession().getServletContext());
379 if (either.isRight()) {
380 log.debug("Failed to get all admin users");
381 return buildErrorResponse(either.right().value());
383 if (either.left().value() != null) {
384 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
386 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
389 } catch (Exception e) {
390 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get All Administrators");
391 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Administrators");
392 log.debug("get all admins failed with unexpected error: {}", e);
393 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
399 @Consumes(MediaType.APPLICATION_JSON)
400 @Produces(MediaType.APPLICATION_JSON)
401 @ApiOperation(value = "Retrieve the list of all active ASDC users or only group of users having specific roles.", httpMethod = "GET", notes = "Returns list of users with the specified roles, or all of users in the case of empty 'roles' header", response = User.class)
402 @ApiResponses(value = { @ApiResponse(code = 200, message = "Returns users Ok"), @ApiResponse(code = 204, message = "No provisioned ASDC users of requested role"), @ApiResponse(code = 403, message = "Restricted Access"),
403 @ApiResponse(code = 400, message = "Missing content"), @ApiResponse(code = 500, message = "Internal Server Error") })
404 public Response getUsersList(@Context final HttpServletRequest request, @ApiParam(value = "Any active user's USER_ID ") @HeaderParam(Constants.USER_ID_HEADER) final String userId,
405 @ApiParam(value = "TESTER,DESIGNER,PRODUCT_STRATEGIST,OPS,PRODUCT_MANAGER,GOVERNOR, ADMIN OR all users by not typing anything") @QueryParam("roles") final String roles) {
407 ServletContext context = request.getSession().getServletContext();
408 String url = request.getMethod() + " " + request.getRequestURI();
409 log.debug("Start handle request of {} modifier id is {}", url, userId);
411 List<String> rolesList = new ArrayList<>();
412 if (roles != null && !roles.trim().isEmpty()) {
413 String[] rolesArr = roles.split(ROLE_DELIMITER);
414 for (String role : rolesArr) {
415 rolesList.add(role.trim());
420 UserBusinessLogic userAdminManager = getUserAdminManager(context);
421 Either<List<User>, ResponseFormat> either = userAdminManager.getUsersList(userId, rolesList, roles);
423 if (either.isRight()) {
424 log.debug("Failed to get ASDC users");
425 return buildErrorResponse(either.right().value());
427 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
429 } catch (Exception e) {
430 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get ASDC users");
431 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get ASDC users");
432 log.debug("get users failed with unexpected error: {}", e);
433 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
438 /////////////////////////////////////////////////////////////////////////////////////////////////////
442 @Consumes(MediaType.APPLICATION_JSON)
443 @Produces(MediaType.APPLICATION_JSON)
444 @ApiOperation(value = "delete user", notes = "Delete user", response = User.class)
445 @ApiResponses(value = { @ApiResponse(code = 200, message = "Update deleted OK"), @ApiResponse(code = 400, message = "Invalid Content."), @ApiResponse(code = 403, message = "Missing information"),
446 @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 405, message = "Method Not Allowed"), @ApiResponse(code = 409, message = "Restricted operation"), @ApiResponse(code = 500, message = "Internal Server Error") })
447 public Response deActivateUser(@ApiParam(value = "userId of user to get", required = true) @PathParam("userId") final String userId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userIdHeader) {
449 ServletContext context = request.getSession().getServletContext();
450 String url = request.getMethod() + " " + request.getRequestURI();
451 log.debug("Start handle request of {} modifier id is {}", url, userIdHeader);
453 User modifier = new User();
454 modifier.setUserId(userIdHeader);
456 Response response = null;
458 UserBusinessLogic userAdminManager = getUserAdminManager(context);
459 Either<User, ResponseFormat> deactiveUserResponse = userAdminManager.deActivateUser(modifier, userId);
461 if (deactiveUserResponse.isRight()) {
462 log.debug("Failed to deactivate user");
463 response = buildErrorResponse(deactiveUserResponse.right().value());
466 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deactiveUserResponse.left().value());
469 } catch (Exception e) {
470 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "Get ASDC users");
471 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get ASDC users");
472 log.debug("deactivate user failed with unexpected error: {}", e);
473 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));