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");
520 EPUser user = EPUserUtils.getUserSession(request);
521 boolean saveOrUpdateResponse = false;
523 EPApp requestedApp = appService.getApp(appId);
524 if (isAuthorizedUser(user, requestedApp)) {
525 fieldsValidation(requestedApp);
526 if (requestedApp.getCentralAuth()) {
527 String code = roleFunc.getType() + PIPE + roleFunc.getCode() + PIPE + roleFunc.getAction();
528 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
529 requestedApp.getUebKey());
530 if (domainRoleFunction != null
531 && (domainRoleFunction.getType() == null || domainRoleFunction.getAction() == null)) {
532 addIfTypeActionDoesNotExits(domainRoleFunction);
534 boolean isSave = true;
535 if (domainRoleFunction != null && domainRoleFunction.getCode().equals(roleFunc.getCode())
536 && domainRoleFunction.getType().equals(roleFunc.getType())
537 && domainRoleFunction.getAction().equals(roleFunc.getAction())) {
538 domainRoleFunction.setName(roleFunc.getName());
539 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(domainRoleFunction,
543 roleFunc.setAppId(requestedApp.getId());
544 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(roleFunc,
547 if (saveOrUpdateResponse) {
548 EPUser requestedUser = externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
549 EPApp app = externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
550 String activityCode = (isSave) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION
551 : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION;
552 logExterlaAuthRoleFunctionActivity(code, requestedUser, app, activityCode);
555 throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
557 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRoleFunction, Unauthorized user");
558 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
559 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
561 } catch (Exception e) {
562 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed", e);
563 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure");
565 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Saved Successfully!", "Success");
568 private void logExterlaAuthRoleFunctionActivity(String code, EPUser requestedUser, EPApp app, String activityCode) {
569 logger.info(EELFLoggerDelegate.applicationLogger, "saveRoleFunction: succeeded for app {}, function {}",
571 AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
572 auditLog.setComments(EcompPortalUtils.truncateString(
573 "saveRoleFunction role for app:" + app.getId() + " and function:'" + code + "'",
574 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
575 auditService.logActivity(auditLog, null);
576 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
577 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
578 EcompPortalUtils.calculateDateTimeDifferenceForLog(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
579 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
580 logger.info(EELFLoggerDelegate.auditLogger,
581 EPLogUtil.formatAuditLogMessage("RoleManageController.saveRoleFunction", activityCode,
582 String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(), code));
583 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
584 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
585 MDC.remove(SystemProperties.MDC_TIMER);
588 private void addIfTypeActionDoesNotExits(CentralV2RoleFunction domainRoleFunction) {
589 if (domainRoleFunction.getCode().contains(PIPE)) {
590 String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(domainRoleFunction.getCode());
591 String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(domainRoleFunction.getCode());
592 String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(domainRoleFunction.getCode());
593 domainRoleFunction.setType(newfunctionTypeFormat);
594 domainRoleFunction.setAction(newfunctionActionFormat);
595 domainRoleFunction.setCode(newfunctionCodeFormat);
597 String type = externalAccessRolesService.getFunctionCodeType(domainRoleFunction.getCode());
598 String action = externalAccessRolesService.getFunctionCodeAction(domainRoleFunction.getCode());
599 domainRoleFunction.setType(type);
600 domainRoleFunction.setAction(action);
604 @RequestMapping(value = { "/portalApi/role_function_list/removeRoleFunction/{appId}" }, method = RequestMethod.POST)
605 public PortalRestResponse<String> removeRoleFunction(HttpServletRequest request, HttpServletResponse response,
606 @RequestBody String roleFunc, @PathVariable("appId") Long appId) throws Exception {
607 EPUser user = EPUserUtils.getUserSession(request);
609 if (roleFunc!=null) {
610 SecureString secureString = new SecureString(roleFunc);
612 Validator validator = VALIDATOR_FACTORY.getValidator();
613 Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
615 if(!constraintViolations.isEmpty()){
616 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed");
617 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR");
622 EPApp requestedApp = appService.getApp(appId);
623 if (isAuthorizedUser(user, requestedApp)) {
624 fieldsValidation(requestedApp);
625 if (requestedApp.getCentralAuth()) {
626 ObjectMapper mapper = new ObjectMapper();
627 String data = roleFunc;
628 boolean getDelFuncResponse = false;
629 CentralV2RoleFunction availableRoleFunction = mapper.readValue(data, CentralV2RoleFunction.class);
630 String code = availableRoleFunction.getType() + PIPE + availableRoleFunction.getCode() + PIPE
631 + availableRoleFunction.getAction();
632 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
633 requestedApp.getUebKey());
634 getDelFuncResponse = externalAccessRolesService
635 .deleteCentralRoleFunction(domainRoleFunction.getCode(), requestedApp);
636 if (getDelFuncResponse) {
637 logger.info(EELFLoggerDelegate.applicationLogger,
638 "deleteRoleFunction: succeeded for app {}, role {}", requestedApp.getId(),
639 domainRoleFunction.getCode());
640 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION;
641 AuditLog auditLog = getAuditInfo(user, activityCode);
642 auditLog.setComments(
643 EcompPortalUtils.truncateString(
644 "Deleted function for app:" + requestedApp.getId() + " and function code:'"
645 + domainRoleFunction.getCode() + "'",
646 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
647 auditService.logActivity(auditLog, null);
648 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
649 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
650 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
651 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
652 EcompPortalUtils.calculateDateTimeDifferenceForLog(
653 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
654 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
655 logger.info(EELFLoggerDelegate.auditLogger,
656 EPLogUtil.formatAuditLogMessage("RoleManageController.removeRoleFunction",
657 EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION,
658 String.valueOf(user.getId()), user.getOrgUserId(),
659 domainRoleFunction.getCode()));
660 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
661 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
662 MDC.remove(SystemProperties.MDC_TIMER);
663 logger.info(EELFLoggerDelegate.auditLogger,
664 "Remove role function " + domainRoleFunction.getName());
667 throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
669 logger.info(EELFLoggerDelegate.auditLogger,
670 "RoleManageController.removeRoleFunction, Unauthorized user");
671 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
672 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
674 } catch (Exception e) {
675 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed", e);
676 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure");
678 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Deleted Successfully!", "Success");
681 @RequestMapping(value = { "/portalApi/centralizedApps" }, method = RequestMethod.GET)
682 public List<CentralizedApp> getCentralizedAppRoles(HttpServletRequest request, HttpServletResponse response, String userId) throws IOException {
684 SecureString secureString = new SecureString(userId);
686 Validator validator = VALIDATOR_FACTORY.getValidator();
687 Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
689 if(!constraintViolations.isEmpty()){
690 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed");
694 EPUser user = EPUserUtils.getUserSession(request);
695 List<CentralizedApp> applicationsList = null;
696 if (adminRolesService.isAccountAdmin(user) || adminRolesService.isSuperAdmin(user)
697 || adminRolesService.isRoleAdmin(user)) {
698 applicationsList = externalAccessRolesService.getCentralizedAppsOfUser(userId);
700 logger.info(EELFLoggerDelegate.auditLogger,
701 "RoleManageController.getCentralizedAppRoles, Unauthorized user");
702 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
704 return applicationsList;
707 public RoleListController getRoleListController() {
708 return roleListController;
711 public void setRoleListController(RoleListController roleListController) {
712 this.roleListController = roleListController;
715 public RoleController getRoleController() {
716 return roleController;
719 public void setRoleController(RoleController roleController) {
720 this.roleController = roleController;
723 @RequestMapping(value = { "/portalApi/syncRoles" }, method = RequestMethod.POST, produces = "application/json")
724 public PortalRestResponse<String> syncRoles(HttpServletRequest request, HttpServletResponse response,
725 @RequestBody Long appId) {
726 EPUser user = EPUserUtils.getUserSession(request);
728 EPApp app = appService.getApp(appId);
729 if (isAuthorizedUser(user, app)) {
730 fieldsValidation(app);
731 externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
733 logger.info(EELFLoggerDelegate.auditLogger,
734 "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
735 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
736 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
738 } catch (Exception e) {
739 logger.error(EELFLoggerDelegate.errorLogger, "failed syncRoles", e);
740 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
742 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync roles completed successfully!", "Success");
745 @RequestMapping(value = { "/portalApi/syncFunctions" }, method = RequestMethod.POST, produces = "application/json")
746 public PortalRestResponse<String> syncFunctions(HttpServletRequest request, HttpServletResponse response,
747 @RequestBody Long appId) {
748 EPUser user = EPUserUtils.getUserSession(request);
750 EPApp app = appService.getApp(appId);
751 if (isAuthorizedUser(user, app)) {
752 fieldsValidation(app);
753 externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);
755 logger.info(EELFLoggerDelegate.auditLogger,
756 "RoleManageController.syncFunctions, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
757 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
758 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
760 } catch (Exception e) {
761 logger.error(EELFLoggerDelegate.errorLogger, "failed syncFunctions", e);
762 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
764 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync Functions completed successfully!", "Success");
767 public List<CentralV2Role> getAvailableChildRoles(String uebKey, Long roleId) throws Exception {
768 List<CentralV2Role> availableChildRoles = externalAccessRolesService.getRolesForApp(uebKey);
769 if (roleId == null || roleId == 0) {
770 return availableChildRoles;
772 CentralV2Role currentRole = externalAccessRolesService.getRoleInfo(roleId, uebKey);
773 Set<CentralV2Role> allParentRoles = new TreeSet<>();
774 allParentRoles = getAllParentRolesAsList(currentRole, allParentRoles);
775 Iterator<CentralV2Role> availableChildRolesIterator = availableChildRoles.iterator();
776 while (availableChildRolesIterator.hasNext()) {
777 CentralV2Role role = availableChildRolesIterator.next();
778 if (!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) {
779 availableChildRolesIterator.remove();
782 return availableChildRoles;
785 private Set<CentralV2Role> getAllParentRolesAsList(CentralV2Role role, Set<CentralV2Role> allParentRoles) {
786 Set<CentralV2Role> parentRoles = role.getParentRoles();
787 allParentRoles.addAll(parentRoles);
788 Iterator<CentralV2Role> parentRolesIterator = parentRoles.iterator();
789 while (parentRolesIterator.hasNext()) {
790 getAllParentRolesAsList(parentRolesIterator.next(), allParentRoles);
792 return allParentRoles;
795 public AuditLog getAuditInfo(EPUser user, String activityCode) {
796 AuditLog auditLog = new AuditLog();
797 auditLog.setUserId(user.getId());
798 auditLog.setActivityCode(activityCode);
799 auditLog.setAffectedRecordId(user.getOrgUserId());
804 private void fieldsValidation(EPApp app) throws Exception {
806 List<EPApp> appInfo = externalAccessRolesService.getApp(app.getUebKey());
807 if (appInfo.isEmpty()) {
808 throw new InvalidApplicationException("Invalid credentials");
810 if (!appInfo.isEmpty() && EcompPortalUtils.checkIfRemoteCentralAccessAllowed()
811 && appInfo.get(0).getCentralAuth()) {
812 ResponseEntity<String> response = externalAccessRolesService.getNameSpaceIfExists(appInfo.get(0));
813 if (response.getStatusCode().value() == HttpServletResponse.SC_NOT_FOUND)
814 throw new InvalidApplicationException("Invalid NameSpace");
818 private boolean isAuthorizedUser(EPUser user, EPApp requestedApp) {
819 if (user != null && (adminRolesService.isAccountAdminOfApplication(user, requestedApp)
820 || (adminRolesService.isSuperAdmin(user) && requestedApp.getId() == PortalConstants.PORTAL_APP_ID)))
825 private void SendErrorForUnauthorizedUser(HttpServletResponse response, EPUser user) throws IOException {
826 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
827 response.getWriter().write("Unauthorized User");
830 @RequestMapping(value = {
831 "/portalApi/uploadRoleFunction/{appId}" }, method = RequestMethod.POST, produces = "application/json")
832 public PortalRestResponse<String> bulkUploadRoleFunc(HttpServletRequest request, HttpServletResponse response,
833 @RequestBody UploadRoleFunctionExtSystem data, @PathVariable("appId") Long appId) {
834 EPUser user = EPUserUtils.getUserSession(request);
836 EPApp app = appService.getApp(appId);
837 if (isAuthorizedUser(user, app)) {
838 fieldsValidation(app);
839 externalAccessRolesService.bulkUploadRoleFunc(data, app);
840 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
841 String code = data.getName() + "," + data.getType() + PIPE + data.getInstance() + PIPE
843 logExterlaAuthRoleFunctionActivity(code, user, app, activityCode);
845 logger.info(EELFLoggerDelegate.auditLogger,
846 "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
847 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
848 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
850 } catch (Exception e) {
851 logger.error(EELFLoggerDelegate.errorLogger, "Failed bulkUploadRoleFunc!", e);
852 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
854 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Uploaded Role Function successfully!", "Success");