2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
7 * Modifications Copyright (c) 2019 Samsung
8 * ===================================================================
9 * Modifications Copyright (c) 2020 IBM
10 * ===================================================================
12 * Unless otherwise specified, all software contained herein is licensed
13 * under the Apache License, Version 2.0 (the "License");
14 * you may not use this software except in compliance with the License.
15 * You may obtain a copy of the License at
17 * http://www.apache.org/licenses/LICENSE-2.0
19 * Unless required by applicable law or agreed to in writing, software
20 * distributed under the License is distributed on an "AS IS" BASIS,
21 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 * See the License for the specific language governing permissions and
23 * limitations under the License.
25 * Unless otherwise specified, all documentation contained herein is licensed
26 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
27 * you may not use this documentation except in compliance with the License.
28 * You may obtain a copy of the License at
30 * https://creativecommons.org/licenses/by/4.0/
32 * Unless required by applicable law or agreed to in writing, documentation
33 * distributed under the License is distributed on an "AS IS" BASIS,
34 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
35 * See the License for the specific language governing permissions and
36 * limitations under the License.
38 * ============LICENSE_END============================================
42 package org.onap.portalapp.portal.controller;
44 import java.io.IOException;
45 import java.util.HashMap;
46 import java.util.Iterator;
47 import java.util.List;
50 import java.util.TreeSet;
51 import javax.servlet.http.HttpServletRequest;
52 import javax.servlet.http.HttpServletResponse;
53 import javax.validation.ConstraintViolation;
54 import javax.validation.Valid;
55 import javax.validation.Validation;
56 import javax.validation.Validator;
57 import javax.validation.ValidatorFactory;
58 import org.apache.commons.lang.StringUtils;
59 import org.json.JSONObject;
60 import org.onap.portalapp.controller.EPRestrictedBaseController;
61 import org.onap.portalapp.controller.core.RoleController;
62 import org.onap.portalapp.controller.core.RoleListController;
63 import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
64 import org.onap.portalapp.portal.domain.CentralizedApp;
65 import org.onap.portalapp.portal.domain.EPApp;
66 import org.onap.portalapp.portal.domain.EPUser;
67 import org.onap.portalapp.portal.domain.EcompAuditLog;
68 import org.onap.portalapp.portal.ecomp.model.PortalRestResponse;
69 import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
70 import org.onap.portalapp.portal.ecomp.model.UploadRoleFunctionExtSystem;
71 import org.onap.portalapp.portal.exceptions.DuplicateRecordException;
72 import org.onap.portalapp.portal.exceptions.InvalidApplicationException;
73 import org.onap.portalapp.portal.exceptions.InvalidRoleException;
74 import org.onap.portalapp.portal.exceptions.NonCentralizedAppException;
75 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
76 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
77 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
78 import org.onap.portalapp.portal.service.AdminRolesService;
79 import org.onap.portalapp.portal.service.EPAppService;
80 import org.onap.portalapp.portal.service.ExternalAccessRolesService;
81 import org.onap.portalapp.portal.transport.CentralV2Role;
82 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
83 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
84 import org.onap.portalapp.portal.utils.EcompPortalUtils;
85 import org.onap.portalapp.portal.utils.PortalConstants;
86 import org.onap.portalapp.util.EPUserUtils;
87 import org.onap.portalapp.validation.SecureString;
88 import org.onap.portalsdk.core.domain.AuditLog;
89 import org.onap.portalsdk.core.domain.Role;
90 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
91 import org.onap.portalsdk.core.service.AuditService;
92 import org.onap.portalsdk.core.util.SystemProperties;
93 import org.onap.portalsdk.core.web.support.JsonMessage;
95 import org.springframework.beans.factory.annotation.Autowired;
96 import org.springframework.context.annotation.EnableAspectJAutoProxy;
97 import org.springframework.http.ResponseEntity;
98 import org.springframework.web.bind.annotation.PathVariable;
99 import org.springframework.web.bind.annotation.RequestBody;
100 import org.springframework.web.bind.annotation.RequestMapping;
101 import org.springframework.web.bind.annotation.PostMapping;
102 import org.springframework.web.bind.annotation.GetMapping;
103 import org.springframework.web.bind.annotation.RequestMethod;
104 import org.springframework.web.bind.annotation.RestController;
105 import org.springframework.web.servlet.ModelAndView;
106 import com.fasterxml.jackson.databind.DeserializationFeature;
107 import com.fasterxml.jackson.databind.JsonNode;
108 import com.fasterxml.jackson.databind.ObjectMapper;
109 import com.fasterxml.jackson.databind.type.TypeFactory;
112 * Proxies REST calls to role-management functions that arrive on paths
113 * /portalApi/* over to controller methods provided by the SDK-Core library.
114 * Those controller methods are mounted on paths not exposed by the Portal FE.
117 @org.springframework.context.annotation.Configuration
118 @EnableAspectJAutoProxy
120 public class RoleManageController extends EPRestrictedBaseController {
121 private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();
123 private static final String PIPE = "|";
125 private static final String ROLE_INVALID_CHARS = "%=():,\"\"";
127 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleManageController.class);
130 private RoleController roleController;
133 private RoleListController roleListController;
136 private EPAppService appService;
139 private AuditService auditService;
142 private ExternalAccessRolesService externalAccessRolesService;
145 private AdminRolesService adminRolesService;
148 * Calls an SDK-Core library method that gets the available roles and writes
149 * them to the request object. Portal specifies a Hibernate mappings from the
150 * Role class to the fn_role_v view, which ensures that only Portal (app_id is
151 * null) roles are fetched.
153 * Any method declared void (no return value) or returning null causes the audit
154 * log aspect method to declare failure. TODO: should return a JSON string.
161 @GetMapping(value = { "/portalApi/get_roles/{appId}" })
162 public void getRoles(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId)
165 EPUser user = EPUserUtils.getUserSession(request);
166 EPApp requestedApp = appService.getApp(appId);
167 if (isAuthorizedUser(user, requestedApp)) {
168 fieldsValidation(requestedApp);
169 if (requestedApp.getCentralAuth()) {
170 List<CentralV2Role> answer = null;
171 Map<String, Object> model = new HashMap<>();
172 ObjectMapper mapper = new ObjectMapper();
173 answer = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey());
174 model.put("availableRoles", answer);
175 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
176 JSONObject j = new JSONObject(msg);
177 response.getWriter().write(j.toString());
179 throw new NonCentralizedAppException(requestedApp.getName());
181 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.getRoles, Unauthorized user");
182 SendErrorForUnauthorizedUser(response, user);
185 } catch (Exception e) {
186 logger.error(EELFLoggerDelegate.errorLogger, "getRoles failed", e);
190 @PostMapping(value = { "/portalApi/role_list/toggleRole/{appId}/{roleId}" })
191 public Map<String, Object> toggleRole(HttpServletRequest request, HttpServletResponse response,
192 @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception {
193 EPApp requestedApp = null;
194 String restcallStatus = null;
195 HashMap<String, Object> responseMap = new HashMap<>();
196 EPUser user = EPUserUtils.getUserSession(request);
198 requestedApp = appService.getApp(appId);
199 if (isAuthorizedUser(user, requestedApp)) {
200 fieldsValidation(requestedApp);
201 ObjectMapper mapper = new ObjectMapper();
202 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
203 CentralV2Role domainRole = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
204 // role. toggle active ind
205 boolean active = domainRole.getActive();
206 domainRole.setActive(!active);
208 String result = mapper.writeValueAsString(domainRole);
209 Role newRole = externalAccessRolesService.ConvertCentralRoleToRole(result);
210 ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService
211 .saveRoleForApplication(newRole, requestedApp.getUebKey());
212 boolean getAddResponse = externalRequestFieldsValidator.isResult();
213 if (getAddResponse) {
214 restcallStatus = "Success";
215 logger.info(EELFLoggerDelegate.auditLogger, "Toggle active status for role " + domainRole.getId());
217 restcallStatus = "Toggle Role Failed";
218 logger.info(EELFLoggerDelegate.auditLogger, "Toggle Role Failed " + domainRole.getId());
220 responseMap.put("restcallStatus", restcallStatus);
221 responseMap.put("availableRoles", externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()));
223 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.toggleRole, Unauthorized user");
224 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
225 responseMap.put("restcallStatus", " Unauthorized user");
227 } catch (Exception e) {
228 logger.error(EELFLoggerDelegate.errorLogger, "toggleRole failed", e);
234 @PostMapping(value = { "/portalApi/role_list/removeRole/{appId}/{roleId}" })
235 public Map<String, Object> removeRole(HttpServletRequest request, HttpServletResponse response,
236 @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception {
238 EPUser user = EPUserUtils.getUserSession(request);
239 EPApp requestedApp = null;
240 String restCallStatus = null;
241 HashMap<String, Object> responseMap = new HashMap<>();
242 ExternalRequestFieldsValidator externalRequestFieldsValidator = null;
244 requestedApp = appService.getApp(appId);
245 if (isAuthorizedUser(user, requestedApp)) {
246 fieldsValidation(requestedApp);
247 if (requestedApp.getCentralAuth()) {
248 externalRequestFieldsValidator = externalAccessRolesService.deleteDependencyRoleRecord(roleId,
249 requestedApp.getUebKey(), user.getOrgUserId());
250 boolean deleteResponse = externalRequestFieldsValidator.isResult();
251 if (deleteResponse) {
252 restCallStatus = "Success";
253 EPUser requestedUser = (EPUser) externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
254 EPApp app = (EPApp) externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
255 logger.info(EELFLoggerDelegate.applicationLogger, "deleteRole: succeeded for app {}, role {}",
256 app.getId(), roleId);
257 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE;
258 AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
259 auditLog.setComments(EcompPortalUtils.truncateString(
260 "Deleted role for app:" + app.getId() + " and role:'" + roleId + "'",
261 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
262 auditService.logActivity(auditLog, null);
263 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
264 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
265 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
266 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
267 EcompPortalUtils.calculateDateTimeDifferenceForLog(
268 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
269 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
270 logger.info(EELFLoggerDelegate.auditLogger,
271 EPLogUtil.formatAuditLogMessage("RoleManageController.removeRole",
272 EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE,
273 String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(),
275 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
276 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
277 MDC.remove(SystemProperties.MDC_TIMER);
279 restCallStatus = "Remove Role failed";
280 responseMap.put("error", externalRequestFieldsValidator.getDetailMessage());
281 logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed");
283 responseMap.put("restCallStatus", restCallStatus);
284 responseMap.put("availableRoles",
285 externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()));
287 throw new NonCentralizedAppException(requestedApp.getName());
289 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.removeRole, Unauthorized user");
290 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
291 responseMap.put("restCallStatus", " Unauthorized user");
293 } catch (Exception e) {
294 logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed", e);
300 @PostMapping(value = { "/portalApi/role/saveRole/{appId}" })
301 public Map<String, Object> saveRole(HttpServletRequest request, HttpServletResponse response,
302 @PathVariable("appId") Long appId) throws Exception {
303 EPUser user = EPUserUtils.getUserSession(request);
304 String responseString = null;
305 HashMap<String, Object> responseMap = new HashMap<>();
307 EPApp requestedApp = appService.getApp(appId);
308 if (isAuthorizedUser(user, requestedApp)) {
309 fieldsValidation(requestedApp);
310 if (requestedApp != null && requestedApp.getCentralAuth().equals(true)) {
311 ObjectMapper mapper = new ObjectMapper();
312 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
313 JsonNode root = mapper.readTree(request.getReader());
314 CentralV2Role role = mapper.readValue(root.get("role").toString(), CentralV2Role.class);
316 List<CentralV2Role> childRoles = mapper.readValue(root.get("childRoles").toString(),
317 TypeFactory.defaultInstance().constructCollectionType(List.class, CentralV2Role.class));
318 List<CentralV2RoleFunction> roleFunctions = mapper.readValue(root.get("roleFunctions").toString(),
319 TypeFactory.defaultInstance().constructCollectionType(List.class,
320 CentralV2RoleFunction.class));
321 if (role.getId() != null && StringUtils.containsAny(role.getName(), ROLE_INVALID_CHARS)) {
322 throw new InvalidRoleException("Invalid role name found for '" + role.getName()
323 + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
325 CentralV2Role domainRole;
326 if (role.getId() != null) {
327 domainRole = externalAccessRolesService.getRoleInfo(role.getId(), requestedApp.getUebKey());
328 domainRole.setName(role.getName());
329 domainRole.setPriority(role.getPriority());
331 // check for existing role of same name
332 List<CentralV2Role> roles = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey());
333 for (CentralV2Role existRole : roles)
334 if (existRole.getName().equalsIgnoreCase(role.getName()))
335 throw new DuplicateRecordException("Role already exists: " + existRole.getName());
337 domainRole = new CentralV2Role.CentralV2RoleBuilder().createCentralV2Role();
338 domainRole.setName(role.getName());
339 domainRole.setPriority(role.getPriority());
340 domainRole.setActive(role.getActive());
341 if (role.getChildRoles() != null && role.getChildRoles().size() > 0) {
342 for (Object childRole : childRoles) {
343 domainRole.addChildRole((CentralV2Role) childRole);
347 if (role.getRoleFunctions() != null && role.getRoleFunctions().size() > 0) {
348 domainRole.setRoleFunctions(new TreeSet<CentralV2RoleFunction>());
349 for (CentralV2RoleFunction roleFunction : roleFunctions) {
350 if (roleFunction.getType() == null && roleFunction.getAction() == null) {
351 throw new InvalidRoleException("Invalid role function type:" + roleFunction.getType()
352 + " and action: " + roleFunction.getAction() + " found while saving!");
354 if (EcompPortalUtils.checkFunctionCodeHasEncodePattern(roleFunction.getCode()))
355 roleFunction.setCode(roleFunction.getType() + PIPE
356 + EcompPortalUtils.encodeFunctionCode(roleFunction.getCode()) + PIPE
357 + roleFunction.getAction());
359 roleFunction.setCode(roleFunction.getType() + PIPE + roleFunction.getCode() + PIPE
360 + roleFunction.getAction());
361 domainRole.addRoleFunction((CentralV2RoleFunction) roleFunction);
364 domainRole.setRoleFunctions(new TreeSet<>());
366 String result = mapper.writeValueAsString(domainRole);
367 Role newRole = externalAccessRolesService.ConvertCentralRoleToRole(result);
368 ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService
369 .saveRoleForApplication(newRole, requestedApp.getUebKey());
370 boolean getAddResponse = externalRequestFieldsValidator.isResult();
371 if (getAddResponse) {
372 String activityCode = (role.getId() == null) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_ROLE
373 : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
374 logger.info(EELFLoggerDelegate.applicationLogger, "saveRole: succeeded for app {}, role {}",
375 requestedApp.getId(), role.getName());
376 AuditLog auditLog = new AuditLog();
377 auditLog.setUserId(user.getId());
378 auditLog.setActivityCode(activityCode);
379 auditLog.setComments(EcompPortalUtils.truncateString(
380 "saveRole role for app:" + requestedApp.getId() + " and role:'" + role.getName() + "'",
381 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
382 auditLog.setAffectedRecordId(user.getOrgUserId());
383 auditService.logActivity(auditLog, null);
384 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
385 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
386 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
387 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
388 EcompPortalUtils.calculateDateTimeDifferenceForLog(
389 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
390 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
391 logger.info(EELFLoggerDelegate.auditLogger,
392 EPLogUtil.formatAuditLogMessage("RoleManageController.saveRole", activityCode,
393 String.valueOf(user.getId()), user.getOrgUserId(), role.getName()));
394 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
395 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
396 MDC.remove(SystemProperties.MDC_TIMER);
397 responseMap.put("status", "Success");
398 responseMap.put("role", domainRole);
400 if (externalRequestFieldsValidator.getDetailMessage().contains("406")) {
401 externalRequestFieldsValidator.setDetailMessage("Failed to save role for '" + role.getName()
402 + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
404 responseMap.put("status", "SaveRole Failed");
405 responseMap.put("role", responseString);
406 responseMap.put("error", externalRequestFieldsValidator.getDetailMessage());
407 logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed");
411 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRole, Unauthorized user");
412 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
413 responseMap.put("error", " Unauthorized user");
415 } catch (Exception e) {
416 logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e);
417 responseMap.put("error", e.getMessage());
422 @PostMapping(value = { "/portalApi/role/removeRoleFunction" })
423 public ModelAndView removeRoleRoleFunction(HttpServletRequest request, HttpServletResponse response)
425 return getRoleController().removeRoleFunction(request, response);
428 @PostMapping(value = { "/portalApi/role/addRoleFunction" })
429 public ModelAndView addRoleRoRoleFunction(HttpServletRequest request, HttpServletResponse response)
431 return getRoleController().addRoleFunction(request, response);
434 @PostMapping(value = { "/portalApi/role/removeChildRole" })
435 public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
436 return getRoleController().removeChildRole(request, response);
439 @PostMapping(value = { "/portalApi/role/addChildRole" })
440 public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
441 return getRoleController().addChildRole(request, response);
444 @GetMapping(value = { "/portalApi/get_role/{appId}/{roleId}" })
445 public void getRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
446 @PathVariable("roleId") Long roleId) throws Exception {
448 EPUser user = EPUserUtils.getUserSession(request);
449 ObjectMapper mapper = new ObjectMapper();
450 EPApp requestedApp = appService.getApp(appId);
451 if (isAuthorizedUser(user, requestedApp)) {
452 fieldsValidation(requestedApp);
453 if (requestedApp.getCentralAuth()) {
454 CentralV2Role answer = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
455 logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + roleId);
456 Map<String, Object> model = new HashMap<>();
457 model.put("availableRoleFunctions", mapper
458 .writeValueAsString(externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey())));
459 model.put("availableRoles",
460 mapper.writeValueAsString(getAvailableChildRoles(requestedApp.getUebKey(), roleId)));
461 model.put("role", mapper.writeValueAsString(answer));
462 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
463 JSONObject j = new JSONObject(msg);
464 response.getWriter().write(j.toString());
466 throw new NonCentralizedAppException(requestedApp.getName());
468 logger.info(EELFLoggerDelegate.auditLogger,
469 "RoleManageController.getRoleFunctionList, Unauthorized user");
470 SendErrorForUnauthorizedUser(response, user);
472 } catch (Exception e) {
473 logger.error(EELFLoggerDelegate.errorLogger, "getRole failed", e);
478 @GetMapping(value = { "/portalApi/get_role_functions/{appId}" })
479 public void getRoleFunctionList(HttpServletRequest request, HttpServletResponse response,
480 @PathVariable("appId") Long appId) throws Exception {
482 EPUser user = EPUserUtils.getUserSession(request);
483 EPApp requestedApp = appService.getApp(appId);
484 if (isAuthorizedUser(user, requestedApp)) {
485 fieldsValidation(requestedApp);
486 if (requestedApp.getCentralAuth()) {
487 List<CentralV2RoleFunction> answer = null;
488 Map<String, Object> model = new HashMap<>();
489 ObjectMapper mapper = new ObjectMapper();
490 answer = externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey());
491 model.put("availableRoleFunctions", answer);
492 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
493 JSONObject j = new JSONObject(msg);
494 response.getWriter().write(j.toString());
496 throw new NonCentralizedAppException(requestedApp.getName());
498 logger.info(EELFLoggerDelegate.auditLogger,
499 "RoleManageController.getRoleFunctionList, Unauthorized user");
500 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
501 response.getWriter().write("Unauthorized User");
503 } catch (Exception e) {
504 logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunctionList failed", e);
509 @PostMapping(value = { "/portalApi/role_function_list/saveRoleFunction/{appId}" })
510 public PortalRestResponse<String> saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @Valid @RequestBody CentralV2RoleFunction roleFunc,
511 @PathVariable("appId") Long appId) throws Exception {
512 if (roleFunc!=null) {
513 Validator validator = VALIDATOR_FACTORY.getValidator();
514 Set<ConstraintViolation<CentralV2RoleFunction>> constraintViolations = validator.validate(roleFunc);
516 if(!constraintViolations.isEmpty()){
517 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed");
518 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR");
522 EPUser user = EPUserUtils.getUserSession(request);
523 boolean saveOrUpdateResponse = false;
525 EPApp requestedApp = appService.getApp(appId);
526 if (isAuthorizedUser(user, requestedApp)) {
527 fieldsValidation(requestedApp);
528 if (requestedApp.getCentralAuth() && roleFunc!=null) {
529 String code = roleFunc.getType() + PIPE + roleFunc.getCode() + PIPE + roleFunc.getAction();
530 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
531 requestedApp.getUebKey());
532 if (domainRoleFunction != null
533 && (domainRoleFunction.getType() == null || domainRoleFunction.getAction() == null)) {
534 addIfTypeActionDoesNotExits(domainRoleFunction);
536 boolean isSave = true;
537 if (domainRoleFunction != null && domainRoleFunction.getCode().equals(roleFunc.getCode())
538 && domainRoleFunction.getType().equals(roleFunc.getType())
539 && domainRoleFunction.getAction().equals(roleFunc.getAction())) {
540 domainRoleFunction.setName(roleFunc.getName());
541 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(domainRoleFunction,
545 roleFunc.setAppId(requestedApp.getId());
546 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(roleFunc,
549 if (saveOrUpdateResponse) {
550 EPUser requestedUser = externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
551 EPApp app = externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
552 String activityCode = (isSave) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION
553 : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION;
554 logExterlaAuthRoleFunctionActivity(code, requestedUser, app, activityCode);
557 throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
559 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRoleFunction, Unauthorized user");
560 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
561 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
563 } catch (Exception e) {
564 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed", e);
565 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure");
567 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Saved Successfully!", "Success");
570 private void logExterlaAuthRoleFunctionActivity(String code, EPUser requestedUser, EPApp app, String activityCode) {
571 logger.info(EELFLoggerDelegate.applicationLogger, "saveRoleFunction: succeeded for app {}, function {}",
573 AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
574 auditLog.setComments(EcompPortalUtils.truncateString(
575 "saveRoleFunction role for app:" + app.getId() + " and function:'" + code + "'",
576 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
577 auditService.logActivity(auditLog, null);
578 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
579 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
580 EcompPortalUtils.calculateDateTimeDifferenceForLog(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
581 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
582 logger.info(EELFLoggerDelegate.auditLogger,
583 EPLogUtil.formatAuditLogMessage("RoleManageController.saveRoleFunction", activityCode,
584 String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(), code));
585 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
586 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
587 MDC.remove(SystemProperties.MDC_TIMER);
590 private void addIfTypeActionDoesNotExits(CentralV2RoleFunction domainRoleFunction) {
591 if (domainRoleFunction.getCode().contains(PIPE)) {
592 String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(domainRoleFunction.getCode());
593 String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(domainRoleFunction.getCode());
594 String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(domainRoleFunction.getCode());
595 domainRoleFunction.setType(newfunctionTypeFormat);
596 domainRoleFunction.setAction(newfunctionActionFormat);
597 domainRoleFunction.setCode(newfunctionCodeFormat);
599 String type = externalAccessRolesService.getFunctionCodeType(domainRoleFunction.getCode());
600 String action = externalAccessRolesService.getFunctionCodeAction(domainRoleFunction.getCode());
601 domainRoleFunction.setType(type);
602 domainRoleFunction.setAction(action);
606 @PostMapping(value = { "/portalApi/role_function_list/removeRoleFunction/{appId}" })
607 public PortalRestResponse<String> removeRoleFunction(HttpServletRequest request, HttpServletResponse response,
608 @RequestBody String roleFunc, @PathVariable("appId") Long appId) throws Exception {
609 EPUser user = EPUserUtils.getUserSession(request);
611 if (roleFunc!=null) {
612 SecureString secureString = new SecureString(roleFunc);
614 Validator validator = VALIDATOR_FACTORY.getValidator();
615 Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
617 if(!constraintViolations.isEmpty()){
618 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed");
619 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR");
624 EPApp requestedApp = appService.getApp(appId);
625 if (isAuthorizedUser(user, requestedApp)) {
626 fieldsValidation(requestedApp);
627 if (requestedApp.getCentralAuth()) {
628 ObjectMapper mapper = new ObjectMapper();
629 String data = roleFunc;
630 boolean getDelFuncResponse = false;
631 CentralV2RoleFunction availableRoleFunction = mapper.readValue(data, CentralV2RoleFunction.class);
632 String code = availableRoleFunction.getType() + PIPE + availableRoleFunction.getCode() + PIPE
633 + availableRoleFunction.getAction();
634 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
635 requestedApp.getUebKey());
636 getDelFuncResponse = externalAccessRolesService
637 .deleteCentralRoleFunction(domainRoleFunction.getCode(), requestedApp);
638 if (getDelFuncResponse) {
639 logger.info(EELFLoggerDelegate.applicationLogger,
640 "deleteRoleFunction: succeeded for app {}, role {}", requestedApp.getId(),
641 domainRoleFunction.getCode());
642 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION;
643 AuditLog auditLog = getAuditInfo(user, activityCode);
644 auditLog.setComments(
645 EcompPortalUtils.truncateString(
646 "Deleted function for app:" + requestedApp.getId() + " and function code:'"
647 + domainRoleFunction.getCode() + "'",
648 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
649 auditService.logActivity(auditLog, null);
650 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
651 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
652 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
653 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
654 EcompPortalUtils.calculateDateTimeDifferenceForLog(
655 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
656 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
657 logger.info(EELFLoggerDelegate.auditLogger,
658 EPLogUtil.formatAuditLogMessage("RoleManageController.removeRoleFunction",
659 EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION,
660 String.valueOf(user.getId()), user.getOrgUserId(),
661 domainRoleFunction.getCode()));
662 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
663 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
664 MDC.remove(SystemProperties.MDC_TIMER);
665 logger.info(EELFLoggerDelegate.auditLogger,
666 "Remove role function " + domainRoleFunction.getName());
669 throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
671 logger.info(EELFLoggerDelegate.auditLogger,
672 "RoleManageController.removeRoleFunction, Unauthorized user");
673 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
674 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
676 } catch (Exception e) {
677 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed", e);
678 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure");
680 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Deleted Successfully!", "Success");
683 @GetMapping(value = { "/portalApi/centralizedApps" })
684 public List<CentralizedApp> getCentralizedAppRoles(HttpServletRequest request, HttpServletResponse response, String userId) {
686 SecureString secureString = new SecureString(userId);
688 Validator validator = VALIDATOR_FACTORY.getValidator();
689 Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
691 if(!constraintViolations.isEmpty()){
692 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed");
697 EPUser user = EPUserUtils.getUserSession(request);
698 List<CentralizedApp> applicationsList = null;
699 if (adminRolesService.isAccountAdmin(user) || adminRolesService.isSuperAdmin(user)
700 || adminRolesService.isRoleAdmin(user)) {
701 applicationsList = externalAccessRolesService.getCentralizedAppsOfUser(userId);
703 logger.info(EELFLoggerDelegate.auditLogger,
704 "RoleManageController.getCentralizedAppRoles, Unauthorized user");
705 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
707 return applicationsList;
710 public RoleListController getRoleListController() {
711 return roleListController;
714 public void setRoleListController(RoleListController roleListController) {
715 this.roleListController = roleListController;
718 public RoleController getRoleController() {
719 return roleController;
722 public void setRoleController(RoleController roleController) {
723 this.roleController = roleController;
726 @PostMapping(value = { "/portalApi/syncRoles" }, produces = "application/json")
727 public PortalRestResponse<String> syncRoles(HttpServletRequest request, HttpServletResponse response,
728 @RequestBody Long appId) {
729 EPUser user = EPUserUtils.getUserSession(request);
731 EPApp app = appService.getApp(appId);
732 if (isAuthorizedUser(user, app)) {
733 fieldsValidation(app);
734 externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
736 logger.info(EELFLoggerDelegate.auditLogger,
737 "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
738 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
739 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
741 } catch (Exception e) {
742 logger.error(EELFLoggerDelegate.errorLogger, "failed syncRoles", e);
743 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
745 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync roles completed successfully!", "Success");
748 @PostMapping(value = { "/portalApi/syncFunctions" }, produces = "application/json")
749 public PortalRestResponse<String> syncFunctions(HttpServletRequest request, HttpServletResponse response,
750 @RequestBody Long appId) {
751 EPUser user = EPUserUtils.getUserSession(request);
753 EPApp app = appService.getApp(appId);
754 if (isAuthorizedUser(user, app)) {
755 fieldsValidation(app);
756 externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);
758 logger.info(EELFLoggerDelegate.auditLogger,
759 "RoleManageController.syncFunctions, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
760 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
761 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
763 } catch (Exception e) {
764 logger.error(EELFLoggerDelegate.errorLogger, "failed syncFunctions", e);
765 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
767 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync Functions completed successfully!", "Success");
770 public List<CentralV2Role> getAvailableChildRoles(String uebKey, Long roleId) throws Exception {
771 List<CentralV2Role> availableChildRoles = externalAccessRolesService.getRolesForApp(uebKey);
772 if (roleId == null || roleId == 0) {
773 return availableChildRoles;
775 CentralV2Role currentRole = externalAccessRolesService.getRoleInfo(roleId, uebKey);
776 Set<CentralV2Role> allParentRoles = new TreeSet<>();
777 allParentRoles = getAllParentRolesAsList(currentRole, allParentRoles);
778 Iterator<CentralV2Role> availableChildRolesIterator = availableChildRoles.iterator();
779 while (availableChildRolesIterator.hasNext()) {
780 CentralV2Role role = availableChildRolesIterator.next();
781 if (!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) {
782 availableChildRolesIterator.remove();
785 return availableChildRoles;
788 private Set<CentralV2Role> getAllParentRolesAsList(CentralV2Role role, Set<CentralV2Role> allParentRoles) {
789 Set<CentralV2Role> parentRoles = role.getParentRoles();
790 allParentRoles.addAll(parentRoles);
791 Iterator<CentralV2Role> parentRolesIterator = parentRoles.iterator();
792 while (parentRolesIterator.hasNext()) {
793 getAllParentRolesAsList(parentRolesIterator.next(), allParentRoles);
795 return allParentRoles;
798 public AuditLog getAuditInfo(EPUser user, String activityCode) {
799 AuditLog auditLog = new AuditLog();
800 auditLog.setUserId(user.getId());
801 auditLog.setActivityCode(activityCode);
802 auditLog.setAffectedRecordId(user.getOrgUserId());
807 private void fieldsValidation(EPApp app) throws Exception {
809 List<EPApp> appInfo = externalAccessRolesService.getApp(app.getUebKey());
810 if (appInfo.isEmpty()) {
811 throw new InvalidApplicationException("Invalid credentials");
813 if (!appInfo.isEmpty() && EcompPortalUtils.checkIfRemoteCentralAccessAllowed()
814 && appInfo.get(0).getCentralAuth()) {
815 ResponseEntity<String> response = externalAccessRolesService.getNameSpaceIfExists(appInfo.get(0));
816 if (response.getStatusCode().value() == HttpServletResponse.SC_NOT_FOUND)
817 throw new InvalidApplicationException("Invalid NameSpace");
821 private boolean isAuthorizedUser(EPUser user, EPApp requestedApp) {
822 if (user != null && (adminRolesService.isAccountAdminOfApplication(user, requestedApp)
823 || (adminRolesService.isSuperAdmin(user) && requestedApp.getId().equals(PortalConstants.PORTAL_APP_ID))))
828 private void SendErrorForUnauthorizedUser(HttpServletResponse response, EPUser user) throws IOException {
829 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
830 response.getWriter().write("Unauthorized User");
833 @PostMapping(value = {
834 "/portalApi/uploadRoleFunction/{appId}" }, produces = "application/json")
835 public PortalRestResponse<String> bulkUploadRoleFunc(HttpServletRequest request, HttpServletResponse response,
836 @RequestBody UploadRoleFunctionExtSystem data, @PathVariable("appId") Long appId) {
837 EPUser user = EPUserUtils.getUserSession(request);
839 EPApp app = appService.getApp(appId);
840 if (isAuthorizedUser(user, app)) {
841 fieldsValidation(app);
842 externalAccessRolesService.bulkUploadRoleFunc(data, app);
843 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
844 String code = data.getName() + "," + data.getType() + PIPE + data.getInstance() + PIPE
846 logExterlaAuthRoleFunctionActivity(code, user, app, activityCode);
848 logger.info(EELFLoggerDelegate.auditLogger,
849 "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
850 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
851 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
853 } catch (Exception e) {
854 logger.error(EELFLoggerDelegate.errorLogger, "Failed bulkUploadRoleFunc!", e);
855 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
857 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Uploaded Role Function successfully!", "Success");