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.service.RoleService;
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 {
78 SearchService searchService;
80 AdminRolesService adminRolesService;
82 UserRolesService userRolesService;
84 ApplicationsRestClientService applicationsRestClientService;
86 RoleService roleService;
88 AuditService auditService;
89 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesController.class);
91 static final String FAILURE = "failure";
94 * RESTful service method to fetch users in the WebPhone external service
96 * @return array of found users as json
98 @RequestMapping(value = { "/portalApi/queryUsers" }, method = RequestMethod.GET, produces = "application/json")
99 public String getPhoneBookSearchResult(HttpServletRequest request, @RequestParam("search") String searchString, HttpServletResponse response) {
100 EPUser user = EPUserUtils.getUserSession(request);
101 String searchResult = null;
102 if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdmin(user)) {
103 EcompPortalUtils.setBadPermissions(user, response, "getPhoneBookSearchResult");
105 searchString = searchString.trim();
106 if (searchString.length() > 2) {
107 searchResult = searchService.searchUsersInPhoneBook(searchString);
109 logger.info(EELFLoggerDelegate.errorLogger, "getPhoneBookSearchResult - too short search string: " + searchString);
112 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/queryUsers", "result =", searchResult);
118 * RESTful service method to fetch applications where user is admin
120 * @return for GET: array of all applications with boolean isAdmin=true/false for each application
122 @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = { RequestMethod.GET }, produces = "application/json")
123 public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(HttpServletRequest request, @RequestParam("user") String orgUserId,
124 HttpServletResponse response) {
126 EPUser user = EPUserUtils.getUserSession(request);
127 AppsListWithAdminRole result = null;
128 if (!adminRolesService.isSuperAdmin(user)) {
129 EcompPortalUtils.setBadPermissions(user, response, "getAppsWithAdminRoleStateForUser");
131 if (EcompPortalUtils.legitimateUserId(orgUserId)) {
132 result = adminRolesService.getAppsWithAdminRoleStateForUser(orgUserId);
134 logger.info(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser - parms error, no Organization User ID");
135 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
139 StringBuilder adminAppRoles = new StringBuilder();
140 if(result != null && result.appsRoles.size() >= 1) {
141 adminAppRoles.append("User '" + result.orgUserId + "' has admin role to the apps = {");
142 for(AppNameIdIsAdmin adminAppRole : result.appsRoles) {
143 if (adminAppRole.isAdmin) {
144 adminAppRoles.append(adminAppRole.appName + ", ");
147 adminAppRoles.append("}.");
149 adminAppRoles.append("User '" + result.orgUserId + "' has no Apps with Admin Role.");
151 logger.info(EELFLoggerDelegate.errorLogger, adminAppRoles.toString());
153 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "get result =", result);
158 @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = { RequestMethod.PUT }, produces = "application/json")
159 public FieldsValidator putAppsWithAdminRoleStateForUser(HttpServletRequest request, @RequestBody AppsListWithAdminRole newAppsListWithAdminRoles,
160 HttpServletResponse response) {
162 //newAppsListWithAdminRoles.appsRoles
163 FieldsValidator fieldsValidator = new FieldsValidator();
164 StringBuilder newAppRoles = new StringBuilder();
165 if(newAppsListWithAdminRoles != null && newAppsListWithAdminRoles.appsRoles.size() >= 1) {
166 newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has admin role to the apps = { ");
167 for(AppNameIdIsAdmin adminAppRole : newAppsListWithAdminRoles.appsRoles) {
168 if (adminAppRole.isAdmin) {
169 newAppRoles.append(adminAppRole.appName + " ,");
172 newAppRoles.deleteCharAt(newAppRoles.length()-1);
173 newAppRoles.append("}.");
175 newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has no Apps with Admin Role.");
177 logger.info(EELFLoggerDelegate.errorLogger, newAppRoles.toString());
179 EPUser user = EPUserUtils.getUserSession(request);
180 boolean changesApplied = false;
182 if (!adminRolesService.isSuperAdmin(user)) {
183 EcompPortalUtils.setBadPermissions(user, response, "putAppsWithAdminRoleStateForUser");
185 changesApplied = adminRolesService.setAppsWithAdminRoleStateForUser(newAppsListWithAdminRoles);
186 AuditLog auditLog = new AuditLog();
187 auditLog.setUserId(user.getId());
188 auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN);
189 auditLog.setAffectedRecordId(newAppsListWithAdminRoles.orgUserId);
190 auditLog.setComments(newAppRoles.toString());
191 auditService.logActivity(auditLog, null);
193 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
194 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
195 logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("UserRolesController.putAppsWithAdminRoleStateForUser",
196 EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN, user.getOrgUserId(), newAppsListWithAdminRoles.orgUserId, newAppRoles.toString()));
197 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
198 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
200 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "put result =", changesApplied);
202 return fieldsValidator;
205 @RequestMapping(value = { "/portalApi/userAppRoles" }, method = { RequestMethod.GET }, produces = "application/json")
206 public List<RoleInAppForUser> getAppRolesForUser(HttpServletRequest request, @RequestParam("user") String orgUserId, @RequestParam("app") Long appid, HttpServletResponse response) {
207 EPUser user = EPUserUtils.getUserSession(request);
208 List<RoleInAppForUser> result = null;
209 String feErrorString = "";
210 if (!adminRolesService.isAccountAdmin(user)) {
211 EcompPortalUtils.setBadPermissions(user, response, "getAppRolesForUser");
212 feErrorString = EcompPortalUtils.getFEErrorString(true, response.getStatus());
214 if (EcompPortalUtils.legitimateUserId(orgUserId)) {
215 result = userRolesService.getAppRolesForUser(appid, orgUserId);
216 int responseCode = EcompPortalUtils.getExternalAppResponseCode();
217 if (responseCode != 0 && responseCode != 200) {
219 response.setStatus(responseCode);
220 feErrorString = EcompPortalUtils.getFEErrorString(false, responseCode);
221 } else if (result == null) {
222 // If the result is null, there was an internal ecomp error in the service call.
223 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
224 feErrorString = EcompPortalUtils.getFEErrorString(true, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
227 logger.info(EELFLoggerDelegate.errorLogger, "getAppRolesForUser - no Organization User ID");
228 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
229 feErrorString = EcompPortalUtils.getFEErrorString(true, HttpServletResponse.SC_BAD_REQUEST);
233 StringBuilder sbUserApps = new StringBuilder();
234 if (result!=null && result.size()>=1) {
235 sbUserApps.append("User '" + orgUserId + "' has Roles={");
236 for(RoleInAppForUser appRole : result) {
237 if (appRole.isApplied) {
238 sbUserApps.append(appRole.roleName + ", ");
241 sbUserApps.append("} assigned to the appId '" + appid + "'.");
243 //Not sure creating an empty object will make any difference
244 //but would like to give it a shot for defect #DE221057
246 result = new ArrayList<RoleInAppForUser>();
248 sbUserApps.append("User '" + orgUserId + "' and appid " + appid + " has no roles");
250 logger.info(EELFLoggerDelegate.errorLogger, sbUserApps.toString());
252 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "get result =", result);
253 if (feErrorString != "") {
254 logger.debug(EELFLoggerDelegate.debugLogger, "LR: FEErrorString to header: "+feErrorString);
256 response.addHeader("FEErrorString", feErrorString);
257 response.addHeader("Access-Control-Expose-Headers", "FEErrorString");
262 @RequestMapping(value = { "/portalApi/userAppRoles" }, method = { RequestMethod.PUT }, produces = "application/json")
263 public FieldsValidator putAppWithUserRoleStateForUser(HttpServletRequest request, @RequestBody AppWithRolesForUser newAppRolesForUser,
264 HttpServletResponse response) {
265 FieldsValidator fieldsValidator = new FieldsValidator();
266 StringBuilder sbUserApps = new StringBuilder();
267 if (newAppRolesForUser!=null) {
268 sbUserApps.append("User '" + newAppRolesForUser.orgUserId);
269 if (newAppRolesForUser.appRoles!=null && newAppRolesForUser.appRoles.size()>=1) {
270 sbUserApps.append("' has roles = { ");
271 for(RoleInAppForUser appRole : newAppRolesForUser.appRoles) {
272 if (appRole.isApplied) {
273 sbUserApps.append(appRole.roleName + " ,");
276 sbUserApps.deleteCharAt(sbUserApps.length()-1);
277 sbUserApps.append("} assigned for the app " + newAppRolesForUser.appId);
279 sbUserApps.append("' has no roles assigned for app " + newAppRolesForUser.appId);
282 logger.info(EELFLoggerDelegate.applicationLogger, "putAppWithUserRoleStateForUser: {}", sbUserApps.toString());
284 EPUser user = EPUserUtils.getUserSession(request);
285 boolean changesApplied = false;
286 if (!adminRolesService.isAccountAdmin(user)) {
287 EcompPortalUtils.setBadPermissions(user, response, "putAppWithUserRoleStateForUser");
289 changesApplied = userRolesService.setAppWithUserRoleStateForUser(user, newAppRolesForUser);
291 logger.info(EELFLoggerDelegate.applicationLogger, "putAppWithUserRoleStateForUser: succeeded for app {}, user {}",
292 newAppRolesForUser.appId, newAppRolesForUser.orgUserId);
293 AuditLog auditLog = new AuditLog();
294 auditLog.setUserId(user.getId());
295 auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_USER);
296 auditLog.setAffectedRecordId(newAppRolesForUser.orgUserId);
297 auditLog.setComments(sbUserApps.toString());
298 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
299 auditService.logActivity(auditLog, null);
300 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
301 logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("UserRolesController.putAppWithUserRoleStateForUser",
302 EcompAuditLog.CD_ACTIVITY_UPDATE_USER, user.getOrgUserId(), newAppRolesForUser.orgUserId, sbUserApps.toString()));
303 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
304 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
306 logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleStateForUser: failed for app {}, user {}",
307 newAppRolesForUser.appId, newAppRolesForUser.orgUserId);
311 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "put result =", changesApplied);
312 return fieldsValidator;
315 @RequestMapping(value = { "/portalApi/updateRemoteUserProfile" }, method = { RequestMethod.GET }, produces = "application/json")
316 public PortalRestResponse<String> updateRemoteUserProfile(HttpServletRequest request,HttpServletResponse response) {
318 String updateRemoteUserFlag = FAILURE;
320 //saveNewUser = userService.saveNewUser(newUser);
321 String orgUserId = request.getParameter("loginId");
322 Long appId = Long.parseLong(request.getParameter("appId"));
323 userRolesService.updateRemoteUserProfile(orgUserId, appId);
325 } catch (Exception e) {
326 return new PortalRestResponse<String>(PortalRestStatusEnum.OK, updateRemoteUserFlag, e.getMessage());
328 return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, updateRemoteUserFlag, "");
332 @RequestMapping(value = { "/portalApi/app/{appId}/users" }, method = { RequestMethod.GET }, produces = "application/json")
333 public List<UserApplicationRoles> getUsersFromAppEndpoint(HttpServletRequest request, @PathVariable("appId") Long appId) throws HTTPException {
335 logger.debug(EELFLoggerDelegate.debugLogger, "/portalApi/app/{}/users was invoked", appId);
336 List<UserApplicationRoles> appUsers = userRolesService.getUsersFromAppEndpoint(appId);
338 } catch(Exception e) {
339 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing UserRolesController.getUsersFromAppEndpoint. Details: " + EcompPortalUtils.getStackTrace(e));
340 return new ArrayList<UserApplicationRoles>();
344 @RequestMapping(value = { "/portalApi/app/{appId}/roles" }, method = { RequestMethod.GET }, produces = "application/json")
345 public List<EcompRole> testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId) throws HTTPException {
346 EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
347 List<EcompRole> rolesList = Arrays.asList(appRoles);
348 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/roles", "response for appId=" + appId, rolesList);
353 @RequestMapping(value = { "/portalApi/admin/import/app/{appId}/roles" }, method = { RequestMethod.GET }, produces = "application/json")
354 public List<EPRole> importRolesFromRemoteApplication(HttpServletRequest request, @PathVariable("appId") Long appId) throws HTTPException {
355 List<EPRole> rolesList = userRolesService.importRolesFromRemoteApplication(appId);
356 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/admin/import/app/{appId}/roles", "response for appId=" + appId, rolesList);
361 @RequestMapping(value = { "/portalApi/app/{appId}/user/{orgUserId}/roles" }, method = { RequestMethod.GET }, produces = "application/json")
362 public EcompRole testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId, @PathVariable("orgUserId") String orgUserId) throws Exception {
363 if (!EcompPortalUtils.legitimateUserId(orgUserId)) {
364 String msg = "Error /user/<user>/roles not legitimate orgUserId = " + orgUserId;
365 logger.error(EELFLoggerDelegate.errorLogger, msg);
366 throw new Exception(msg);
368 EcompRole[] roles = applicationsRestClientService.get(EcompRole[].class, appId, String.format("/user/%s/roles", orgUserId));
369 if (roles.length != 1) {
370 String msg = "Error /user/<user>/roles returned array. expected size 1 recieved size = " + roles.length;
371 logger.error(EELFLoggerDelegate.errorLogger, msg);
372 throw new Exception(msg);
375 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/user/{orgUserId}/roles", "response for appId='" + appId + "' and orgUserId='" + orgUserId + "'", roles[0]);
379 @RequestMapping(value = { "/portalApi/saveUserAppRoles" }, method = { RequestMethod.PUT }, produces = "application/json")
380 public FieldsValidator putAppWithUserRoleRequest(HttpServletRequest request, @RequestBody AppWithRolesForUser newAppRolesForUser,
381 HttpServletResponse response) {
382 FieldsValidator fieldsValidator = null;
385 EPUser user = EPUserUtils.getUserSession(request);
386 fieldsValidator = userRolesService.putUserAppRolesRequest(newAppRolesForUser, user);
387 response.setStatus(fieldsValidator.httpStatusCode.intValue());
389 } catch (Exception e) {
390 logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleRequest failed", e);
393 // return fieldsValidator;
394 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/saveUserAppRoles", "PUT result =",
395 response.getStatus());
396 return fieldsValidator;
399 @RequestMapping(value = { "/portalApi/appCatalogRoles" }, method = {
400 RequestMethod.GET }, produces = "application/json")
401 public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(HttpServletRequest request,
402 @RequestParam("appName") String appName) {
403 EPUser user = EPUserUtils.getUserSession(request);
404 List<EPUserAppCatalogRoles> userAppRoleList = null;
406 userAppRoleList = userRolesService.getUserAppCatalogRoles(user, appName);
407 } catch (Exception e) {
408 logger.error(EELFLoggerDelegate.errorLogger, "putUserWidgetsSortPref failed", e);
411 Collections.sort(userAppRoleList, getUserAppCatalogRolesComparator);
412 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userApplicationRoles", "result =", userAppRoleList);
414 return userAppRoleList;
417 private Comparator<EPUserAppCatalogRoles> getUserAppCatalogRolesComparator = new Comparator<EPUserAppCatalogRoles>() {
418 public int compare(EPUserAppCatalogRoles o1, EPUserAppCatalogRoles o2) {
419 return o1.getRolename().compareTo(o2.getRolename());
423 @RequestMapping(value = "/portalApi/externalRequestAccessSystem", method = RequestMethod.GET, produces = "application/json")
424 public ExternalSystemAccess readExternalRequestAccess(HttpServletRequest request) {
425 ExternalSystemAccess result = null;
427 result = userRolesService.getExternalRequestAccess();
428 EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/externalRequestAccessSystem", "GET result =", result);
429 } catch (Exception e) {
430 logger.error(EELFLoggerDelegate.errorLogger,"readExternalRequestAccess failed: " + e.getMessage());