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;
49 import javax.servlet.http.HttpServletRequest;
50 import javax.servlet.http.HttpServletResponse;
51 import javax.validation.ConstraintViolation;
52 import javax.validation.Valid;
53 import javax.validation.Validation;
54 import javax.validation.Validator;
55 import javax.validation.ValidatorFactory;
56 import org.apache.commons.lang.StringUtils;
57 import org.json.JSONObject;
58 import org.onap.portalapp.controller.EPRestrictedBaseController;
59 import org.onap.portalapp.controller.core.RoleController;
60 import org.onap.portalapp.controller.core.RoleListController;
61 import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
62 import org.onap.portalapp.portal.domain.CentralizedApp;
63 import org.onap.portalapp.portal.domain.EPApp;
64 import org.onap.portalapp.portal.domain.EPUser;
65 import org.onap.portalapp.portal.domain.EcompAuditLog;
66 import org.onap.portalapp.portal.ecomp.model.PortalRestResponse;
67 import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
68 import org.onap.portalapp.portal.ecomp.model.UploadRoleFunctionExtSystem;
69 import org.onap.portalapp.portal.exceptions.DuplicateRecordException;
70 import org.onap.portalapp.portal.exceptions.InvalidApplicationException;
71 import org.onap.portalapp.portal.exceptions.InvalidRoleException;
72 import org.onap.portalapp.portal.exceptions.NonCentralizedAppException;
73 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
74 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
75 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
76 import org.onap.portalapp.portal.service.AdminRolesService;
77 import org.onap.portalapp.portal.service.EPAppService;
78 import org.onap.portalapp.portal.service.ExternalAccessRolesService;
79 import org.onap.portalapp.portal.transport.CentralV2Role;
80 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
81 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
82 import org.onap.portalapp.portal.utils.EcompPortalUtils;
83 import org.onap.portalapp.portal.utils.PortalConstants;
84 import org.onap.portalapp.util.EPUserUtils;
85 import org.onap.portalapp.validation.SecureString;
86 import org.onap.portalsdk.core.domain.AuditLog;
87 import org.onap.portalsdk.core.domain.Role;
88 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
89 import org.onap.portalsdk.core.service.AuditService;
90 import org.onap.portalsdk.core.util.SystemProperties;
91 import org.onap.portalsdk.core.web.support.JsonMessage;
93 import org.springframework.beans.factory.annotation.Autowired;
94 import org.springframework.context.annotation.EnableAspectJAutoProxy;
95 import org.springframework.http.ResponseEntity;
96 import org.springframework.web.bind.annotation.PathVariable;
97 import org.springframework.web.bind.annotation.RequestBody;
98 import org.springframework.web.bind.annotation.RequestMapping;
99 import org.springframework.web.bind.annotation.RequestMethod;
100 import org.springframework.web.bind.annotation.RestController;
101 import org.springframework.web.servlet.ModelAndView;
102 import com.fasterxml.jackson.databind.DeserializationFeature;
103 import com.fasterxml.jackson.databind.JsonNode;
104 import com.fasterxml.jackson.databind.ObjectMapper;
105 import com.fasterxml.jackson.databind.type.TypeFactory;
108 * Proxies REST calls to role-management functions that arrive on paths
109 * /portalApi/* over to controller methods provided by the SDK-Core library.
110 * Those controller methods are mounted on paths not exposed by the Portal FE.
113 @org.springframework.context.annotation.Configuration
114 @EnableAspectJAutoProxy
116 public class RoleManageController extends EPRestrictedBaseController {
117 private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();
119 private static final String PIPE = "|";
121 private static final String ROLE_INVALID_CHARS = "%=():,\"\"";
123 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleManageController.class);
126 private RoleController roleController;
129 private RoleListController roleListController;
132 private EPAppService appService;
135 private AuditService auditService;
138 private ExternalAccessRolesService externalAccessRolesService;
141 private AdminRolesService adminRolesService;
144 * Calls an SDK-Core library method that gets the available roles and writes
145 * them to the request object. Portal specifies a Hibernate mappings from the
146 * Role class to the fn_role_v view, which ensures that only Portal (app_id is
147 * null) roles are fetched.
149 * Any method declared void (no return value) or returning null causes the audit
150 * log aspect method to declare failure. TODO: should return a JSON string.
157 @RequestMapping(value = { "/portalApi/get_roles/{appId}" }, method = RequestMethod.GET)
158 public void getRoles(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId)
161 EPUser user = EPUserUtils.getUserSession(request);
162 EPApp requestedApp = appService.getApp(appId);
163 if (isAuthorizedUser(user, requestedApp)) {
164 fieldsValidation(requestedApp);
165 if (requestedApp.getCentralAuth()) {
166 List<CentralV2Role> answer = null;
167 Map<String, Object> model = new HashMap<>();
168 ObjectMapper mapper = new ObjectMapper();
169 answer = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey());
170 model.put("availableRoles", answer);
171 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
172 JSONObject j = new JSONObject(msg);
173 response.getWriter().write(j.toString());
175 throw new NonCentralizedAppException(requestedApp.getName());
177 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.getRoles, Unauthorized user");
178 SendErrorForUnauthorizedUser(response, user);
181 } catch (Exception e) {
182 logger.error(EELFLoggerDelegate.errorLogger, "getRoles failed", e);
186 @RequestMapping(value = { "/portalApi/role_list/toggleRole/{appId}/{roleId}" }, method = RequestMethod.POST)
187 public Map<String, Object> toggleRole(HttpServletRequest request, HttpServletResponse response,
188 @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception {
189 EPApp requestedApp = null;
190 String restcallStatus = null;
191 HashMap<String, Object> responseMap = new HashMap<>();
192 EPUser user = EPUserUtils.getUserSession(request);
194 requestedApp = appService.getApp(appId);
195 if (isAuthorizedUser(user, requestedApp)) {
196 fieldsValidation(requestedApp);
197 ObjectMapper mapper = new ObjectMapper();
198 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
199 CentralV2Role domainRole = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
200 // role. toggle active ind
201 boolean active = domainRole.getActive();
202 domainRole.setActive(!active);
204 String result = mapper.writeValueAsString(domainRole);
205 Role newRole = externalAccessRolesService.ConvertCentralRoleToRole(result);
206 ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService
207 .saveRoleForApplication(newRole, requestedApp.getUebKey());
208 boolean getAddResponse = externalRequestFieldsValidator.isResult();
209 if (getAddResponse) {
210 restcallStatus = "Success";
211 logger.info(EELFLoggerDelegate.auditLogger, "Toggle active status for role " + domainRole.getId());
213 restcallStatus = "Toggle Role Failed";
214 logger.info(EELFLoggerDelegate.auditLogger, "Toggle Role Failed " + domainRole.getId());
216 responseMap.put("restcallStatus", restcallStatus);
217 responseMap.put("availableRoles", externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()));
219 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.toggleRole, Unauthorized user");
220 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
221 responseMap.put("restcallStatus", " Unauthorized user");
223 } catch (Exception e) {
224 logger.error(EELFLoggerDelegate.errorLogger, "toggleRole failed", e);
230 @RequestMapping(value = { "/portalApi/role_list/removeRole/{appId}/{roleId}" }, method = RequestMethod.POST)
231 public Map<String, Object> removeRole(HttpServletRequest request, HttpServletResponse response,
232 @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception {
234 EPUser user = EPUserUtils.getUserSession(request);
235 EPApp requestedApp = null;
236 String restCallStatus = null;
237 HashMap<String, Object> responseMap = new HashMap<>();
238 ExternalRequestFieldsValidator externalRequestFieldsValidator = null;
240 requestedApp = appService.getApp(appId);
241 if (isAuthorizedUser(user, requestedApp)) {
242 fieldsValidation(requestedApp);
243 if (requestedApp.getCentralAuth()) {
244 externalRequestFieldsValidator = externalAccessRolesService.deleteDependencyRoleRecord(roleId,
245 requestedApp.getUebKey(), user.getOrgUserId());
246 boolean deleteResponse = externalRequestFieldsValidator.isResult();
247 if (deleteResponse) {
248 restCallStatus = "Success";
249 EPUser requestedUser = (EPUser) externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
250 EPApp app = (EPApp) externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
251 logger.info(EELFLoggerDelegate.applicationLogger, "deleteRole: succeeded for app {}, role {}",
252 app.getId(), roleId);
253 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE;
254 AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
255 auditLog.setComments(EcompPortalUtils.truncateString(
256 "Deleted role for app:" + app.getId() + " and role:'" + roleId + "'",
257 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
258 auditService.logActivity(auditLog, null);
259 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
260 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
261 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
262 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
263 EcompPortalUtils.calculateDateTimeDifferenceForLog(
264 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
265 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
266 logger.info(EELFLoggerDelegate.auditLogger,
267 EPLogUtil.formatAuditLogMessage("RoleManageController.removeRole",
268 EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE,
269 String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(),
271 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
272 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
273 MDC.remove(SystemProperties.MDC_TIMER);
275 restCallStatus = "Remove Role failed";
276 responseMap.put("error", externalRequestFieldsValidator.getDetailMessage());
277 logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed");
279 responseMap.put("restCallStatus", restCallStatus);
280 responseMap.put("availableRoles",
281 externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()));
283 throw new NonCentralizedAppException(requestedApp.getName());
285 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.removeRole, Unauthorized user");
286 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
287 responseMap.put("restCallStatus", " Unauthorized user");
289 } catch (Exception e) {
290 logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed", e);
296 @RequestMapping(value = { "/portalApi/role/saveRole/{appId}" }, method = RequestMethod.POST)
297 public Map<String, Object> saveRole(HttpServletRequest request, HttpServletResponse response,
298 @PathVariable("appId") Long appId) throws Exception {
299 EPUser user = EPUserUtils.getUserSession(request);
300 String responseString = null;
301 HashMap<String, Object> responseMap = new HashMap<>();
303 EPApp requestedApp = appService.getApp(appId);
304 if (isAuthorizedUser(user, requestedApp)) {
305 fieldsValidation(requestedApp);
306 if (requestedApp != null && requestedApp.getCentralAuth().equals(true)) {
307 ObjectMapper mapper = new ObjectMapper();
308 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
309 JsonNode root = mapper.readTree(request.getReader());
310 CentralV2Role role = mapper.readValue(root.get("role").toString(), CentralV2Role.class);
312 List<CentralV2Role> childRoles = mapper.readValue(root.get("childRoles").toString(),
313 TypeFactory.defaultInstance().constructCollectionType(List.class, CentralV2Role.class));
314 List<CentralV2RoleFunction> roleFunctions = mapper.readValue(root.get("roleFunctions").toString(),
315 TypeFactory.defaultInstance().constructCollectionType(List.class,
316 CentralV2RoleFunction.class));
317 if (role.getId() != null && StringUtils.containsAny(role.getName(), ROLE_INVALID_CHARS)) {
318 throw new InvalidRoleException("Invalid role name found for '" + role.getName()
319 + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
321 CentralV2Role domainRole;
322 if (role.getId() != null) {
323 domainRole = externalAccessRolesService.getRoleInfo(role.getId(), requestedApp.getUebKey());
324 domainRole.setName(role.getName());
325 domainRole.setPriority(role.getPriority());
327 // check for existing role of same name
328 List<CentralV2Role> roles = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey());
329 for (CentralV2Role existRole : roles)
330 if (existRole.getName().equalsIgnoreCase(role.getName()))
331 throw new DuplicateRecordException("Role already exists: " + existRole.getName());
333 domainRole = new CentralV2Role.CentralV2RoleBuilder().createCentralV2Role();
334 domainRole.setName(role.getName());
335 domainRole.setPriority(role.getPriority());
336 domainRole.setActive(role.getActive());
337 if (role.getChildRoles() != null && role.getChildRoles().size() > 0) {
338 for (Object childRole : childRoles) {
339 domainRole.addChildRole((CentralV2Role) childRole);
343 if (role.getRoleFunctions() != null && role.getRoleFunctions().size() > 0) {
344 domainRole.setRoleFunctions(new TreeSet<CentralV2RoleFunction>());
345 for (CentralV2RoleFunction roleFunction : roleFunctions) {
346 if (roleFunction.getType() == null && roleFunction.getAction() == null) {
347 throw new InvalidRoleException("Invalid role function type:" + roleFunction.getType()
348 + " and action: " + roleFunction.getAction() + " found while saving!");
350 if (EcompPortalUtils.checkFunctionCodeHasEncodePattern(roleFunction.getCode()))
351 roleFunction.setCode(roleFunction.getType() + PIPE
352 + EcompPortalUtils.encodeFunctionCode(roleFunction.getCode()) + PIPE
353 + roleFunction.getAction());
355 roleFunction.setCode(roleFunction.getType() + PIPE + roleFunction.getCode() + PIPE
356 + roleFunction.getAction());
357 domainRole.addRoleFunction((CentralV2RoleFunction) roleFunction);
360 domainRole.setRoleFunctions(new TreeSet<>());
362 String result = mapper.writeValueAsString(domainRole);
363 Role newRole = externalAccessRolesService.ConvertCentralRoleToRole(result);
364 ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService
365 .saveRoleForApplication(newRole, requestedApp.getUebKey());
366 boolean getAddResponse = externalRequestFieldsValidator.isResult();
367 if (getAddResponse) {
368 String activityCode = (role.getId() == null) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_ROLE
369 : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
370 logger.info(EELFLoggerDelegate.applicationLogger, "saveRole: succeeded for app {}, role {}",
371 requestedApp.getId(), role.getName());
372 AuditLog auditLog = new AuditLog();
373 auditLog.setUserId(user.getId());
374 auditLog.setActivityCode(activityCode);
375 auditLog.setComments(EcompPortalUtils.truncateString(
376 "saveRole role for app:" + requestedApp.getId() + " and role:'" + role.getName() + "'",
377 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
378 auditLog.setAffectedRecordId(user.getOrgUserId());
379 auditService.logActivity(auditLog, null);
380 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
381 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
382 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
383 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
384 EcompPortalUtils.calculateDateTimeDifferenceForLog(
385 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
386 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
387 logger.info(EELFLoggerDelegate.auditLogger,
388 EPLogUtil.formatAuditLogMessage("RoleManageController.saveRole", activityCode,
389 String.valueOf(user.getId()), user.getOrgUserId(), role.getName()));
390 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
391 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
392 MDC.remove(SystemProperties.MDC_TIMER);
393 responseMap.put("status", "Success");
394 responseMap.put("role", domainRole);
396 if (externalRequestFieldsValidator.getDetailMessage().contains("406")) {
397 externalRequestFieldsValidator.setDetailMessage("Failed to save role for '" + role.getName()
398 + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
400 responseMap.put("status", "SaveRole Failed");
401 responseMap.put("role", responseString);
402 responseMap.put("error", externalRequestFieldsValidator.getDetailMessage());
403 logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed");
407 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRole, Unauthorized user");
408 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
409 responseMap.put("error", " Unauthorized user");
411 } catch (Exception e) {
412 logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e);
413 responseMap.put("error", e.getMessage());
418 @RequestMapping(value = { "/portalApi/role/removeRoleFunction" }, method = RequestMethod.POST)
419 public ModelAndView removeRoleRoleFunction(HttpServletRequest request, HttpServletResponse response)
421 return getRoleController().removeRoleFunction(request, response);
424 @RequestMapping(value = { "/portalApi/role/addRoleFunction" }, method = RequestMethod.POST)
425 public ModelAndView addRoleRoRoleFunction(HttpServletRequest request, HttpServletResponse response)
427 return getRoleController().addRoleFunction(request, response);
430 @RequestMapping(value = { "/portalApi/role/removeChildRole" }, method = RequestMethod.POST)
431 public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
432 return getRoleController().removeChildRole(request, response);
435 @RequestMapping(value = { "/portalApi/role/addChildRole" }, method = RequestMethod.POST)
436 public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
437 return getRoleController().addChildRole(request, response);
440 @RequestMapping(value = { "/portalApi/get_role/{appId}/{roleId}" }, method = RequestMethod.GET)
441 public void getRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
442 @PathVariable("roleId") Long roleId) throws Exception {
444 EPUser user = EPUserUtils.getUserSession(request);
445 ObjectMapper mapper = new ObjectMapper();
446 EPApp requestedApp = appService.getApp(appId);
447 if (isAuthorizedUser(user, requestedApp)) {
448 fieldsValidation(requestedApp);
449 if (requestedApp.getCentralAuth()) {
450 CentralV2Role answer = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
451 logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + roleId);
452 Map<String, Object> model = new HashMap<>();
453 model.put("availableRoleFunctions", mapper
454 .writeValueAsString(externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey())));
455 model.put("availableRoles",
456 mapper.writeValueAsString(getAvailableChildRoles(requestedApp.getUebKey(), roleId)));
457 model.put("role", mapper.writeValueAsString(answer));
458 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
459 JSONObject j = new JSONObject(msg);
460 response.getWriter().write(j.toString());
462 throw new NonCentralizedAppException(requestedApp.getName());
464 logger.info(EELFLoggerDelegate.auditLogger,
465 "RoleManageController.getRoleFunctionList, Unauthorized user");
466 SendErrorForUnauthorizedUser(response, user);
468 } catch (Exception e) {
469 logger.error(EELFLoggerDelegate.errorLogger, "getRole failed", e);
474 @RequestMapping(value = { "/portalApi/get_role_functions/{appId}" }, method = RequestMethod.GET)
475 public void getRoleFunctionList(HttpServletRequest request, HttpServletResponse response,
476 @PathVariable("appId") Long appId) throws Exception {
478 EPUser user = EPUserUtils.getUserSession(request);
479 EPApp requestedApp = appService.getApp(appId);
480 if (isAuthorizedUser(user, requestedApp)) {
481 fieldsValidation(requestedApp);
482 if (requestedApp.getCentralAuth()) {
483 List<CentralV2RoleFunction> answer = null;
484 Map<String, Object> model = new HashMap<>();
485 ObjectMapper mapper = new ObjectMapper();
486 answer = externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey());
487 model.put("availableRoleFunctions", answer);
488 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
489 JSONObject j = new JSONObject(msg);
490 response.getWriter().write(j.toString());
492 throw new NonCentralizedAppException(requestedApp.getName());
494 logger.info(EELFLoggerDelegate.auditLogger,
495 "RoleManageController.getRoleFunctionList, Unauthorized user");
496 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
497 response.getWriter().write("Unauthorized User");
499 } catch (Exception e) {
500 logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunctionList failed", e);
505 @RequestMapping(value = { "/portalApi/role_function_list/saveRoleFunction/{appId}" }, method = RequestMethod.POST)
506 public PortalRestResponse<String> saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @Valid @RequestBody CentralV2RoleFunction roleFunc,
507 @PathVariable("appId") Long appId) throws Exception {
508 if (roleFunc!=null) {
509 Validator validator = VALIDATOR_FACTORY.getValidator();
510 Set<ConstraintViolation<CentralV2RoleFunction>> constraintViolations = validator.validate(roleFunc);
512 if(!constraintViolations.isEmpty()){
513 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed");
514 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR");
518 EPUser user = EPUserUtils.getUserSession(request);
519 boolean saveOrUpdateResponse = false;
521 EPApp requestedApp = appService.getApp(appId);
522 if (isAuthorizedUser(user, requestedApp)) {
523 fieldsValidation(requestedApp);
524 if (requestedApp.getCentralAuth() && roleFunc!=null) {
525 String code = roleFunc.getType() + PIPE + roleFunc.getCode() + PIPE + roleFunc.getAction();
526 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
527 requestedApp.getUebKey());
528 if (domainRoleFunction != null
529 && (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) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION
549 : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION;
550 logExterlaAuthRoleFunctionActivity(code, requestedUser, app, activityCode);
553 throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
555 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRoleFunction, Unauthorized user");
556 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
557 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
559 } catch (Exception e) {
560 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed", e);
561 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure");
563 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Saved Successfully!", "Success");
566 private void logExterlaAuthRoleFunctionActivity(String code, EPUser requestedUser, EPApp app, String activityCode) {
567 logger.info(EELFLoggerDelegate.applicationLogger, "saveRoleFunction: succeeded for app {}, function {}",
569 AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
570 auditLog.setComments(EcompPortalUtils.truncateString(
571 "saveRoleFunction role for app:" + app.getId() + " and function:'" + code + "'",
572 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
573 auditService.logActivity(auditLog, null);
574 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
575 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
576 EcompPortalUtils.calculateDateTimeDifferenceForLog(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
577 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
578 logger.info(EELFLoggerDelegate.auditLogger,
579 EPLogUtil.formatAuditLogMessage("RoleManageController.saveRoleFunction", activityCode,
580 String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(), code));
581 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
582 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
583 MDC.remove(SystemProperties.MDC_TIMER);
586 private void addIfTypeActionDoesNotExits(CentralV2RoleFunction domainRoleFunction) {
587 if (domainRoleFunction.getCode().contains(PIPE)) {
588 String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(domainRoleFunction.getCode());
589 String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(domainRoleFunction.getCode());
590 String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(domainRoleFunction.getCode());
591 domainRoleFunction.setType(newfunctionTypeFormat);
592 domainRoleFunction.setAction(newfunctionActionFormat);
593 domainRoleFunction.setCode(newfunctionCodeFormat);
595 String type = externalAccessRolesService.getFunctionCodeType(domainRoleFunction.getCode());
596 String action = externalAccessRolesService.getFunctionCodeAction(domainRoleFunction.getCode());
597 domainRoleFunction.setType(type);
598 domainRoleFunction.setAction(action);
602 @RequestMapping(value = { "/portalApi/role_function_list/removeRoleFunction/{appId}" }, method = RequestMethod.POST)
603 public PortalRestResponse<String> removeRoleFunction(HttpServletRequest request, HttpServletResponse response,
604 @RequestBody String roleFunc, @PathVariable("appId") Long appId) throws Exception {
605 EPUser user = EPUserUtils.getUserSession(request);
607 if (roleFunc!=null) {
608 SecureString secureString = new SecureString(roleFunc);
610 Validator validator = VALIDATOR_FACTORY.getValidator();
611 Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
613 if(!constraintViolations.isEmpty()){
614 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed");
615 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR");
620 EPApp requestedApp = appService.getApp(appId);
621 if (isAuthorizedUser(user, requestedApp)) {
622 fieldsValidation(requestedApp);
623 if (requestedApp.getCentralAuth()) {
624 ObjectMapper mapper = new ObjectMapper();
625 String data = roleFunc;
626 boolean getDelFuncResponse = false;
627 CentralV2RoleFunction availableRoleFunction = mapper.readValue(data, CentralV2RoleFunction.class);
628 String code = availableRoleFunction.getType() + PIPE + availableRoleFunction.getCode() + PIPE
629 + availableRoleFunction.getAction();
630 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
631 requestedApp.getUebKey());
632 getDelFuncResponse = externalAccessRolesService
633 .deleteCentralRoleFunction(domainRoleFunction.getCode(), requestedApp);
634 if (getDelFuncResponse) {
635 logger.info(EELFLoggerDelegate.applicationLogger,
636 "deleteRoleFunction: succeeded for app {}, role {}", requestedApp.getId(),
637 domainRoleFunction.getCode());
638 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION;
639 AuditLog auditLog = getAuditInfo(user, activityCode);
640 auditLog.setComments(
641 EcompPortalUtils.truncateString(
642 "Deleted function for app:" + requestedApp.getId() + " and function code:'"
643 + domainRoleFunction.getCode() + "'",
644 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
645 auditService.logActivity(auditLog, null);
646 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
647 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
648 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
649 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
650 EcompPortalUtils.calculateDateTimeDifferenceForLog(
651 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
652 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
653 logger.info(EELFLoggerDelegate.auditLogger,
654 EPLogUtil.formatAuditLogMessage("RoleManageController.removeRoleFunction",
655 EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION,
656 String.valueOf(user.getId()), user.getOrgUserId(),
657 domainRoleFunction.getCode()));
658 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
659 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
660 MDC.remove(SystemProperties.MDC_TIMER);
661 logger.info(EELFLoggerDelegate.auditLogger,
662 "Remove role function " + domainRoleFunction.getName());
665 throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
667 logger.info(EELFLoggerDelegate.auditLogger,
668 "RoleManageController.removeRoleFunction, Unauthorized user");
669 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
670 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
672 } catch (Exception e) {
673 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed", e);
674 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure");
676 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Deleted Successfully!", "Success");
679 @RequestMapping(value = { "/portalApi/centralizedApps" }, method = RequestMethod.GET)
680 public List<CentralizedApp> getCentralizedAppRoles(HttpServletRequest request, HttpServletResponse response, String userId) {
682 SecureString secureString = new SecureString(userId);
684 Validator validator = VALIDATOR_FACTORY.getValidator();
685 Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
687 if(!constraintViolations.isEmpty()){
688 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed");
693 EPUser user = EPUserUtils.getUserSession(request);
694 List<CentralizedApp> applicationsList = null;
695 if (adminRolesService.isAccountAdmin(user) || adminRolesService.isSuperAdmin(user)
696 || adminRolesService.isRoleAdmin(user)) {
697 applicationsList = externalAccessRolesService.getCentralizedAppsOfUser(userId);
699 logger.info(EELFLoggerDelegate.auditLogger,
700 "RoleManageController.getCentralizedAppRoles, Unauthorized user");
701 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
703 return applicationsList;
706 public RoleListController getRoleListController() {
707 return roleListController;
710 public void setRoleListController(RoleListController roleListController) {
711 this.roleListController = roleListController;
714 public RoleController getRoleController() {
715 return roleController;
718 public void setRoleController(RoleController roleController) {
719 this.roleController = roleController;
722 @RequestMapping(value = { "/portalApi/syncRoles" }, method = RequestMethod.POST, produces = "application/json")
723 public PortalRestResponse<String> syncRoles(HttpServletRequest request, HttpServletResponse response,
724 @RequestBody Long appId) {
725 EPUser user = EPUserUtils.getUserSession(request);
727 EPApp app = appService.getApp(appId);
728 if (isAuthorizedUser(user, app)) {
729 fieldsValidation(app);
730 externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
732 logger.info(EELFLoggerDelegate.auditLogger,
733 "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
734 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
735 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
737 } catch (Exception e) {
738 logger.error(EELFLoggerDelegate.errorLogger, "failed syncRoles", e);
739 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
741 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync roles completed successfully!", "Success");
744 @RequestMapping(value = { "/portalApi/syncFunctions" }, method = RequestMethod.POST, produces = "application/json")
745 public PortalRestResponse<String> syncFunctions(HttpServletRequest request, HttpServletResponse response,
746 @RequestBody Long appId) {
747 EPUser user = EPUserUtils.getUserSession(request);
749 EPApp app = appService.getApp(appId);
750 if (isAuthorizedUser(user, app)) {
751 fieldsValidation(app);
752 externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);
754 logger.info(EELFLoggerDelegate.auditLogger,
755 "RoleManageController.syncFunctions, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
756 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
757 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
759 } catch (Exception e) {
760 logger.error(EELFLoggerDelegate.errorLogger, "failed syncFunctions", e);
761 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
763 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync Functions completed successfully!", "Success");
766 public List<CentralV2Role> getAvailableChildRoles(String uebKey, Long roleId) throws Exception {
767 List<CentralV2Role> availableChildRoles = externalAccessRolesService.getRolesForApp(uebKey);
768 if (roleId == null || roleId == 0) {
769 return availableChildRoles;
771 CentralV2Role currentRole = externalAccessRolesService.getRoleInfo(roleId, uebKey);
772 Set<CentralV2Role> allParentRoles = new TreeSet<>();
773 allParentRoles = getAllParentRolesAsList(currentRole, allParentRoles);
774 Iterator<CentralV2Role> availableChildRolesIterator = availableChildRoles.iterator();
775 while (availableChildRolesIterator.hasNext()) {
776 CentralV2Role role = availableChildRolesIterator.next();
777 if (!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) {
778 availableChildRolesIterator.remove();
781 return availableChildRoles;
784 private Set<CentralV2Role> getAllParentRolesAsList(CentralV2Role role, Set<CentralV2Role> allParentRoles) {
785 Set<CentralV2Role> parentRoles = role.getParentRoles();
786 allParentRoles.addAll(parentRoles);
787 Iterator<CentralV2Role> parentRolesIterator = parentRoles.iterator();
788 while (parentRolesIterator.hasNext()) {
789 getAllParentRolesAsList(parentRolesIterator.next(), allParentRoles);
791 return allParentRoles;
794 public AuditLog getAuditInfo(EPUser user, String activityCode) {
795 AuditLog auditLog = new AuditLog();
796 auditLog.setUserId(user.getId());
797 auditLog.setActivityCode(activityCode);
798 auditLog.setAffectedRecordId(user.getOrgUserId());
803 private void fieldsValidation(EPApp app) throws Exception {
805 List<EPApp> appInfo = externalAccessRolesService.getApp(app.getUebKey());
806 if (appInfo.isEmpty()) {
807 throw new InvalidApplicationException("Invalid credentials");
809 if (!appInfo.isEmpty() && EcompPortalUtils.checkIfRemoteCentralAccessAllowed()
810 && appInfo.get(0).getCentralAuth()) {
811 ResponseEntity<String> response = externalAccessRolesService.getNameSpaceIfExists(appInfo.get(0));
812 if (response.getStatusCode().value() == HttpServletResponse.SC_NOT_FOUND)
813 throw new InvalidApplicationException("Invalid NameSpace");
817 private boolean isAuthorizedUser(EPUser user, EPApp requestedApp) {
818 if (user != null && (adminRolesService.isAccountAdminOfApplication(user, requestedApp)
819 || (adminRolesService.isSuperAdmin(user) && requestedApp.getId().equals(PortalConstants.PORTAL_APP_ID))))
824 private void SendErrorForUnauthorizedUser(HttpServletResponse response, EPUser user) throws IOException {
825 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
826 response.getWriter().write("Unauthorized User");
829 @RequestMapping(value = {
830 "/portalApi/uploadRoleFunction/{appId}" }, method = RequestMethod.POST, produces = "application/json")
831 public PortalRestResponse<String> bulkUploadRoleFunc(HttpServletRequest request, HttpServletResponse response,
832 @RequestBody UploadRoleFunctionExtSystem data, @PathVariable("appId") Long appId) {
833 EPUser user = EPUserUtils.getUserSession(request);
835 EPApp app = appService.getApp(appId);
836 if (isAuthorizedUser(user, app)) {
837 fieldsValidation(app);
838 externalAccessRolesService.bulkUploadRoleFunc(data, app);
839 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
840 String code = data.getName() + "," + data.getType() + PIPE + data.getInstance() + PIPE
842 logExterlaAuthRoleFunctionActivity(code, user, app, activityCode);
844 logger.info(EELFLoggerDelegate.auditLogger,
845 "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
846 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
847 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
849 } catch (Exception e) {
850 logger.error(EELFLoggerDelegate.errorLogger, "Failed bulkUploadRoleFunc!", e);
851 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
853 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Uploaded Role Function successfully!", "Success");