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.PostMapping;
101 import org.springframework.web.bind.annotation.GetMapping;
102 import org.springframework.web.bind.annotation.RestController;
103 import org.springframework.web.servlet.ModelAndView;
104 import com.fasterxml.jackson.databind.DeserializationFeature;
105 import com.fasterxml.jackson.databind.JsonNode;
106 import com.fasterxml.jackson.databind.ObjectMapper;
107 import com.fasterxml.jackson.databind.type.TypeFactory;
110 * Proxies REST calls to role-management functions that arrive on paths
111 * /portalApi/* over to controller methods provided by the SDK-Core library.
112 * Those controller methods are mounted on paths not exposed by the Portal FE.
115 @org.springframework.context.annotation.Configuration
116 @EnableAspectJAutoProxy
118 public class RoleManageController extends EPRestrictedBaseController {
119 private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();
121 private static final String PIPE = "|";
123 private static final String ROLE_INVALID_CHARS = "%=():,\"\"";
125 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleManageController.class);
128 private RoleController roleController;
131 private RoleListController roleListController;
134 private EPAppService appService;
137 private AuditService auditService;
140 private ExternalAccessRolesService externalAccessRolesService;
143 private AdminRolesService adminRolesService;
146 * Calls an SDK-Core library method that gets the available roles and writes
147 * them to the request object. Portal specifies a Hibernate mappings from the
148 * Role class to the fn_role_v view, which ensures that only Portal (app_id is
149 * null) roles are fetched.
151 * Any method declared void (no return value) or returning null causes the audit
152 * log aspect method to declare failure. TODO: should return a JSON string.
159 @GetMapping(value = { "/portalApi/get_roles/{appId}" })
160 public void getRoles(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId)
163 EPUser user = EPUserUtils.getUserSession(request);
164 EPApp requestedApp = appService.getApp(appId);
165 if (isAuthorizedUser(user, requestedApp)) {
166 fieldsValidation(requestedApp);
167 if (requestedApp.getRolesInAAF()) {
168 List<CentralV2Role> answer = null;
169 Map<String, Object> model = new HashMap<>();
170 ObjectMapper mapper = new ObjectMapper();
171 answer = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey());
172 model.put("availableRoles", answer);
173 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
174 JSONObject j = new JSONObject(msg);
175 response.getWriter().write(j.toString());
177 throw new NonCentralizedAppException(requestedApp.getName());
179 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.getRoles, Unauthorized user");
180 SendErrorForUnauthorizedUser(response, user);
183 } catch (Exception e) {
184 logger.error(EELFLoggerDelegate.errorLogger, "getRoles failed", e);
188 @PostMapping(value = { "/portalApi/role_list/toggleRole/{appId}/{roleId}" })
189 public Map<String, Object> toggleRole(HttpServletRequest request, HttpServletResponse response,
190 @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception {
191 EPApp requestedApp = null;
192 String restcallStatus = null;
193 HashMap<String, Object> responseMap = new HashMap<>();
194 EPUser user = EPUserUtils.getUserSession(request);
196 requestedApp = appService.getApp(appId);
197 if (isAuthorizedUser(user, requestedApp)) {
198 fieldsValidation(requestedApp);
199 ObjectMapper mapper = new ObjectMapper();
200 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
201 CentralV2Role domainRole = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
202 // role. toggle active ind
203 boolean active = domainRole.getActive();
204 domainRole.setActive(!active);
206 String result = mapper.writeValueAsString(domainRole);
207 Role newRole = externalAccessRolesService.ConvertCentralRoleToRole(result);
208 ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService
209 .saveRoleForApplication(newRole, requestedApp.getUebKey());
210 boolean getAddResponse = externalRequestFieldsValidator.isResult();
211 if (getAddResponse) {
212 restcallStatus = "Success";
213 logger.info(EELFLoggerDelegate.auditLogger, "Toggle active status for role " + domainRole.getId());
215 restcallStatus = "Toggle Role Failed";
216 logger.info(EELFLoggerDelegate.auditLogger, "Toggle Role Failed " + domainRole.getId());
218 responseMap.put("restcallStatus", restcallStatus);
219 responseMap.put("availableRoles", externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()));
221 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.toggleRole, Unauthorized user");
222 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
223 responseMap.put("restcallStatus", " Unauthorized user");
225 } catch (Exception e) {
226 logger.error(EELFLoggerDelegate.errorLogger, "toggleRole failed", e);
232 @PostMapping(value = { "/portalApi/role_list/removeRole/{appId}/{roleId}" })
233 public Map<String, Object> removeRole(HttpServletRequest request, HttpServletResponse response,
234 @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception {
236 EPUser user = EPUserUtils.getUserSession(request);
237 EPApp requestedApp = null;
238 String restCallStatus = null;
239 HashMap<String, Object> responseMap = new HashMap<>();
240 ExternalRequestFieldsValidator externalRequestFieldsValidator = null;
242 requestedApp = appService.getApp(appId);
243 if (isAuthorizedUser(user, requestedApp)) {
244 fieldsValidation(requestedApp);
245 if (requestedApp.getRolesInAAF()) {
246 externalRequestFieldsValidator = externalAccessRolesService.deleteDependencyRoleRecord(roleId,
247 requestedApp.getUebKey(), user.getOrgUserId());
248 boolean deleteResponse = externalRequestFieldsValidator.isResult();
249 if (deleteResponse) {
250 restCallStatus = "Success";
251 EPUser requestedUser = (EPUser) externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
252 EPApp app = (EPApp) externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
253 logger.info(EELFLoggerDelegate.applicationLogger, "deleteRole: succeeded for app {}, role {}",
254 app.getId(), roleId);
255 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE;
256 AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
257 auditLog.setComments(EcompPortalUtils.truncateString(
258 "Deleted role for app:" + app.getId() + " and role:'" + roleId + "'",
259 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
260 auditService.logActivity(auditLog, null);
261 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
262 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
263 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
264 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
265 EcompPortalUtils.calculateDateTimeDifferenceForLog(
266 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
267 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
268 logger.info(EELFLoggerDelegate.auditLogger,
269 EPLogUtil.formatAuditLogMessage("RoleManageController.removeRole",
270 EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE,
271 String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(),
273 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
274 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
275 MDC.remove(SystemProperties.MDC_TIMER);
277 restCallStatus = "Remove Role failed";
278 responseMap.put("error", externalRequestFieldsValidator.getDetailMessage());
279 logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed");
281 responseMap.put("restCallStatus", restCallStatus);
282 responseMap.put("availableRoles",
283 externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()));
285 throw new NonCentralizedAppException(requestedApp.getName());
287 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.removeRole, Unauthorized user");
288 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
289 responseMap.put("restCallStatus", " Unauthorized user");
291 } catch (Exception e) {
292 logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed", e);
298 @PostMapping(value = { "/portalApi/role/saveRole/{appId}" })
299 public Map<String, Object> saveRole(HttpServletRequest request, HttpServletResponse response,
300 @PathVariable("appId") Long appId) throws Exception {
301 EPUser user = EPUserUtils.getUserSession(request);
302 String responseString = null;
303 HashMap<String, Object> responseMap = new HashMap<>();
305 EPApp requestedApp = appService.getApp(appId);
306 if (isAuthorizedUser(user, requestedApp)) {
307 fieldsValidation(requestedApp);
308 if (requestedApp != null && requestedApp.getRolesInAAF().equals(true)) {
309 ObjectMapper mapper = new ObjectMapper();
310 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
311 JsonNode root = mapper.readTree(request.getReader());
312 CentralV2Role role = mapper.readValue(root.get("role").toString(), CentralV2Role.class);
314 List<CentralV2Role> childRoles = mapper.readValue(root.get("childRoles").toString(),
315 TypeFactory.defaultInstance().constructCollectionType(List.class, CentralV2Role.class));
316 List<CentralV2RoleFunction> roleFunctions = mapper.readValue(root.get("roleFunctions").toString(),
317 TypeFactory.defaultInstance().constructCollectionType(List.class,
318 CentralV2RoleFunction.class));
319 if (role.getId() != null && StringUtils.containsAny(role.getName(), ROLE_INVALID_CHARS)) {
320 throw new InvalidRoleException("Invalid role name found for '" + role.getName()
321 + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
323 CentralV2Role domainRole;
324 if (role.getId() != null) {
325 domainRole = externalAccessRolesService.getRoleInfo(role.getId(), requestedApp.getUebKey());
326 domainRole.setName(role.getName());
327 domainRole.setPriority(role.getPriority());
329 // check for existing role of same name
330 List<CentralV2Role> roles = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey());
331 for (CentralV2Role existRole : roles)
332 if (existRole.getName().equalsIgnoreCase(role.getName()))
333 throw new DuplicateRecordException("Role already exists: " + existRole.getName());
335 domainRole = new CentralV2Role.CentralV2RoleBuilder().createCentralV2Role();
336 domainRole.setName(role.getName());
337 domainRole.setPriority(role.getPriority());
338 domainRole.setActive(role.getActive());
339 if (role.getChildRoles() != null && role.getChildRoles().size() > 0) {
340 for (Object childRole : childRoles) {
341 domainRole.addChildRole((CentralV2Role) childRole);
345 if (role.getRoleFunctions() != null && role.getRoleFunctions().size() > 0) {
346 domainRole.setRoleFunctions(new TreeSet<CentralV2RoleFunction>());
347 for (CentralV2RoleFunction roleFunction : roleFunctions) {
348 if (roleFunction.getType() == null && roleFunction.getAction() == null) {
349 throw new InvalidRoleException("Invalid role function type:" + roleFunction.getType()
350 + " and action: " + roleFunction.getAction() + " found while saving!");
352 if (EcompPortalUtils.checkFunctionCodeHasEncodePattern(roleFunction.getCode()))
353 roleFunction.setCode(roleFunction.getType() + PIPE
354 + EcompPortalUtils.encodeFunctionCode(roleFunction.getCode()) + PIPE
355 + roleFunction.getAction());
357 roleFunction.setCode(roleFunction.getType() + PIPE + roleFunction.getCode() + PIPE
358 + roleFunction.getAction());
359 domainRole.addRoleFunction((CentralV2RoleFunction) roleFunction);
362 domainRole.setRoleFunctions(new TreeSet<>());
364 String result = mapper.writeValueAsString(domainRole);
365 Role newRole = externalAccessRolesService.ConvertCentralRoleToRole(result);
366 ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService
367 .saveRoleForApplication(newRole, requestedApp.getUebKey());
368 boolean getAddResponse = externalRequestFieldsValidator.isResult();
369 if (getAddResponse) {
370 String activityCode = (role.getId() == null) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_ROLE
371 : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
372 logger.info(EELFLoggerDelegate.applicationLogger, "saveRole: succeeded for app {}, role {}",
373 requestedApp.getId(), role.getName());
374 AuditLog auditLog = new AuditLog();
375 auditLog.setUserId(user.getId());
376 auditLog.setActivityCode(activityCode);
377 auditLog.setComments(EcompPortalUtils.truncateString(
378 "saveRole role for app:" + requestedApp.getId() + " and role:'" + role.getName() + "'",
379 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
380 auditLog.setAffectedRecordId(user.getOrgUserId());
381 auditService.logActivity(auditLog, null);
382 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
383 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
384 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
385 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
386 EcompPortalUtils.calculateDateTimeDifferenceForLog(
387 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
388 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
389 logger.info(EELFLoggerDelegate.auditLogger,
390 EPLogUtil.formatAuditLogMessage("RoleManageController.saveRole", activityCode,
391 String.valueOf(user.getId()), user.getOrgUserId(), role.getName()));
392 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
393 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
394 MDC.remove(SystemProperties.MDC_TIMER);
395 responseMap.put("status", "Success");
396 responseMap.put("role", domainRole);
398 if (externalRequestFieldsValidator.getDetailMessage().contains("406")) {
399 externalRequestFieldsValidator.setDetailMessage("Failed to save role for '" + role.getName()
400 + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
402 responseMap.put("status", "SaveRole Failed");
403 responseMap.put("role", responseString);
404 responseMap.put("error", externalRequestFieldsValidator.getDetailMessage());
405 logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed");
409 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRole, Unauthorized user");
410 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
411 responseMap.put("error", " Unauthorized user");
413 } catch (Exception e) {
414 logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e);
415 responseMap.put("error", e.getMessage());
420 @PostMapping(value = { "/portalApi/role/removeRoleFunction" })
421 public ModelAndView removeRoleRoleFunction(HttpServletRequest request, HttpServletResponse response)
423 return getRoleController().removeRoleFunction(request, response);
426 @PostMapping(value = { "/portalApi/role/addRoleFunction" })
427 public ModelAndView addRoleRoRoleFunction(HttpServletRequest request, HttpServletResponse response)
429 return getRoleController().addRoleFunction(request, response);
432 @PostMapping(value = { "/portalApi/role/removeChildRole" })
433 public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
434 return getRoleController().removeChildRole(request, response);
437 @PostMapping(value = { "/portalApi/role/addChildRole" })
438 public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
439 return getRoleController().addChildRole(request, response);
442 @GetMapping(value = { "/portalApi/get_role/{appId}/{roleId}" })
443 public void getRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
444 @PathVariable("roleId") Long roleId) throws Exception {
446 EPUser user = EPUserUtils.getUserSession(request);
447 ObjectMapper mapper = new ObjectMapper();
448 EPApp requestedApp = appService.getApp(appId);
449 if (isAuthorizedUser(user, requestedApp)) {
450 fieldsValidation(requestedApp);
451 if (requestedApp.getRolesInAAF()) {
452 CentralV2Role answer = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
453 logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + roleId);
454 Map<String, Object> model = new HashMap<>();
455 model.put("availableRoleFunctions", mapper
456 .writeValueAsString(externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey())));
457 model.put("availableRoles",
458 mapper.writeValueAsString(getAvailableChildRoles(requestedApp.getUebKey(), roleId)));
459 model.put("role", mapper.writeValueAsString(answer));
460 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
461 JSONObject j = new JSONObject(msg);
462 response.getWriter().write(j.toString());
464 throw new NonCentralizedAppException(requestedApp.getName());
466 logger.info(EELFLoggerDelegate.auditLogger,
467 "RoleManageController.getRoleFunctionList, Unauthorized user");
468 SendErrorForUnauthorizedUser(response, user);
470 } catch (Exception e) {
471 logger.error(EELFLoggerDelegate.errorLogger, "getRole failed", e);
476 @GetMapping(value = { "/portalApi/get_role_functions/{appId}" })
477 public void getRoleFunctionList(HttpServletRequest request, HttpServletResponse response,
478 @PathVariable("appId") Long appId) throws Exception {
480 EPUser user = EPUserUtils.getUserSession(request);
481 EPApp requestedApp = appService.getApp(appId);
482 if (isAuthorizedUser(user, requestedApp)) {
483 fieldsValidation(requestedApp);
484 if (requestedApp.getRolesInAAF()) {
485 List<CentralV2RoleFunction> answer = null;
486 Map<String, Object> model = new HashMap<>();
487 ObjectMapper mapper = new ObjectMapper();
488 answer = externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey());
489 model.put("availableRoleFunctions", answer);
490 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
491 JSONObject j = new JSONObject(msg);
492 response.getWriter().write(j.toString());
494 throw new NonCentralizedAppException(requestedApp.getName());
496 logger.info(EELFLoggerDelegate.auditLogger,
497 "RoleManageController.getRoleFunctionList, Unauthorized user");
498 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
499 response.getWriter().write("Unauthorized User");
501 } catch (Exception e) {
502 logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunctionList failed", e);
507 @PostMapping(value = { "/portalApi/role_function_list/saveRoleFunction/{appId}" })
508 public PortalRestResponse<String> saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @Valid @RequestBody CentralV2RoleFunction roleFunc,
509 @PathVariable("appId") Long appId) throws Exception {
510 if (roleFunc!=null) {
511 Validator validator = VALIDATOR_FACTORY.getValidator();
512 Set<ConstraintViolation<CentralV2RoleFunction>> constraintViolations = validator.validate(roleFunc);
514 if(!constraintViolations.isEmpty()){
515 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed");
516 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR");
520 EPUser user = EPUserUtils.getUserSession(request);
521 boolean saveOrUpdateResponse = false;
523 EPApp requestedApp = appService.getApp(appId);
524 if (isAuthorizedUser(user, requestedApp)) {
525 fieldsValidation(requestedApp);
526 if (requestedApp.getRolesInAAF() && roleFunc!=null) {
527 String code = roleFunc.getType() + PIPE + roleFunc.getCode() + PIPE + roleFunc.getAction();
528 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
529 requestedApp.getUebKey());
530 if (domainRoleFunction != null
531 && (domainRoleFunction.getType() == null || domainRoleFunction.getAction() == null)) {
532 addIfTypeActionDoesNotExits(domainRoleFunction);
534 boolean isSave = true;
535 if (domainRoleFunction != null && domainRoleFunction.getCode().equals(roleFunc.getCode())
536 && domainRoleFunction.getType().equals(roleFunc.getType())
537 && domainRoleFunction.getAction().equals(roleFunc.getAction())) {
538 domainRoleFunction.setName(roleFunc.getName());
539 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(domainRoleFunction,
543 roleFunc.setAppId(requestedApp.getId());
544 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(roleFunc,
547 if (saveOrUpdateResponse) {
548 EPUser requestedUser = externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
549 EPApp app = externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
550 String activityCode = (isSave) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION
551 : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION;
552 logExterlaAuthRoleFunctionActivity(code, requestedUser, app, activityCode);
555 throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
557 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRoleFunction, Unauthorized user");
558 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
559 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
561 } catch (Exception e) {
562 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed", e);
563 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure");
565 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Saved Successfully!", "Success");
568 private void logExterlaAuthRoleFunctionActivity(String code, EPUser requestedUser, EPApp app, String activityCode) {
569 logger.info(EELFLoggerDelegate.applicationLogger, "saveRoleFunction: succeeded for app {}, function {}",
571 AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
572 auditLog.setComments(EcompPortalUtils.truncateString(
573 "saveRoleFunction role for app:" + app.getId() + " and function:'" + code + "'",
574 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
575 auditService.logActivity(auditLog, null);
576 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
577 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
578 EcompPortalUtils.calculateDateTimeDifferenceForLog(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
579 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
580 logger.info(EELFLoggerDelegate.auditLogger,
581 EPLogUtil.formatAuditLogMessage("RoleManageController.saveRoleFunction", activityCode,
582 String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(), code));
583 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
584 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
585 MDC.remove(SystemProperties.MDC_TIMER);
588 private void addIfTypeActionDoesNotExits(CentralV2RoleFunction domainRoleFunction) {
589 if (domainRoleFunction.getCode().contains(PIPE)) {
590 String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(domainRoleFunction.getCode());
591 String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(domainRoleFunction.getCode());
592 String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(domainRoleFunction.getCode());
593 domainRoleFunction.setType(newfunctionTypeFormat);
594 domainRoleFunction.setAction(newfunctionActionFormat);
595 domainRoleFunction.setCode(newfunctionCodeFormat);
597 String type = externalAccessRolesService.getFunctionCodeType(domainRoleFunction.getCode());
598 String action = externalAccessRolesService.getFunctionCodeAction(domainRoleFunction.getCode());
599 domainRoleFunction.setType(type);
600 domainRoleFunction.setAction(action);
604 @PostMapping(value = { "/portalApi/role_function_list/removeRoleFunction/{appId}" })
605 public PortalRestResponse<String> removeRoleFunction(HttpServletRequest request, HttpServletResponse response,
606 @RequestBody String roleFunc, @PathVariable("appId") Long appId) throws Exception {
607 EPUser user = EPUserUtils.getUserSession(request);
609 if (roleFunc!=null) {
610 SecureString secureString = new SecureString(roleFunc);
612 Validator validator = VALIDATOR_FACTORY.getValidator();
613 Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
615 if(!constraintViolations.isEmpty()){
616 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed");
617 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR");
622 EPApp requestedApp = appService.getApp(appId);
623 if (isAuthorizedUser(user, requestedApp)) {
624 fieldsValidation(requestedApp);
625 if (requestedApp.getRolesInAAF()) {
626 ObjectMapper mapper = new ObjectMapper();
627 String data = roleFunc;
628 boolean getDelFuncResponse = false;
629 CentralV2RoleFunction availableRoleFunction = mapper.readValue(data, CentralV2RoleFunction.class);
630 String code = availableRoleFunction.getType() + PIPE + availableRoleFunction.getCode() + PIPE
631 + availableRoleFunction.getAction();
632 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
633 requestedApp.getUebKey());
634 getDelFuncResponse = externalAccessRolesService
635 .deleteCentralRoleFunction(domainRoleFunction.getCode(), requestedApp);
636 if (getDelFuncResponse) {
637 logger.info(EELFLoggerDelegate.applicationLogger,
638 "deleteRoleFunction: succeeded for app {}, role {}", requestedApp.getId(),
639 domainRoleFunction.getCode());
640 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION;
641 AuditLog auditLog = getAuditInfo(user, activityCode);
642 auditLog.setComments(
643 EcompPortalUtils.truncateString(
644 "Deleted function for app:" + requestedApp.getId() + " and function code:'"
645 + domainRoleFunction.getCode() + "'",
646 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
647 auditService.logActivity(auditLog, null);
648 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
649 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
650 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
651 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
652 EcompPortalUtils.calculateDateTimeDifferenceForLog(
653 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
654 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
655 logger.info(EELFLoggerDelegate.auditLogger,
656 EPLogUtil.formatAuditLogMessage("RoleManageController.removeRoleFunction",
657 EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION,
658 String.valueOf(user.getId()), user.getOrgUserId(),
659 domainRoleFunction.getCode()));
660 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
661 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
662 MDC.remove(SystemProperties.MDC_TIMER);
663 logger.info(EELFLoggerDelegate.auditLogger,
664 "Remove role function " + domainRoleFunction.getName());
667 throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
669 logger.info(EELFLoggerDelegate.auditLogger,
670 "RoleManageController.removeRoleFunction, Unauthorized user");
671 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
672 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
674 } catch (Exception e) {
675 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed", e);
676 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure");
678 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Deleted Successfully!", "Success");
681 @GetMapping(value = { "/portalApi/centralizedApps" })
682 public List<CentralizedApp> getCentralizedAppRoles(HttpServletRequest request, HttpServletResponse response, String userId) {
684 SecureString secureString = new SecureString(userId);
686 Validator validator = VALIDATOR_FACTORY.getValidator();
687 Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
689 if(!constraintViolations.isEmpty()){
690 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed");
695 EPUser user = EPUserUtils.getUserSession(request);
696 List<CentralizedApp> applicationsList = null;
697 if (adminRolesService.isAccountAdmin(user) || adminRolesService.isSuperAdmin(user)
698 || adminRolesService.isRoleAdmin(user)) {
699 applicationsList = externalAccessRolesService.getCentralizedAppsOfUser(userId);
701 logger.info(EELFLoggerDelegate.auditLogger,
702 "RoleManageController.getCentralizedAppRoles, Unauthorized user");
703 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
705 return applicationsList;
708 public RoleListController getRoleListController() {
709 return roleListController;
712 public void setRoleListController(RoleListController roleListController) {
713 this.roleListController = roleListController;
716 public RoleController getRoleController() {
717 return roleController;
720 public void setRoleController(RoleController roleController) {
721 this.roleController = roleController;
724 @PostMapping(value = { "/portalApi/syncRoles" }, produces = "application/json")
725 public PortalRestResponse<String> syncRoles(HttpServletRequest request, HttpServletResponse response,
726 @RequestBody Long appId) {
727 EPUser user = EPUserUtils.getUserSession(request);
729 EPApp app = appService.getApp(appId);
730 if (isAuthorizedUser(user, app)) {
731 fieldsValidation(app);
732 externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
734 logger.info(EELFLoggerDelegate.auditLogger,
735 "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
736 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
737 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
739 } catch (Exception e) {
740 logger.error(EELFLoggerDelegate.errorLogger, "failed syncRoles", e);
741 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
743 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync roles completed successfully!", "Success");
746 @PostMapping(value = { "/portalApi/syncFunctions" }, produces = "application/json")
747 public PortalRestResponse<String> syncFunctions(HttpServletRequest request, HttpServletResponse response,
748 @RequestBody Long appId) {
749 EPUser user = EPUserUtils.getUserSession(request);
751 EPApp app = appService.getApp(appId);
752 if (isAuthorizedUser(user, app)) {
753 fieldsValidation(app);
754 externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);
756 logger.info(EELFLoggerDelegate.auditLogger,
757 "RoleManageController.syncFunctions, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
758 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
759 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
761 } catch (Exception e) {
762 logger.error(EELFLoggerDelegate.errorLogger, "failed syncFunctions", e);
763 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
765 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync Functions completed successfully!", "Success");
768 public List<CentralV2Role> getAvailableChildRoles(String uebKey, Long roleId) throws Exception {
769 List<CentralV2Role> availableChildRoles = externalAccessRolesService.getRolesForApp(uebKey);
770 if (roleId == null || roleId == 0) {
771 return availableChildRoles;
773 CentralV2Role currentRole = externalAccessRolesService.getRoleInfo(roleId, uebKey);
774 Set<CentralV2Role> allParentRoles = new TreeSet<>();
775 allParentRoles = getAllParentRolesAsList(currentRole, allParentRoles);
776 Iterator<CentralV2Role> availableChildRolesIterator = availableChildRoles.iterator();
777 while (availableChildRolesIterator.hasNext()) {
778 CentralV2Role role = availableChildRolesIterator.next();
779 if (!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) {
780 availableChildRolesIterator.remove();
783 return availableChildRoles;
786 private Set<CentralV2Role> getAllParentRolesAsList(CentralV2Role role, Set<CentralV2Role> allParentRoles) {
787 Set<CentralV2Role> parentRoles = role.getParentRoles();
788 allParentRoles.addAll(parentRoles);
789 Iterator<CentralV2Role> parentRolesIterator = parentRoles.iterator();
790 while (parentRolesIterator.hasNext()) {
791 getAllParentRolesAsList(parentRolesIterator.next(), allParentRoles);
793 return allParentRoles;
796 public AuditLog getAuditInfo(EPUser user, String activityCode) {
797 AuditLog auditLog = new AuditLog();
798 auditLog.setUserId(user.getId());
799 auditLog.setActivityCode(activityCode);
800 auditLog.setAffectedRecordId(user.getOrgUserId());
805 private void fieldsValidation(EPApp app) throws Exception {
807 List<EPApp> appInfo = externalAccessRolesService.getApp(app.getUebKey());
808 if (appInfo.isEmpty()) {
809 throw new InvalidApplicationException("Invalid credentials");
811 if (!appInfo.isEmpty() && EcompPortalUtils.checkIfRemoteCentralAccessAllowed()
812 && appInfo.get(0).getRolesInAAF()) {
813 ResponseEntity<String> response = externalAccessRolesService.getNameSpaceIfExists(appInfo.get(0));
814 if (response.getStatusCode().value() == HttpServletResponse.SC_NOT_FOUND)
815 throw new InvalidApplicationException("Invalid NameSpace");
819 private boolean isAuthorizedUser(EPUser user, EPApp requestedApp) {
820 if (user != null && (adminRolesService.isAccountAdminOfApplication(user, requestedApp)
821 || (adminRolesService.isSuperAdmin(user) && requestedApp.getId().equals(PortalConstants.PORTAL_APP_ID))))
826 private void SendErrorForUnauthorizedUser(HttpServletResponse response, EPUser user) throws IOException {
827 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
828 response.getWriter().write("Unauthorized User");
831 @PostMapping(value = {
832 "/portalApi/uploadRoleFunction/{appId}" }, produces = "application/json")
833 public PortalRestResponse<String> bulkUploadRoleFunc(HttpServletRequest request, HttpServletResponse response,
834 @RequestBody UploadRoleFunctionExtSystem data, @PathVariable("appId") Long appId) {
835 EPUser user = EPUserUtils.getUserSession(request);
837 EPApp app = appService.getApp(appId);
838 if (isAuthorizedUser(user, app)) {
839 fieldsValidation(app);
840 externalAccessRolesService.bulkUploadRoleFunc(data, app);
841 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
842 String code = data.getName() + "," + data.getType() + PIPE + data.getInstance() + PIPE
844 logExterlaAuthRoleFunctionActivity(code, user, app, activityCode);
846 logger.info(EELFLoggerDelegate.auditLogger,
847 "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
848 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
849 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
851 } catch (Exception e) {
852 logger.error(EELFLoggerDelegate.errorLogger, "Failed bulkUploadRoleFunc!", e);
853 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
855 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Uploaded Role Function successfully!", "Success");