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;
144 private AdminRolesService adminRolesService;
147 * Calls an SDK-Core library method that gets the available roles and writes
148 * them to the request object. Portal specifies a Hibernate mappings from the
149 * Role class to the fn_role_v view, which ensures that only Portal (app_id is
150 * null) roles are fetched.
152 * Any method declared void (no return value) or returning null causes the audit
153 * log aspect method to declare failure. TODO: should return a JSON string.
160 @RequestMapping(value = { "/portalApi/get_roles/{appId}" }, method = RequestMethod.GET)
161 public void getRoles(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId)
164 EPUser user = EPUserUtils.getUserSession(request);
165 EPApp requestedApp = appService.getApp(appId);
166 if (isAuthorizedUser(user, requestedApp)) {
167 fieldsValidation(requestedApp);
168 if (requestedApp.getCentralAuth()) {
169 List<CentralV2Role> answer = null;
170 Map<String, Object> model = new HashMap<>();
171 ObjectMapper mapper = new ObjectMapper();
172 answer = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey());
173 model.put("availableRoles", answer);
174 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
175 JSONObject j = new JSONObject(msg);
176 response.getWriter().write(j.toString());
178 throw new NonCentralizedAppException(requestedApp.getName());
180 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.getRoles, Unauthorized user");
181 SendErrorForUnauthorizedUser(response, user);
184 } catch (Exception e) {
185 logger.error(EELFLoggerDelegate.errorLogger, "getRoles failed", e);
189 @RequestMapping(value = { "/portalApi/role_list/toggleRole/{appId}/{roleId}" }, method = RequestMethod.POST)
190 public Map<String, Object> toggleRole(HttpServletRequest request, HttpServletResponse response,
191 @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception {
192 EPApp requestedApp = null;
193 String restcallStatus = null;
194 HashMap<String, Object> responseMap = new HashMap<>();
195 EPUser user = EPUserUtils.getUserSession(request);
197 requestedApp = appService.getApp(appId);
198 if (isAuthorizedUser(user, requestedApp)) {
199 fieldsValidation(requestedApp);
200 ObjectMapper mapper = new ObjectMapper();
201 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
202 CentralV2Role domainRole = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
203 // role. toggle active ind
204 boolean active = domainRole.getActive();
205 domainRole.setActive(!active);
207 String result = mapper.writeValueAsString(domainRole);
208 Role newRole = externalAccessRolesService.ConvertCentralRoleToRole(result);
209 ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService
210 .saveRoleForApplication(newRole, requestedApp.getUebKey());
211 boolean getAddResponse = externalRequestFieldsValidator.isResult();
212 if (getAddResponse) {
213 restcallStatus = "Success";
214 logger.info(EELFLoggerDelegate.auditLogger, "Toggle active status for role " + domainRole.getId());
216 restcallStatus = "Toggle Role Failed";
217 logger.info(EELFLoggerDelegate.auditLogger, "Toggle Role Failed " + domainRole.getId());
219 responseMap.put("restcallStatus", restcallStatus);
220 responseMap.put("availableRoles", externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()));
222 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.toggleRole, Unauthorized user");
223 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
224 responseMap.put("restcallStatus", " Unauthorized user");
226 } catch (Exception e) {
227 logger.error(EELFLoggerDelegate.errorLogger, "toggleRole failed", e);
233 @RequestMapping(value = { "/portalApi/role_list/removeRole/{appId}/{roleId}" }, method = RequestMethod.POST)
234 public Map<String, Object> removeRole(HttpServletRequest request, HttpServletResponse response,
235 @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception {
237 EPUser user = EPUserUtils.getUserSession(request);
238 EPApp requestedApp = null;
239 String restCallStatus = null;
240 HashMap<String, Object> responseMap = new HashMap<>();
241 ExternalRequestFieldsValidator externalRequestFieldsValidator = null;
243 requestedApp = appService.getApp(appId);
244 if (isAuthorizedUser(user, requestedApp)) {
245 fieldsValidation(requestedApp);
246 if (requestedApp.getCentralAuth()) {
247 externalRequestFieldsValidator = externalAccessRolesService.deleteDependencyRoleRecord(roleId,
248 requestedApp.getUebKey(), user.getOrgUserId());
249 boolean deleteResponse = externalRequestFieldsValidator.isResult();
250 if (deleteResponse) {
251 restCallStatus = "Success";
252 EPUser requestedUser = (EPUser) externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
253 EPApp app = (EPApp) externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
254 logger.info(EELFLoggerDelegate.applicationLogger, "deleteRole: succeeded for app {}, role {}",
255 app.getId(), roleId);
256 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE;
257 AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
258 auditLog.setComments(EcompPortalUtils.truncateString(
259 "Deleted role for app:" + app.getId() + " and role:'" + roleId + "'",
260 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
261 auditService.logActivity(auditLog, null);
262 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
263 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
264 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
265 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
266 EcompPortalUtils.calculateDateTimeDifferenceForLog(
267 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
268 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
269 logger.info(EELFLoggerDelegate.auditLogger,
270 EPLogUtil.formatAuditLogMessage("RoleManageController.removeRole",
271 EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE,
272 String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(),
274 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
275 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
276 MDC.remove(SystemProperties.MDC_TIMER);
278 restCallStatus = "Remove Role failed";
279 responseMap.put("error", externalRequestFieldsValidator.getDetailMessage());
280 logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed");
282 responseMap.put("restCallStatus", restCallStatus);
283 responseMap.put("availableRoles",
284 externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()));
286 throw new NonCentralizedAppException(requestedApp.getName());
288 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.removeRole, Unauthorized user");
289 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
290 responseMap.put("restCallStatus", " Unauthorized user");
292 } catch (Exception e) {
293 logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed", e);
299 @RequestMapping(value = { "/portalApi/role/saveRole/{appId}" }, method = RequestMethod.POST)
300 public Map<String, Object> saveRole(HttpServletRequest request, HttpServletResponse response,
301 @PathVariable("appId") Long appId) throws Exception {
302 EPUser user = EPUserUtils.getUserSession(request);
303 String responseString = null;
304 HashMap<String, Object> responseMap = new HashMap<>();
306 EPApp requestedApp = appService.getApp(appId);
307 if (isAuthorizedUser(user, requestedApp)) {
308 fieldsValidation(requestedApp);
309 if (requestedApp != null && requestedApp.getCentralAuth().equals(true)) {
310 ObjectMapper mapper = new ObjectMapper();
311 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
312 JsonNode root = mapper.readTree(request.getReader());
313 CentralV2Role role = mapper.readValue(root.get("role").toString(), CentralV2Role.class);
315 List<CentralV2Role> childRoles = mapper.readValue(root.get("childRoles").toString(),
316 TypeFactory.defaultInstance().constructCollectionType(List.class, CentralV2Role.class));
317 List<CentralV2RoleFunction> roleFunctions = mapper.readValue(root.get("roleFunctions").toString(),
318 TypeFactory.defaultInstance().constructCollectionType(List.class,
319 CentralV2RoleFunction.class));
320 if (role.getId() != null && StringUtils.containsAny(role.getName(), ROLE_INVALID_CHARS)) {
321 throw new InvalidRoleException("Invalid role name found for '" + role.getName()
322 + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
324 CentralV2Role domainRole;
325 if (role.getId() != null) {
326 domainRole = externalAccessRolesService.getRoleInfo(role.getId(), requestedApp.getUebKey());
327 domainRole.setName(role.getName());
328 domainRole.setPriority(role.getPriority());
330 // check for existing role of same name
331 List<CentralV2Role> roles = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey());
332 for (CentralV2Role existRole : roles)
333 if (existRole.getName().equalsIgnoreCase(role.getName()))
334 throw new DuplicateRecordException("Role already exists: " + existRole.getName());
336 domainRole = new CentralV2Role();
337 domainRole.setName(role.getName());
338 domainRole.setPriority(role.getPriority());
339 domainRole.setActive(role.getActive());
340 if (role.getChildRoles() != null && role.getChildRoles().size() > 0) {
341 for (Object childRole : childRoles) {
342 domainRole.addChildRole((CentralV2Role) childRole);
346 if (role.getRoleFunctions() != null && role.getRoleFunctions().size() > 0) {
347 domainRole.setRoleFunctions(new TreeSet<CentralV2RoleFunction>());
348 for (CentralV2RoleFunction roleFunction : roleFunctions) {
349 if (roleFunction.getType() == null && roleFunction.getAction() == null) {
350 throw new InvalidRoleException("Invalid role function type:" + roleFunction.getType()
351 + " and action: " + roleFunction.getAction() + " found while saving!");
353 if (EcompPortalUtils.checkFunctionCodeHasEncodePattern(roleFunction.getCode()))
354 roleFunction.setCode(roleFunction.getType() + PIPE
355 + EcompPortalUtils.encodeFunctionCode(roleFunction.getCode()) + PIPE
356 + roleFunction.getAction());
358 roleFunction.setCode(roleFunction.getType() + PIPE + roleFunction.getCode() + PIPE
359 + roleFunction.getAction());
360 domainRole.addRoleFunction((CentralV2RoleFunction) roleFunction);
363 domainRole.setRoleFunctions(new TreeSet<>());
365 String result = mapper.writeValueAsString(domainRole);
366 Role newRole = externalAccessRolesService.ConvertCentralRoleToRole(result);
367 ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService
368 .saveRoleForApplication(newRole, requestedApp.getUebKey());
369 boolean getAddResponse = externalRequestFieldsValidator.isResult();
370 if (getAddResponse) {
371 String activityCode = (role.getId() == null) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_ROLE
372 : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
373 logger.info(EELFLoggerDelegate.applicationLogger, "saveRole: succeeded for app {}, role {}",
374 requestedApp.getId(), role.getName());
375 AuditLog auditLog = new AuditLog();
376 auditLog.setUserId(user.getId());
377 auditLog.setActivityCode(activityCode);
378 auditLog.setComments(EcompPortalUtils.truncateString(
379 "saveRole role for app:" + requestedApp.getId() + " and role:'" + role.getName() + "'",
380 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
381 auditLog.setAffectedRecordId(user.getOrgUserId());
382 auditService.logActivity(auditLog, null);
383 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
384 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
385 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
386 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
387 EcompPortalUtils.calculateDateTimeDifferenceForLog(
388 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
389 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
390 logger.info(EELFLoggerDelegate.auditLogger,
391 EPLogUtil.formatAuditLogMessage("RoleManageController.saveRole", activityCode,
392 String.valueOf(user.getId()), user.getOrgUserId(), role.getName()));
393 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
394 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
395 MDC.remove(SystemProperties.MDC_TIMER);
396 responseMap.put("status", "Success");
397 responseMap.put("role", domainRole);
399 if (externalRequestFieldsValidator.getDetailMessage().contains("406")) {
400 externalRequestFieldsValidator.setDetailMessage("Failed to save role for '" + role.getName()
401 + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
403 responseMap.put("status", "SaveRole Failed");
404 responseMap.put("role", responseString);
405 responseMap.put("error", externalRequestFieldsValidator.getDetailMessage());
406 logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed");
410 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRole, Unauthorized user");
411 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
412 responseMap.put("error", " Unauthorized user");
414 } catch (Exception e) {
415 logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e);
416 responseMap.put("error", e.getMessage());
421 @RequestMapping(value = { "/portalApi/role/removeRoleFunction" }, method = RequestMethod.POST)
422 public ModelAndView removeRoleRoleFunction(HttpServletRequest request, HttpServletResponse response)
424 return getRoleController().removeRoleFunction(request, response);
427 @RequestMapping(value = { "/portalApi/role/addRoleFunction" }, method = RequestMethod.POST)
428 public ModelAndView addRoleRoRoleFunction(HttpServletRequest request, HttpServletResponse response)
430 return getRoleController().addRoleFunction(request, response);
433 @RequestMapping(value = { "/portalApi/role/removeChildRole" }, method = RequestMethod.POST)
434 public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
435 return getRoleController().removeChildRole(request, response);
438 @RequestMapping(value = { "/portalApi/role/addChildRole" }, method = RequestMethod.POST)
439 public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
440 return getRoleController().addChildRole(request, response);
443 @RequestMapping(value = { "/portalApi/get_role/{appId}/{roleId}" }, method = RequestMethod.GET)
444 public void getRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
445 @PathVariable("roleId") Long roleId) throws Exception {
447 EPUser user = EPUserUtils.getUserSession(request);
448 ObjectMapper mapper = new ObjectMapper();
449 EPApp requestedApp = appService.getApp(appId);
450 if (isAuthorizedUser(user, requestedApp)) {
451 fieldsValidation(requestedApp);
452 if (requestedApp.getCentralAuth()) {
453 CentralV2Role answer = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
454 logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + roleId);
455 Map<String, Object> model = new HashMap<>();
456 model.put("availableRoleFunctions", mapper
457 .writeValueAsString(externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey())));
458 model.put("availableRoles",
459 mapper.writeValueAsString(getAvailableChildRoles(requestedApp.getUebKey(), roleId)));
460 model.put("role", mapper.writeValueAsString(answer));
461 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
462 JSONObject j = new JSONObject(msg);
463 response.getWriter().write(j.toString());
465 throw new NonCentralizedAppException(requestedApp.getName());
467 logger.info(EELFLoggerDelegate.auditLogger,
468 "RoleManageController.getRoleFunctionList, Unauthorized user");
469 SendErrorForUnauthorizedUser(response, user);
471 } catch (Exception e) {
472 logger.error(EELFLoggerDelegate.errorLogger, "getRole failed", e);
477 @RequestMapping(value = { "/portalApi/get_role_functions/{appId}" }, method = RequestMethod.GET)
478 public void getRoleFunctionList(HttpServletRequest request, HttpServletResponse response,
479 @PathVariable("appId") Long appId) throws Exception {
481 EPUser user = EPUserUtils.getUserSession(request);
482 EPApp requestedApp = appService.getApp(appId);
483 if (isAuthorizedUser(user, requestedApp)) {
484 fieldsValidation(requestedApp);
485 if (requestedApp.getCentralAuth()) {
486 List<CentralV2RoleFunction> answer = null;
487 Map<String, Object> model = new HashMap<>();
488 ObjectMapper mapper = new ObjectMapper();
489 answer = externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey());
490 model.put("availableRoleFunctions", answer);
491 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
492 JSONObject j = new JSONObject(msg);
493 response.getWriter().write(j.toString());
495 throw new NonCentralizedAppException(requestedApp.getName());
497 logger.info(EELFLoggerDelegate.auditLogger,
498 "RoleManageController.getRoleFunctionList, Unauthorized user");
499 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
500 response.getWriter().write("Unauthorized User");
502 } catch (Exception e) {
503 logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunctionList failed", e);
508 @RequestMapping(value = { "/portalApi/role_function_list/saveRoleFunction/{appId}" }, method = RequestMethod.POST)
509 public PortalRestResponse<String> saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @Valid @RequestBody CentralV2RoleFunction roleFunc,
510 @PathVariable("appId") Long appId) throws Exception {
511 if (roleFunc!=null) {
512 Validator validator = VALIDATOR_FACTORY.getValidator();
513 Set<ConstraintViolation<CentralV2RoleFunction>> constraintViolations = validator.validate(roleFunc);
515 if(!constraintViolations.isEmpty()){
516 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed");
517 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR");
521 EPUser user = EPUserUtils.getUserSession(request);
522 boolean saveOrUpdateResponse = false;
524 EPApp requestedApp = appService.getApp(appId);
525 if (isAuthorizedUser(user, requestedApp)) {
526 fieldsValidation(requestedApp);
527 if (requestedApp.getCentralAuth() && roleFunc!=null) {
528 String code = roleFunc.getType() + PIPE + roleFunc.getCode() + PIPE + roleFunc.getAction();
529 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
530 requestedApp.getUebKey());
531 if (domainRoleFunction != null
532 && (domainRoleFunction.getType() == null || domainRoleFunction.getAction() == null)) {
533 addIfTypeActionDoesNotExits(domainRoleFunction);
535 boolean isSave = true;
536 if (domainRoleFunction != null && domainRoleFunction.getCode().equals(roleFunc.getCode())
537 && domainRoleFunction.getType().equals(roleFunc.getType())
538 && domainRoleFunction.getAction().equals(roleFunc.getAction())) {
539 domainRoleFunction.setName(roleFunc.getName());
540 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(domainRoleFunction,
544 roleFunc.setAppId(requestedApp.getId());
545 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(roleFunc,
548 if (saveOrUpdateResponse) {
549 EPUser requestedUser = externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
550 EPApp app = externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
551 String activityCode = (isSave) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION
552 : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION;
553 logExterlaAuthRoleFunctionActivity(code, requestedUser, app, activityCode);
556 throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
558 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRoleFunction, Unauthorized user");
559 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
560 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
562 } catch (Exception e) {
563 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed", e);
564 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure");
566 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Saved Successfully!", "Success");
569 private void logExterlaAuthRoleFunctionActivity(String code, EPUser requestedUser, EPApp app, String activityCode) {
570 logger.info(EELFLoggerDelegate.applicationLogger, "saveRoleFunction: succeeded for app {}, function {}",
572 AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
573 auditLog.setComments(EcompPortalUtils.truncateString(
574 "saveRoleFunction role for app:" + app.getId() + " and function:'" + code + "'",
575 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
576 auditService.logActivity(auditLog, null);
577 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
578 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
579 EcompPortalUtils.calculateDateTimeDifferenceForLog(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
580 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
581 logger.info(EELFLoggerDelegate.auditLogger,
582 EPLogUtil.formatAuditLogMessage("RoleManageController.saveRoleFunction", activityCode,
583 String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(), code));
584 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
585 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
586 MDC.remove(SystemProperties.MDC_TIMER);
589 private void addIfTypeActionDoesNotExits(CentralV2RoleFunction domainRoleFunction) {
590 if (domainRoleFunction.getCode().contains(PIPE)) {
591 String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(domainRoleFunction.getCode());
592 String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(domainRoleFunction.getCode());
593 String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(domainRoleFunction.getCode());
594 domainRoleFunction.setType(newfunctionTypeFormat);
595 domainRoleFunction.setAction(newfunctionActionFormat);
596 domainRoleFunction.setCode(newfunctionCodeFormat);
598 String type = externalAccessRolesService.getFunctionCodeType(domainRoleFunction.getCode());
599 String action = externalAccessRolesService.getFunctionCodeAction(domainRoleFunction.getCode());
600 domainRoleFunction.setType(type);
601 domainRoleFunction.setAction(action);
605 @RequestMapping(value = { "/portalApi/role_function_list/removeRoleFunction/{appId}" }, method = RequestMethod.POST)
606 public PortalRestResponse<String> removeRoleFunction(HttpServletRequest request, HttpServletResponse response,
607 @RequestBody String roleFunc, @PathVariable("appId") Long appId) throws Exception {
608 EPUser user = EPUserUtils.getUserSession(request);
610 if (roleFunc!=null) {
611 SecureString secureString = new SecureString(roleFunc);
613 Validator validator = VALIDATOR_FACTORY.getValidator();
614 Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
616 if(!constraintViolations.isEmpty()){
617 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed");
618 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR");
623 EPApp requestedApp = appService.getApp(appId);
624 if (isAuthorizedUser(user, requestedApp)) {
625 fieldsValidation(requestedApp);
626 if (requestedApp.getCentralAuth()) {
627 ObjectMapper mapper = new ObjectMapper();
628 String data = roleFunc;
629 boolean getDelFuncResponse = false;
630 CentralV2RoleFunction availableRoleFunction = mapper.readValue(data, CentralV2RoleFunction.class);
631 String code = availableRoleFunction.getType() + PIPE + availableRoleFunction.getCode() + PIPE
632 + availableRoleFunction.getAction();
633 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
634 requestedApp.getUebKey());
635 getDelFuncResponse = externalAccessRolesService
636 .deleteCentralRoleFunction(domainRoleFunction.getCode(), requestedApp);
637 if (getDelFuncResponse) {
638 logger.info(EELFLoggerDelegate.applicationLogger,
639 "deleteRoleFunction: succeeded for app {}, role {}", requestedApp.getId(),
640 domainRoleFunction.getCode());
641 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION;
642 AuditLog auditLog = getAuditInfo(user, activityCode);
643 auditLog.setComments(
644 EcompPortalUtils.truncateString(
645 "Deleted function for app:" + requestedApp.getId() + " and function code:'"
646 + domainRoleFunction.getCode() + "'",
647 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
648 auditService.logActivity(auditLog, null);
649 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
650 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
651 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
652 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
653 EcompPortalUtils.calculateDateTimeDifferenceForLog(
654 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
655 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
656 logger.info(EELFLoggerDelegate.auditLogger,
657 EPLogUtil.formatAuditLogMessage("RoleManageController.removeRoleFunction",
658 EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION,
659 String.valueOf(user.getId()), user.getOrgUserId(),
660 domainRoleFunction.getCode()));
661 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
662 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
663 MDC.remove(SystemProperties.MDC_TIMER);
664 logger.info(EELFLoggerDelegate.auditLogger,
665 "Remove role function " + domainRoleFunction.getName());
668 throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
670 logger.info(EELFLoggerDelegate.auditLogger,
671 "RoleManageController.removeRoleFunction, Unauthorized user");
672 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
673 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
675 } catch (Exception e) {
676 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed", e);
677 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure");
679 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Deleted Successfully!", "Success");
682 @RequestMapping(value = { "/portalApi/centralizedApps" }, method = RequestMethod.GET)
683 public List<CentralizedApp> getCentralizedAppRoles(HttpServletRequest request, HttpServletResponse response, String userId) {
685 SecureString secureString = new SecureString(userId);
687 Validator validator = VALIDATOR_FACTORY.getValidator();
688 Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
690 if(!constraintViolations.isEmpty()){
691 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed");
696 EPUser user = EPUserUtils.getUserSession(request);
697 List<CentralizedApp> applicationsList = null;
698 if (adminRolesService.isAccountAdmin(user) || adminRolesService.isSuperAdmin(user)
699 || adminRolesService.isRoleAdmin(user)) {
700 applicationsList = externalAccessRolesService.getCentralizedAppsOfUser(userId);
702 logger.info(EELFLoggerDelegate.auditLogger,
703 "RoleManageController.getCentralizedAppRoles, Unauthorized user");
704 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
706 return applicationsList;
709 public RoleListController getRoleListController() {
710 return roleListController;
713 public void setRoleListController(RoleListController roleListController) {
714 this.roleListController = roleListController;
717 public RoleController getRoleController() {
718 return roleController;
721 public void setRoleController(RoleController roleController) {
722 this.roleController = roleController;
725 @RequestMapping(value = { "/portalApi/syncRoles" }, method = RequestMethod.POST, produces = "application/json")
726 public PortalRestResponse<String> syncRoles(HttpServletRequest request, HttpServletResponse response,
727 @RequestBody Long appId) {
728 EPUser user = EPUserUtils.getUserSession(request);
730 EPApp app = appService.getApp(appId);
731 if (isAuthorizedUser(user, app)) {
732 fieldsValidation(app);
733 externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
735 logger.info(EELFLoggerDelegate.auditLogger,
736 "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
737 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
738 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
740 } catch (Exception e) {
741 logger.error(EELFLoggerDelegate.errorLogger, "failed syncRoles", e);
742 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
744 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync roles completed successfully!", "Success");
747 @RequestMapping(value = { "/portalApi/syncFunctions" }, method = RequestMethod.POST, produces = "application/json")
748 public PortalRestResponse<String> syncFunctions(HttpServletRequest request, HttpServletResponse response,
749 @RequestBody Long appId) {
750 EPUser user = EPUserUtils.getUserSession(request);
752 EPApp app = appService.getApp(appId);
753 if (isAuthorizedUser(user, app)) {
754 fieldsValidation(app);
755 externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);
757 logger.info(EELFLoggerDelegate.auditLogger,
758 "RoleManageController.syncFunctions, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
759 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
760 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
762 } catch (Exception e) {
763 logger.error(EELFLoggerDelegate.errorLogger, "failed syncFunctions", e);
764 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
766 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync Functions completed successfully!", "Success");
769 public List<CentralV2Role> getAvailableChildRoles(String uebKey, Long roleId) throws Exception {
770 List<CentralV2Role> availableChildRoles = externalAccessRolesService.getRolesForApp(uebKey);
771 if (roleId == null || roleId == 0) {
772 return availableChildRoles;
774 CentralV2Role currentRole = externalAccessRolesService.getRoleInfo(roleId, uebKey);
775 Set<CentralV2Role> allParentRoles = new TreeSet<>();
776 allParentRoles = getAllParentRolesAsList(currentRole, allParentRoles);
777 Iterator<CentralV2Role> availableChildRolesIterator = availableChildRoles.iterator();
778 while (availableChildRolesIterator.hasNext()) {
779 CentralV2Role role = availableChildRolesIterator.next();
780 if (!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) {
781 availableChildRolesIterator.remove();
784 return availableChildRoles;
787 private Set<CentralV2Role> getAllParentRolesAsList(CentralV2Role role, Set<CentralV2Role> allParentRoles) {
788 Set<CentralV2Role> parentRoles = role.getParentRoles();
789 allParentRoles.addAll(parentRoles);
790 Iterator<CentralV2Role> parentRolesIterator = parentRoles.iterator();
791 while (parentRolesIterator.hasNext()) {
792 getAllParentRolesAsList(parentRolesIterator.next(), allParentRoles);
794 return allParentRoles;
797 public AuditLog getAuditInfo(EPUser user, String activityCode) {
798 AuditLog auditLog = new AuditLog();
799 auditLog.setUserId(user.getId());
800 auditLog.setActivityCode(activityCode);
801 auditLog.setAffectedRecordId(user.getOrgUserId());
806 private void fieldsValidation(EPApp app) throws Exception {
808 List<EPApp> appInfo = externalAccessRolesService.getApp(app.getUebKey());
809 if (appInfo.isEmpty()) {
810 throw new InvalidApplicationException("Invalid credentials");
812 if (!appInfo.isEmpty() && EcompPortalUtils.checkIfRemoteCentralAccessAllowed()
813 && appInfo.get(0).getCentralAuth()) {
814 ResponseEntity<String> response = externalAccessRolesService.getNameSpaceIfExists(appInfo.get(0));
815 if (response.getStatusCode().value() == HttpServletResponse.SC_NOT_FOUND)
816 throw new InvalidApplicationException("Invalid NameSpace");
820 private boolean isAuthorizedUser(EPUser user, EPApp requestedApp) {
821 if (user != null && (adminRolesService.isAccountAdminOfApplication(user, requestedApp)
822 || (adminRolesService.isSuperAdmin(user) && requestedApp.getId().equals(PortalConstants.PORTAL_APP_ID))))
827 private void SendErrorForUnauthorizedUser(HttpServletResponse response, EPUser user) throws IOException {
828 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
829 response.getWriter().write("Unauthorized User");
832 @RequestMapping(value = {
833 "/portalApi/uploadRoleFunction/{appId}" }, method = RequestMethod.POST, produces = "application/json")
834 public PortalRestResponse<String> bulkUploadRoleFunc(HttpServletRequest request, HttpServletResponse response,
835 @RequestBody UploadRoleFunctionExtSystem data, @PathVariable("appId") Long appId) {
836 EPUser user = EPUserUtils.getUserSession(request);
838 EPApp app = appService.getApp(appId);
839 if (isAuthorizedUser(user, app)) {
840 fieldsValidation(app);
841 externalAccessRolesService.bulkUploadRoleFunc(data, app);
842 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
843 String code = data.getName() + "," + data.getType() + PIPE + data.getInstance() + PIPE
845 logExterlaAuthRoleFunctionActivity(code, user, app, activityCode);
847 logger.info(EELFLoggerDelegate.auditLogger,
848 "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
849 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
850 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
852 } catch (Exception e) {
853 logger.error(EELFLoggerDelegate.errorLogger, "Failed bulkUploadRoleFunc!", e);
854 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
856 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Uploaded Role Function successfully!", "Success");