2 * ================================================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property
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 * ================================================================================
20 package org.openecomp.portalapp.portal.controller;
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.Collections;
25 import java.util.Comparator;
26 import java.util.List;
28 import javax.servlet.http.HttpServletRequest;
29 import javax.servlet.http.HttpServletResponse;
31 import org.apache.cxf.transport.http.HTTPException;
32 import org.openecomp.portalapp.controller.EPRestrictedBaseController;
33 import org.openecomp.portalapp.portal.domain.EPRole;
34 import org.openecomp.portalapp.portal.domain.EPUser;
35 import org.openecomp.portalapp.portal.domain.EPUserAppCatalogRoles;
36 import org.openecomp.portalapp.portal.domain.EcompAuditLog;
37 import org.openecomp.portalapp.portal.domain.ExternalSystemAccess;
38 import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
39 import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
40 import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
41 import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
42 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
43 import org.openecomp.portalapp.portal.service.AdminRolesService;
44 import org.openecomp.portalapp.portal.service.ApplicationsRestClientService;
45 import org.openecomp.portalapp.portal.service.SearchService;
46 import org.openecomp.portalapp.portal.service.UserRolesService;
47 import org.openecomp.portalapp.portal.transport.AppNameIdIsAdmin;
48 import org.openecomp.portalapp.portal.transport.AppWithRolesForUser;
49 import org.openecomp.portalapp.portal.transport.AppsListWithAdminRole;
50 import org.openecomp.portalapp.portal.transport.FieldsValidator;
51 import org.openecomp.portalapp.portal.transport.RoleInAppForUser;
52 import org.openecomp.portalapp.portal.transport.UserApplicationRoles;
53 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
54 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
55 import org.openecomp.portalapp.util.EPUserUtils;
56 import org.openecomp.portalsdk.core.domain.AuditLog;
57 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
58 import org.openecomp.portalsdk.core.restful.domain.EcompRole;
59 import org.openecomp.portalsdk.core.service.AuditService;
60 import org.openecomp.portalsdk.core.util.SystemProperties;
62 import org.springframework.beans.factory.annotation.Autowired;
63 import org.springframework.context.annotation.EnableAspectJAutoProxy;
64 import org.springframework.web.bind.annotation.PathVariable;
65 import org.springframework.web.bind.annotation.RequestBody;
66 import org.springframework.web.bind.annotation.RequestMapping;
67 import org.springframework.web.bind.annotation.RequestMethod;
68 import org.springframework.web.bind.annotation.RequestParam;
69 import org.springframework.web.bind.annotation.RestController;
72 @org.springframework.context.annotation.Configuration
73 @EnableAspectJAutoProxy
75 public class UserRolesController extends EPRestrictedBaseController {
77 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesController.class);
80 private SearchService searchService;
82 private AdminRolesService adminRolesService;
83 private @Autowired UserRolesService userRolesService;
85 private ApplicationsRestClientService applicationsRestClientService;
87 private AuditService auditService;
89 private static final String FAILURE = "failure";
92 * RESTful service method to fetch users in the WebPhone external service
100 * @return array of found users as json
102 @RequestMapping(value = { "/portalApi/queryUsers" }, method = RequestMethod.GET, produces = "application/json")
103 public String getPhoneBookSearchResult(HttpServletRequest request, @RequestParam("search") String searchString,
104 HttpServletResponse response) {
105 EPUser user = EPUserUtils.getUserSession(request);
106 String searchResult = null;
107 if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdmin(user)) {
108 EcompPortalUtils.setBadPermissions(user, response, "getPhoneBookSearchResult");
110 searchString = searchString.trim();
111 if (searchString.length() > 2) {
112 searchResult = searchService.searchUsersInPhoneBook(searchString);
114 logger.info(EELFLoggerDelegate.errorLogger,
115 "getPhoneBookSearchResult - too short search string: " + searchString);
118 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/queryUsers", "result =", searchResult);
124 * RESTful service method to fetch applications where user is admin
131 * HttpServletResponse
132 * @return for GET: array of all applications with boolean
133 * isAdmin=true/false for each application
135 @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = {
136 RequestMethod.GET }, produces = "application/json")
137 public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(HttpServletRequest request,
138 @RequestParam("user") String orgUserId, HttpServletResponse response) {
140 EPUser user = EPUserUtils.getUserSession(request);
141 AppsListWithAdminRole result = null;
142 if (!adminRolesService.isSuperAdmin(user)) {
143 EcompPortalUtils.setBadPermissions(user, response, "getAppsWithAdminRoleStateForUser");
145 if (EcompPortalUtils.legitimateUserId(orgUserId)) {
146 result = adminRolesService.getAppsWithAdminRoleStateForUser(orgUserId);
148 logger.info(EELFLoggerDelegate.errorLogger,
149 "getAppsWithAdminRoleStateForUser - parms error, no Organization User ID");
150 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
154 StringBuilder adminAppRoles = new StringBuilder();
155 if (result != null && result.appsRoles.size() >= 1) {
156 adminAppRoles.append("User '" + result.orgUserId + "' has admin role to the apps = {");
157 for (AppNameIdIsAdmin adminAppRole : result.appsRoles) {
158 if (adminAppRole.isAdmin) {
159 adminAppRoles.append(adminAppRole.appName + ", ");
162 adminAppRoles.append("}.");
164 adminAppRoles.append("User '" + result.orgUserId + "' has no Apps with Admin Role.");
166 logger.info(EELFLoggerDelegate.errorLogger, adminAppRoles.toString());
168 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "get result =", result);
177 * @param newAppsListWithAdminRoles
180 * HttpServletResponse
181 * @return FieldsValidator
183 @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = {
184 RequestMethod.PUT }, produces = "application/json")
185 public FieldsValidator putAppsWithAdminRoleStateForUser(HttpServletRequest request,
186 @RequestBody AppsListWithAdminRole newAppsListWithAdminRoles, HttpServletResponse response) {
188 // newAppsListWithAdminRoles.appsRoles
189 FieldsValidator fieldsValidator = new FieldsValidator();
190 StringBuilder newAppRoles = new StringBuilder();
191 if (newAppsListWithAdminRoles != null && newAppsListWithAdminRoles.appsRoles.size() >= 1) {
192 newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has admin role to the apps = { ");
193 for (AppNameIdIsAdmin adminAppRole : newAppsListWithAdminRoles.appsRoles) {
194 if (adminAppRole.isAdmin) {
195 newAppRoles.append(adminAppRole.appName + " ,");
198 newAppRoles.deleteCharAt(newAppRoles.length() - 1);
199 newAppRoles.append("}.");
201 newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has no Apps with Admin Role.");
203 logger.info(EELFLoggerDelegate.errorLogger, newAppRoles.toString());
205 EPUser user = EPUserUtils.getUserSession(request);
206 boolean changesApplied = false;
208 if (!adminRolesService.isSuperAdmin(user)) {
209 EcompPortalUtils.setBadPermissions(user, response, "putAppsWithAdminRoleStateForUser");
211 changesApplied = adminRolesService.setAppsWithAdminRoleStateForUser(newAppsListWithAdminRoles);
212 AuditLog auditLog = new AuditLog();
213 auditLog.setUserId(user.getId());
214 auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN);
215 auditLog.setAffectedRecordId(newAppsListWithAdminRoles.orgUserId);
216 auditLog.setComments(newAppRoles.toString());
217 auditService.logActivity(auditLog, null);
219 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
220 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
221 EcompPortalUtils.calculateDateTimeDifferenceForLog(
222 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
223 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
224 logger.info(EELFLoggerDelegate.auditLogger,
225 EPLogUtil.formatAuditLogMessage("UserRolesController.putAppsWithAdminRoleStateForUser",
226 EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN, user.getOrgUserId(),
227 newAppsListWithAdminRoles.orgUserId, newAppRoles.toString()));
228 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
229 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
230 MDC.remove(SystemProperties.MDC_TIMER);
232 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "put result =", changesApplied);
234 return fieldsValidator;
238 * It returns a list of user app roles for single app
243 * HttpServletResponse
248 * @param extRequestValue
249 * set to false if request is from users page otherwise true
250 * @return List<RoleInAppForUser>
252 @RequestMapping(value = { "/portalApi/userAppRoles" }, method = {
253 RequestMethod.GET }, produces = "application/json")
254 public List<RoleInAppForUser> getAppRolesForUser(HttpServletRequest request, @RequestParam("user") String orgUserId,
255 @RequestParam("app") Long appid, @RequestParam("externalRequest") Boolean extRequestValue,
256 HttpServletResponse response) {
257 EPUser user = EPUserUtils.getUserSession(request);
258 List<RoleInAppForUser> result = null;
259 String feErrorString = "";
260 if (!adminRolesService.isAccountAdmin(user)) {
261 EcompPortalUtils.setBadPermissions(user, response, "getAppRolesForUser");
262 feErrorString = EcompPortalUtils.getFEErrorString(true, response.getStatus());
264 if (EcompPortalUtils.legitimateUserId(orgUserId)) {
265 result = userRolesService.getAppRolesForUser(appid, orgUserId, extRequestValue);
266 int responseCode = EcompPortalUtils.getExternalAppResponseCode();
267 if (responseCode != 0 && responseCode != 200) {
269 response.setStatus(responseCode);
270 feErrorString = EcompPortalUtils.getFEErrorString(false, responseCode);
271 } else if (result == null) {
272 // If the result is null, there was an internal ecomp error
273 // in the service call.
274 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
275 feErrorString = EcompPortalUtils.getFEErrorString(true,
276 HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
279 logger.info(EELFLoggerDelegate.errorLogger, "getAppRolesForUser - no Organization User ID");
280 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
281 feErrorString = EcompPortalUtils.getFEErrorString(true, HttpServletResponse.SC_BAD_REQUEST);
285 StringBuilder sbUserApps = new StringBuilder();
286 if (result != null && result.size() >= 1) {
287 sbUserApps.append("User '" + orgUserId + "' has Roles={");
288 for (RoleInAppForUser appRole : result) {
289 if (appRole.isApplied) {
290 sbUserApps.append(appRole.roleName + ", ");
293 sbUserApps.append("} assigned to the appId '" + appid + "'.");
295 // Not sure creating an empty object will make any difference
296 // but would like to give it a shot for defect #DE221057
297 if (result == null) {
298 result = new ArrayList<RoleInAppForUser>();
300 sbUserApps.append("User '" + orgUserId + "' and appid " + appid + " has no roles");
302 logger.info(EELFLoggerDelegate.errorLogger, sbUserApps.toString());
304 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "get result =", result);
305 if (feErrorString != "") {
306 logger.debug(EELFLoggerDelegate.debugLogger, "LR: FEErrorString to header: " + feErrorString);
308 response.addHeader("FEErrorString", feErrorString);
309 response.addHeader("Access-Control-Expose-Headers", "FEErrorString");
314 @RequestMapping(value = { "/portalApi/userAppRoles" }, method = {
315 RequestMethod.PUT }, produces = "application/json")
316 public FieldsValidator putAppWithUserRoleStateForUser(HttpServletRequest request,
317 @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) {
318 FieldsValidator fieldsValidator = new FieldsValidator();
319 StringBuilder sbUserApps = new StringBuilder();
320 if (newAppRolesForUser != null) {
321 sbUserApps.append("User '" + newAppRolesForUser.orgUserId);
322 if (newAppRolesForUser.appRoles != null && newAppRolesForUser.appRoles.size() >= 1) {
323 sbUserApps.append("' has roles = { ");
324 for (RoleInAppForUser appRole : newAppRolesForUser.appRoles) {
325 if (appRole.isApplied) {
326 sbUserApps.append(appRole.roleName + " ,");
329 sbUserApps.deleteCharAt(sbUserApps.length() - 1);
330 sbUserApps.append("} assigned for the app " + newAppRolesForUser.appId);
332 sbUserApps.append("' has no roles assigned for app " + newAppRolesForUser.appId);
335 logger.info(EELFLoggerDelegate.applicationLogger, "putAppWithUserRoleStateForUser: {}", sbUserApps.toString());
337 EPUser user = EPUserUtils.getUserSession(request);
338 boolean changesApplied = false;
339 if (!adminRolesService.isAccountAdmin(user)) {
340 EcompPortalUtils.setBadPermissions(user, response, "putAppWithUserRoleStateForUser");
342 changesApplied = userRolesService.setAppWithUserRoleStateForUser(user, newAppRolesForUser);
343 if (changesApplied) {
344 logger.info(EELFLoggerDelegate.applicationLogger,
345 "putAppWithUserRoleStateForUser: succeeded for app {}, user {}", newAppRolesForUser.appId,
346 newAppRolesForUser.orgUserId);
347 AuditLog auditLog = new AuditLog();
348 auditLog.setUserId(user.getId());
349 auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_USER);
350 auditLog.setAffectedRecordId(newAppRolesForUser.orgUserId);
351 auditLog.setComments(sbUserApps.toString());
352 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
353 auditService.logActivity(auditLog, null);
354 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
355 EcompPortalUtils.calculateDateTimeDifferenceForLog(
356 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
357 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
358 logger.info(EELFLoggerDelegate.auditLogger,
359 EPLogUtil.formatAuditLogMessage("UserRolesController.putAppWithUserRoleStateForUser",
360 EcompAuditLog.CD_ACTIVITY_UPDATE_USER, user.getOrgUserId(),
361 newAppRolesForUser.orgUserId, sbUserApps.toString()));
362 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
363 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
364 MDC.remove(SystemProperties.MDC_TIMER);
366 logger.error(EELFLoggerDelegate.errorLogger,
367 "putAppWithUserRoleStateForUser: failed for app {}, user {}", newAppRolesForUser.appId,
368 newAppRolesForUser.orgUserId);
372 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "put result =", changesApplied);
373 return fieldsValidator;
376 @RequestMapping(value = { "/portalApi/updateRemoteUserProfile" }, method = {
377 RequestMethod.GET }, produces = "application/json")
378 public PortalRestResponse<String> updateRemoteUserProfile(HttpServletRequest request,
379 HttpServletResponse response) {
381 String updateRemoteUserFlag = FAILURE;
383 // saveNewUser = userService.saveNewUser(newUser);
384 String orgUserId = request.getParameter("loginId");
385 Long appId = Long.parseLong(request.getParameter("appId"));
386 userRolesService.updateRemoteUserProfile(orgUserId, appId);
388 } catch (Exception e) {
389 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, updateRemoteUserFlag, e.getMessage());
391 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, updateRemoteUserFlag, "");
395 @RequestMapping(value = { "/portalApi/app/{appId}/users" }, method = {
396 RequestMethod.GET }, produces = "application/json")
397 public List<UserApplicationRoles> getUsersFromAppEndpoint(HttpServletRequest request,
398 @PathVariable("appId") Long appId) throws HTTPException {
400 logger.debug(EELFLoggerDelegate.debugLogger, "/portalApi/app/{}/users was invoked", appId);
401 List<UserApplicationRoles> appUsers = userRolesService.getUsersFromAppEndpoint(appId);
403 } catch (Exception e) {
404 logger.error(EELFLoggerDelegate.errorLogger,
405 "Exception occurred while performing UserRolesController.getUsersFromAppEndpoint. Details: "
406 + EcompPortalUtils.getStackTrace(e));
407 return new ArrayList<UserApplicationRoles>();
411 @RequestMapping(value = { "/portalApi/app/{appId}/roles" }, method = {
412 RequestMethod.GET }, produces = "application/json")
413 public List<EcompRole> testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId)
414 throws HTTPException {
415 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
416 List<EcompRole> rolesList = Arrays.asList(appRoles);
417 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/roles", "response for appId=" + appId,
423 @RequestMapping(value = { "/portalApi/admin/import/app/{appId}/roles" }, method = {
424 RequestMethod.GET }, produces = "application/json")
425 public List<EPRole> importRolesFromRemoteApplication(HttpServletRequest request, @PathVariable("appId") Long appId)
426 throws HTTPException {
427 List<EPRole> rolesList = userRolesService.importRolesFromRemoteApplication(appId);
428 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/admin/import/app/{appId}/roles",
429 "response for appId=" + appId, rolesList);
434 @RequestMapping(value = { "/portalApi/app/{appId}/user/{orgUserId}/roles" }, method = {
435 RequestMethod.GET }, produces = "application/json")
436 public EcompRole testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId,
437 @PathVariable("orgUserId") String orgUserId) throws Exception {
438 if (!EcompPortalUtils.legitimateUserId(orgUserId)) {
439 String msg = "Error /user/<user>/roles not legitimate orgUserId = " + orgUserId;
440 logger.error(EELFLoggerDelegate.errorLogger, msg);
441 throw new Exception(msg);
443 EcompRole[] roles = applicationsRestClientService.get(EcompRole[].class, appId,
444 String.format("/user/%s/roles", orgUserId));
445 if (roles.length != 1) {
446 String msg = "Error /user/<user>/roles returned array. expected size 1 recieved size = " + roles.length;
447 logger.error(EELFLoggerDelegate.errorLogger, msg);
448 throw new Exception(msg);
451 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/user/{orgUserId}/roles",
452 "response for appId='" + appId + "' and orgUserId='" + orgUserId + "'", roles[0]);
456 @RequestMapping(value = { "/portalApi/saveUserAppRoles" }, method = {
457 RequestMethod.PUT }, produces = "application/json")
458 public FieldsValidator putAppWithUserRoleRequest(HttpServletRequest request,
459 @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) {
460 FieldsValidator fieldsValidator = null;
463 EPUser user = EPUserUtils.getUserSession(request);
464 fieldsValidator = userRolesService.putUserAppRolesRequest(newAppRolesForUser, user);
465 response.setStatus(fieldsValidator.httpStatusCode.intValue());
467 } catch (Exception e) {
468 logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleRequest failed", e);
471 // return fieldsValidator;
472 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/saveUserAppRoles", "PUT result =",
473 response.getStatus());
474 return fieldsValidator;
477 @RequestMapping(value = { "/portalApi/appCatalogRoles" }, method = {
478 RequestMethod.GET }, produces = "application/json")
479 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(HttpServletRequest request,
480 @RequestParam("appName") String appName) {
481 EPUser user = EPUserUtils.getUserSession(request);
482 List<EPUserAppCatalogRoles> userAppRoleList = null;
484 userAppRoleList = userRolesService.getUserAppCatalogRoles(user, appName);
485 } catch (Exception e) {
486 logger.error(EELFLoggerDelegate.errorLogger, "putUserWidgetsSortPref failed", e);
489 Collections.sort(userAppRoleList, getUserAppCatalogRolesComparator);
490 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userApplicationRoles", "result =", userAppRoleList);
492 return userAppRoleList;
496 private Comparator<EPUserAppCatalogRoles> getUserAppCatalogRolesComparator = new Comparator<EPUserAppCatalogRoles>() {
497 public int compare(EPUserAppCatalogRoles o1, EPUserAppCatalogRoles o2) {
498 return o1.getRolename().compareTo(o2.getRolename());
502 @RequestMapping(value = "/portalApi/externalRequestAccessSystem", method = RequestMethod.GET, produces = "application/json")
503 public ExternalSystemAccess readExternalRequestAccess(HttpServletRequest request) {
504 ExternalSystemAccess result = null;
506 result = userRolesService.getExternalRequestAccess();
507 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/externalRequestAccessSystem", "GET result =",
509 } catch (Exception e) {
510 logger.error(EELFLoggerDelegate.errorLogger, "readExternalRequestAccess failed: " + e.getMessage());