2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
7 * Modifications Copyright (c) 2019 Samsung
8 * ===================================================================
10 * Unless otherwise specified, all software contained herein is licensed
11 * under the Apache License, Version 2.0 (the "License");
12 * you may not use this software except in compliance with the License.
13 * You may obtain a copy of the License at
15 * http://www.apache.org/licenses/LICENSE-2.0
17 * Unless required by applicable law or agreed to in writing, software
18 * distributed under the License is distributed on an "AS IS" BASIS,
19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 * See the License for the specific language governing permissions and
21 * limitations under the License.
23 * Unless otherwise specified, all documentation contained herein is licensed
24 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25 * you may not use this documentation except in compliance with the License.
26 * You may obtain a copy of the License at
28 * https://creativecommons.org/licenses/by/4.0/
30 * Unless required by applicable law or agreed to in writing, documentation
31 * distributed under the License is distributed on an "AS IS" BASIS,
32 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33 * See the License for the specific language governing permissions and
34 * limitations under the License.
36 * ============LICENSE_END============================================
40 package org.onap.portalapp.portal.controller;
42 import java.io.IOException;
43 import java.util.HashMap;
44 import java.util.Iterator;
45 import java.util.List;
48 import java.util.TreeSet;
50 import javax.servlet.http.HttpServletRequest;
51 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.RequestMethod;
102 import org.springframework.web.bind.annotation.RestController;
103 import org.springframework.web.servlet.ModelAndView;
105 import com.fasterxml.jackson.databind.DeserializationFeature;
106 import com.fasterxml.jackson.databind.JsonNode;
107 import com.fasterxml.jackson.databind.ObjectMapper;
108 import com.fasterxml.jackson.databind.type.TypeFactory;
111 * Proxies REST calls to role-management functions that arrive on paths
112 * /portalApi/* over to controller methods provided by the SDK-Core library.
113 * Those controller methods are mounted on paths not exposed by the Portal FE.
116 @org.springframework.context.annotation.Configuration
117 @EnableAspectJAutoProxy
119 public class RoleManageController extends EPRestrictedBaseController {
120 private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();
122 private static final String PIPE = "|";
124 private static final String ROLE_INVALID_CHARS = "%=():,\"\"";
126 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleManageController.class);
129 private RoleController roleController;
132 private RoleListController roleListController;
135 private EPAppService appService;
138 private AuditService auditService;
141 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
150 * the Role class to the fn_role_v view, which ensures that only Portal
151 * (app_id is null) roles are fetched.
153 * Any method declared void (no return value) or returning null causes the
154 * audit log aspect method to declare failure. TODO: should return a JSON
162 @RequestMapping(value = { "/portalApi/get_roles/{appId}" }, method = RequestMethod.GET)
163 public void getRoles(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId) throws Exception {
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);
192 @RequestMapping(value = { "/portalApi/role_list/toggleRole/{appId}/{roleId}" }, method = RequestMethod.POST)
193 public Map<String, Object> toggleRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
194 @PathVariable("roleId") Long roleId) throws Exception {
195 EPApp requestedApp = null;
196 String restcallStatus = null;
197 HashMap<String, Object> responseMap = new HashMap<>();
198 EPUser user = EPUserUtils.getUserSession(request);
200 requestedApp = appService.getApp(appId);
201 if (isAuthorizedUser(user, requestedApp)) {
202 fieldsValidation(requestedApp);
203 ObjectMapper mapper = new ObjectMapper();
204 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
205 CentralV2Role domainRole = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
206 // role. toggle active ind
207 boolean active = domainRole.getActive();
208 domainRole.setActive(!active);
210 String result = mapper.writeValueAsString(domainRole);
211 Role newRole = externalAccessRolesService.ConvertCentralRoleToRole(result);
212 ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService
213 .saveRoleForApplication(newRole, requestedApp.getUebKey());
214 boolean getAddResponse = externalRequestFieldsValidator.isResult();
215 if (getAddResponse) {
216 restcallStatus = "Success";
217 logger.info(EELFLoggerDelegate.auditLogger, "Toggle active status for role " + domainRole.getId());
219 restcallStatus = "Toggle Role Failed";
220 logger.info(EELFLoggerDelegate.auditLogger, "Toggle Role Failed " + domainRole.getId());
222 responseMap.put("restcallStatus", restcallStatus);
223 responseMap.put("availableRoles", externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()));
225 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.toggleRole, Unauthorized user");
226 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
227 responseMap.put("restcallStatus", " Unauthorized user");
229 } catch (Exception e) {
230 logger.error(EELFLoggerDelegate.errorLogger, "toggleRole failed", e);
236 @RequestMapping(value = { "/portalApi/role_list/removeRole/{appId}/{roleId}" }, method = RequestMethod.POST)
237 public Map<String, Object> removeRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
238 @PathVariable("roleId") Long roleId) throws Exception {
240 EPUser user = EPUserUtils.getUserSession(request);
241 EPApp requestedApp = null;
242 String restCallStatus = null;
243 HashMap<String, Object> responseMap = new HashMap<>();
244 ExternalRequestFieldsValidator externalRequestFieldsValidator = null;
246 requestedApp = appService.getApp(appId);
247 if (isAuthorizedUser(user, requestedApp)) {
248 fieldsValidation(requestedApp);
249 if (requestedApp.getCentralAuth()) {
250 externalRequestFieldsValidator = externalAccessRolesService.deleteDependencyRoleRecord(roleId,
251 requestedApp.getUebKey(), user.getOrgUserId());
252 boolean deleteResponse = externalRequestFieldsValidator.isResult();
253 if (deleteResponse) {
254 restCallStatus = "Success";
255 EPUser requestedUser = (EPUser) externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
256 EPApp app = (EPApp) externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
257 logger.info(EELFLoggerDelegate.applicationLogger, "deleteRole: succeeded for app {}, role {}",
258 app.getId(), roleId);
259 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE;
260 AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
261 auditLog.setComments(EcompPortalUtils.truncateString(
262 "Deleted role for app:" + app.getId() + " and role:'" + roleId + "'",
263 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
264 auditService.logActivity(auditLog, null);
265 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
266 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
267 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
268 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
269 EcompPortalUtils.calculateDateTimeDifferenceForLog(
270 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
271 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
272 logger.info(EELFLoggerDelegate.auditLogger,
273 EPLogUtil.formatAuditLogMessage("RoleManageController.removeRole",
274 EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE,
275 String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(),
277 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
278 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
279 MDC.remove(SystemProperties.MDC_TIMER);
281 restCallStatus = "Remove Role failed";
282 responseMap.put("error", externalRequestFieldsValidator.getDetailMessage());
283 logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed");
285 responseMap.put("restCallStatus", restCallStatus);
286 responseMap.put("availableRoles",
287 externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()));
289 throw new NonCentralizedAppException(requestedApp.getName());
291 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.removeRole, Unauthorized user");
292 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
293 responseMap.put("restCallStatus", " Unauthorized user");
295 } catch (Exception e) {
296 logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed", e);
302 @RequestMapping(value = { "/portalApi/role/saveRole/{appId}" }, method = RequestMethod.POST)
303 public Map<String, Object> saveRole(HttpServletRequest request, HttpServletResponse response,
304 @PathVariable("appId") Long appId) throws Exception {
305 EPUser user = EPUserUtils.getUserSession(request);
306 String responseString = null;
307 HashMap<String, Object> responseMap = new HashMap<>();
309 EPApp requestedApp = appService.getApp(appId);
310 if (isAuthorizedUser(user, requestedApp)) {
311 fieldsValidation(requestedApp);
312 if (requestedApp != null && requestedApp.getCentralAuth().equals(true)) {
313 ObjectMapper mapper = new ObjectMapper();
314 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
315 JsonNode root = mapper.readTree(request.getReader());
316 CentralV2Role role = mapper.readValue(root.get("role").toString(), CentralV2Role.class);
318 List<CentralV2Role> childRoles = mapper.readValue(root.get("childRoles").toString(),
319 TypeFactory.defaultInstance().constructCollectionType(List.class, CentralV2Role.class));
320 List<CentralV2RoleFunction> roleFunctions = mapper.readValue(root.get("roleFunctions").toString(),
321 TypeFactory.defaultInstance().constructCollectionType(List.class,
322 CentralV2RoleFunction.class));
323 if (role.getId() != null && StringUtils.containsAny(role.getName(), ROLE_INVALID_CHARS)) {
324 throw new InvalidRoleException("Invalid role name found for '" + role.getName()
325 + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
327 CentralV2Role domainRole;
328 if (role.getId() != null) {
329 domainRole = externalAccessRolesService.getRoleInfo(role.getId(), requestedApp.getUebKey());
330 domainRole.setName(role.getName());
331 domainRole.setPriority(role.getPriority());
333 // check for existing role of same name
334 List<CentralV2Role> roles = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey());
335 for (CentralV2Role existRole : roles)
336 if (existRole.getName().equalsIgnoreCase(role.getName()))
337 throw new DuplicateRecordException("Role already exists: " + existRole.getName());
339 domainRole = new CentralV2Role();
340 domainRole.setName(role.getName());
341 domainRole.setPriority(role.getPriority());
342 domainRole.setActive(role.getActive());
343 if (role.getChildRoles() != null && role.getChildRoles().size() > 0) {
344 for (Object childRole : childRoles) {
345 domainRole.addChildRole((CentralV2Role) childRole);
349 if (role.getRoleFunctions() != null && role.getRoleFunctions().size() > 0) {
350 domainRole.setRoleFunctions(new TreeSet<CentralV2RoleFunction>());
351 for (CentralV2RoleFunction roleFunction : roleFunctions) {
352 if (roleFunction.getType() == null && roleFunction.getAction() == null) {
353 throw new InvalidRoleException("Invalid role function type:" + roleFunction.getType()
354 + " and action: " + roleFunction.getAction() + " found while saving!");
356 roleFunction.setCode(externalAccessRolesService.encodeFunctionCode(roleFunction.getCode()));
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 @RequestMapping(value = { "/portalApi/role/removeRoleFunction" }, method = RequestMethod.POST)
421 public ModelAndView removeRoleRoleFunction(HttpServletRequest request, HttpServletResponse response)
423 return getRoleController().removeRoleFunction(request, response);
426 @RequestMapping(value = { "/portalApi/role/addRoleFunction" }, method = RequestMethod.POST)
427 public ModelAndView addRoleRoRoleFunction(HttpServletRequest request, HttpServletResponse response)
429 return getRoleController().addRoleFunction(request, response);
432 @RequestMapping(value = { "/portalApi/role/removeChildRole" }, method = RequestMethod.POST)
433 public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
434 return getRoleController().removeChildRole(request, response);
437 @RequestMapping(value = { "/portalApi/role/addChildRole" }, method = RequestMethod.POST)
438 public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
439 return getRoleController().addChildRole(request, response);
442 @RequestMapping(value = { "/portalApi/get_role/{appId}/{roleId}" }, method = RequestMethod.GET)
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.getCentralAuth()) {
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.writeValueAsString(
456 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 @RequestMapping(value = { "/portalApi/get_role_functions/{appId}" }, method = RequestMethod.GET)
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.getCentralAuth()) {
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 @RequestMapping(value = { "/portalApi/role_function_list/saveRoleFunction/{appId}" }, method = RequestMethod.POST)
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");
519 EPUser user = EPUserUtils.getUserSession(request);
520 boolean saveOrUpdateResponse = false;
522 EPApp requestedApp = appService.getApp(appId);
523 if (isAuthorizedUser(user, requestedApp)) {
524 fieldsValidation(requestedApp);
525 if (requestedApp.getCentralAuth()) {
526 String code = roleFunc.getType()+PIPE+roleFunc.getCode()+PIPE+roleFunc.getAction();
527 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
528 requestedApp.getUebKey());
529 if(domainRoleFunction != null && (domainRoleFunction.getType() == null || domainRoleFunction.getAction() == null)) {
530 addIfTypeActionDoesNotExits(domainRoleFunction);
532 boolean isSave = true;
533 if (domainRoleFunction != null && domainRoleFunction.getCode().equals(roleFunc.getCode())
534 && domainRoleFunction.getType().equals(roleFunc.getType())
535 && domainRoleFunction.getAction().equals(roleFunc.getAction())) {
536 domainRoleFunction.setName(roleFunc.getName());
537 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(domainRoleFunction,
541 roleFunc.setAppId(requestedApp.getId());
542 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(roleFunc,
545 if (saveOrUpdateResponse) {
546 EPUser requestedUser = externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
547 EPApp app = externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
548 String activityCode = (isSave)
549 ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION
550 : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION;
551 logExterlaAuthRoleFunctionActivity(code, requestedUser, app, activityCode);
554 throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
556 logger.info(EELFLoggerDelegate.auditLogger,
557 "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,
570 "saveRoleFunction: succeeded for app {}, function {}", app.getId(), code);
571 AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
572 auditLog.setComments(EcompPortalUtils.truncateString("saveRoleFunction role for app:"
573 + app.getId() + " and function:'" + code + "'",
574 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
575 auditService.logActivity(auditLog, null);
576 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
577 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
578 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
579 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
580 EcompPortalUtils.calculateDateTimeDifferenceForLog(
581 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
582 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
583 logger.info(EELFLoggerDelegate.auditLogger,
584 EPLogUtil.formatAuditLogMessage("RoleManageController.saveRoleFunction", activityCode,
585 String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(),
587 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
588 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
589 MDC.remove(SystemProperties.MDC_TIMER);
594 private void addIfTypeActionDoesNotExits(CentralV2RoleFunction domainRoleFunction) {
595 if(domainRoleFunction.getCode().contains(PIPE)) {
596 String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(domainRoleFunction.getCode());
597 String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(domainRoleFunction.getCode());
598 String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(domainRoleFunction.getCode());
599 domainRoleFunction.setType(newfunctionTypeFormat);
600 domainRoleFunction.setAction(newfunctionActionFormat);
601 domainRoleFunction.setCode(newfunctionCodeFormat);
603 String type = externalAccessRolesService.getFunctionCodeType(domainRoleFunction.getCode());
604 String action = externalAccessRolesService.getFunctionCodeAction(domainRoleFunction.getCode());
605 domainRoleFunction.setType(type);
606 domainRoleFunction.setAction(action);
610 @RequestMapping(value = { "/portalApi/role_function_list/removeRoleFunction/{appId}" }, method = RequestMethod.POST)
611 public PortalRestResponse<String> removeRoleFunction(HttpServletRequest request, HttpServletResponse response,
612 @RequestBody String roleFunc, @PathVariable("appId") Long appId) throws Exception {
613 EPUser user = EPUserUtils.getUserSession(request);
615 if (roleFunc!=null) {
616 SecureString secureString = new SecureString(roleFunc);
618 Validator validator = VALIDATOR_FACTORY.getValidator();
619 Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
621 if(!constraintViolations.isEmpty()){
622 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed");
623 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR");
628 EPApp requestedApp = appService.getApp(appId);
629 if (isAuthorizedUser(user, requestedApp)) {
630 fieldsValidation(requestedApp);
631 if (requestedApp.getCentralAuth()) {
632 ObjectMapper mapper = new ObjectMapper();
633 String data = roleFunc;
634 boolean getDelFuncResponse = false;
635 CentralV2RoleFunction availableRoleFunction = mapper.readValue(data, CentralV2RoleFunction.class);
636 String code = availableRoleFunction.getType() + PIPE + availableRoleFunction.getCode() + PIPE
637 + availableRoleFunction.getAction();
638 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
639 requestedApp.getUebKey());
640 getDelFuncResponse = externalAccessRolesService
641 .deleteCentralRoleFunction(domainRoleFunction.getCode(), requestedApp);
642 if (getDelFuncResponse) {
643 logger.info(EELFLoggerDelegate.applicationLogger,
644 "deleteRoleFunction: succeeded for app {}, role {}", requestedApp.getId(),
645 domainRoleFunction.getCode());
646 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION;
647 AuditLog auditLog = getAuditInfo(user, activityCode);
648 auditLog.setComments(
649 EcompPortalUtils.truncateString(
650 "Deleted function for app:" + requestedApp.getId() + " and function code:'"
651 + domainRoleFunction.getCode() + "'",
652 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
653 auditService.logActivity(auditLog, null);
654 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
655 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
656 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
657 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
658 EcompPortalUtils.calculateDateTimeDifferenceForLog(
659 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
660 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
661 logger.info(EELFLoggerDelegate.auditLogger,
662 EPLogUtil.formatAuditLogMessage("RoleManageController.removeRoleFunction",
663 EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION,
664 String.valueOf(user.getId()), user.getOrgUserId(),
665 domainRoleFunction.getCode()));
666 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
667 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
668 MDC.remove(SystemProperties.MDC_TIMER);
669 logger.info(EELFLoggerDelegate.auditLogger,
670 "Remove role function " + domainRoleFunction.getName());
673 throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
675 logger.info(EELFLoggerDelegate.auditLogger,
676 "RoleManageController.removeRoleFunction, Unauthorized user");
677 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
678 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
680 } catch (Exception e) {
681 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed", e);
682 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure");
684 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Deleted Successfully!", "Success");
687 @RequestMapping(value = { "/portalApi/centralizedApps" }, method = RequestMethod.GET)
688 public List<CentralizedApp> getCentralizedAppRoles(HttpServletRequest request, HttpServletResponse response, String userId) throws IOException {
690 SecureString secureString = new SecureString(userId);
692 Validator validator = VALIDATOR_FACTORY.getValidator();
693 Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
695 if(!constraintViolations.isEmpty()){
696 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed");
701 EPUser user = EPUserUtils.getUserSession(request);
702 List<CentralizedApp> applicationsList = null;
703 if (adminRolesService.isAccountAdmin(user) || adminRolesService.isSuperAdmin(user) || adminRolesService.isRoleAdmin(user)) {
704 applicationsList = externalAccessRolesService.getCentralizedAppsOfUser(userId);
706 logger.info(EELFLoggerDelegate.auditLogger,
707 "RoleManageController.getCentralizedAppRoles, Unauthorized user");
708 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
710 return applicationsList;
713 public RoleListController getRoleListController() {
714 return roleListController;
717 public void setRoleListController(RoleListController roleListController) {
718 this.roleListController = roleListController;
721 public RoleController getRoleController() {
722 return roleController;
725 public void setRoleController(RoleController roleController) {
726 this.roleController = roleController;
730 @RequestMapping(value = { "/portalApi/syncRoles" }, method = RequestMethod.POST, produces = "application/json")
731 public PortalRestResponse<String> syncRoles(HttpServletRequest request, HttpServletResponse response,
732 @RequestBody Long appId) {
733 EPUser user = EPUserUtils.getUserSession(request);
735 EPApp app = appService.getApp(appId);
736 if (isAuthorizedUser(user, app)) {
737 fieldsValidation(app);
738 externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
740 logger.info(EELFLoggerDelegate.auditLogger,
741 "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
742 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
743 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
745 } catch (Exception e) {
746 logger.error(EELFLoggerDelegate.errorLogger, "failed syncRoles", e);
747 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
749 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync roles completed successfully!", "Success");
752 @RequestMapping(value = { "/portalApi/syncFunctions" }, method = RequestMethod.POST, produces = "application/json")
753 public PortalRestResponse<String> syncFunctions(HttpServletRequest request, HttpServletResponse response,
754 @RequestBody Long appId) {
755 EPUser user = EPUserUtils.getUserSession(request);
757 EPApp app = appService.getApp(appId);
758 if (isAuthorizedUser(user, app)) {
759 fieldsValidation(app);
760 externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);
762 logger.info(EELFLoggerDelegate.auditLogger,
763 "RoleManageController.syncFunctions, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
764 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
765 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
767 } catch (Exception e) {
768 logger.error(EELFLoggerDelegate.errorLogger, "failed syncFunctions", e);
769 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
771 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync Functions completed successfully!", "Success");
774 public List<CentralV2Role> getAvailableChildRoles(String uebKey, Long roleId) throws Exception {
775 List<CentralV2Role> availableChildRoles = externalAccessRolesService.getRolesForApp(uebKey);
776 if (roleId == null || roleId == 0) {
777 return availableChildRoles;
779 CentralV2Role currentRole = externalAccessRolesService.getRoleInfo(roleId, uebKey);
780 Set<CentralV2Role> allParentRoles = new TreeSet<>();
781 allParentRoles = getAllParentRolesAsList(currentRole, allParentRoles);
782 Iterator<CentralV2Role> availableChildRolesIterator = availableChildRoles.iterator();
783 while (availableChildRolesIterator.hasNext()) {
784 CentralV2Role role = availableChildRolesIterator.next();
785 if (!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) {
786 availableChildRolesIterator.remove();
789 return availableChildRoles;
792 private Set<CentralV2Role> getAllParentRolesAsList(CentralV2Role role, Set<CentralV2Role> allParentRoles) {
793 Set<CentralV2Role> parentRoles = role.getParentRoles();
794 allParentRoles.addAll(parentRoles);
795 Iterator<CentralV2Role> parentRolesIterator = parentRoles.iterator();
796 while (parentRolesIterator.hasNext()) {
797 getAllParentRolesAsList(parentRolesIterator.next(), allParentRoles);
799 return allParentRoles;
802 public AuditLog getAuditInfo(EPUser user, String activityCode)
804 AuditLog auditLog = new AuditLog();
805 auditLog.setUserId(user.getId());
806 auditLog.setActivityCode(activityCode);
807 auditLog.setAffectedRecordId(user.getOrgUserId());
812 private void fieldsValidation(EPApp app) throws Exception{
814 List<EPApp> appInfo = externalAccessRolesService.getApp(app.getUebKey());
815 if(appInfo.isEmpty()){
816 throw new InvalidApplicationException("Invalid credentials");
818 if(!appInfo.isEmpty() && EcompPortalUtils.checkIfRemoteCentralAccessAllowed() && appInfo.get(0).getCentralAuth()){
819 ResponseEntity<String> response = externalAccessRolesService.getNameSpaceIfExists(appInfo.get(0));
820 if (response.getStatusCode().value() == HttpServletResponse.SC_NOT_FOUND)
821 throw new InvalidApplicationException("Invalid NameSpace");
825 private boolean isAuthorizedUser(EPUser user, EPApp requestedApp) {
826 if (user != null && (adminRolesService.isAccountAdminOfApplication(user, requestedApp)
827 || (adminRolesService.isSuperAdmin(user) && requestedApp.getId() == PortalConstants.PORTAL_APP_ID)))
832 private void SendErrorForUnauthorizedUser(HttpServletResponse response, EPUser user) throws IOException {
833 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
834 response.getWriter().write("Unauthorized User");
837 @RequestMapping(value = { "/portalApi/uploadRoleFunction/{appId}" }, method = RequestMethod.POST, produces = "application/json")
838 public PortalRestResponse<String> bulkUploadRoleFunc(HttpServletRequest request, HttpServletResponse response,
839 @RequestBody UploadRoleFunctionExtSystem data, @PathVariable("appId") Long appId) {
840 EPUser user = EPUserUtils.getUserSession(request);
842 EPApp app = appService.getApp(appId);
843 if (isAuthorizedUser(user, app)) {
844 fieldsValidation(app);
845 externalAccessRolesService.bulkUploadRoleFunc(data, app);
846 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
847 String code = data.getName()+","+data.getType()+ PIPE + data.getInstance() + PIPE + data.getAction();
848 logExterlaAuthRoleFunctionActivity(code , user, app, activityCode);
850 logger.info(EELFLoggerDelegate.auditLogger,
851 "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
852 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
853 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
855 } catch (Exception e) {
856 logger.error(EELFLoggerDelegate.errorLogger, "Failed bulkUploadRoleFunc!", e);
857 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
859 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Uploaded Role Function successfully!", "Success");