2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
7 * Modifications Copyright (c) 2019 Samsung
8 * ===================================================================
9 * Modifications Copyright (c) 2020 IBM
10 * ===================================================================
12 * Unless otherwise specified, all software contained herein is licensed
13 * under the Apache License, Version 2.0 (the "License");
14 * you may not use this software except in compliance with the License.
15 * You may obtain a copy of the License at
17 * http://www.apache.org/licenses/LICENSE-2.0
19 * Unless required by applicable law or agreed to in writing, software
20 * distributed under the License is distributed on an "AS IS" BASIS,
21 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 * See the License for the specific language governing permissions and
23 * limitations under the License.
25 * Unless otherwise specified, all documentation contained herein is licensed
26 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
27 * you may not use this documentation except in compliance with the License.
28 * You may obtain a copy of the License at
30 * https://creativecommons.org/licenses/by/4.0/
32 * Unless required by applicable law or agreed to in writing, documentation
33 * distributed under the License is distributed on an "AS IS" BASIS,
34 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
35 * See the License for the specific language governing permissions and
36 * limitations under the License.
38 * ============LICENSE_END============================================
42 package org.onap.portalapp.portal.controller;
44 import java.io.IOException;
45 import java.util.HashMap;
46 import java.util.Iterator;
47 import java.util.List;
50 import java.util.TreeSet;
51 import javax.servlet.http.HttpServletRequest;
52 import javax.servlet.http.HttpServletResponse;
53 import javax.validation.ConstraintViolation;
54 import javax.validation.Valid;
55 import javax.validation.Validation;
56 import javax.validation.Validator;
57 import javax.validation.ValidatorFactory;
58 import org.apache.commons.lang.StringUtils;
59 import org.json.JSONObject;
60 import org.onap.portalapp.controller.EPRestrictedBaseController;
61 import org.onap.portalapp.controller.core.RoleController;
62 import org.onap.portalapp.controller.core.RoleListController;
63 import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
64 import org.onap.portalapp.portal.domain.CentralizedApp;
65 import org.onap.portalapp.portal.domain.EPApp;
66 import org.onap.portalapp.portal.domain.EPUser;
67 import org.onap.portalapp.portal.domain.EcompAuditLog;
68 import org.onap.portalapp.portal.ecomp.model.PortalRestResponse;
69 import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
70 import org.onap.portalapp.portal.ecomp.model.UploadRoleFunctionExtSystem;
71 import org.onap.portalapp.portal.exceptions.DuplicateRecordException;
72 import org.onap.portalapp.portal.exceptions.InvalidApplicationException;
73 import org.onap.portalapp.portal.exceptions.InvalidRoleException;
74 import org.onap.portalapp.portal.exceptions.NonCentralizedAppException;
75 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
76 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
77 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
78 import org.onap.portalapp.portal.service.AdminRolesService;
79 import org.onap.portalapp.portal.service.EPAppService;
80 import org.onap.portalapp.portal.service.ExternalAccessRolesService;
81 import org.onap.portalapp.portal.transport.CentralV2Role;
82 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
83 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
84 import org.onap.portalapp.portal.utils.EcompPortalUtils;
85 import org.onap.portalapp.portal.utils.PortalConstants;
86 import org.onap.portalapp.util.EPUserUtils;
87 import org.onap.portalapp.validation.SecureString;
88 import org.onap.portalsdk.core.domain.AuditLog;
89 import org.onap.portalsdk.core.domain.Role;
90 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
91 import org.onap.portalsdk.core.service.AuditService;
92 import org.onap.portalsdk.core.util.SystemProperties;
93 import org.onap.portalsdk.core.web.support.JsonMessage;
95 import org.springframework.beans.factory.annotation.Autowired;
96 import org.springframework.context.annotation.EnableAspectJAutoProxy;
97 import org.springframework.http.ResponseEntity;
98 import org.springframework.web.bind.annotation.PathVariable;
99 import org.springframework.web.bind.annotation.RequestBody;
100 import org.springframework.web.bind.annotation.PostMapping;
101 import org.springframework.web.bind.annotation.GetMapping;
102 import org.springframework.web.bind.annotation.RestController;
103 import org.springframework.web.servlet.ModelAndView;
104 import com.fasterxml.jackson.databind.DeserializationFeature;
105 import com.fasterxml.jackson.databind.JsonNode;
106 import com.fasterxml.jackson.databind.ObjectMapper;
107 import com.fasterxml.jackson.databind.type.TypeFactory;
110 * Proxies REST calls to role-management functions that arrive on paths
111 * /portalApi/* over to controller methods provided by the SDK-Core library.
112 * Those controller methods are mounted on paths not exposed by the Portal FE.
115 @org.springframework.context.annotation.Configuration
116 @EnableAspectJAutoProxy
118 public class RoleManageController extends EPRestrictedBaseController {
119 private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();
121 private static final String PIPE = "|";
123 private static final String ROLE_INVALID_CHARS = "%=():,\"\"";
125 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleManageController.class);
128 private RoleController roleController;
131 private RoleListController roleListController;
134 private EPAppService appService;
137 private AuditService auditService;
140 private ExternalAccessRolesService externalAccessRolesService;
143 private AdminRolesService adminRolesService;
146 * Calls an SDK-Core library method that gets the available roles and writes
147 * them to the request object. Portal specifies a Hibernate mappings from the
148 * Role class to the fn_role_v view, which ensures that only Portal (app_id is
149 * null) roles are fetched.
151 * Any method declared void (no return value) or returning null causes the audit
152 * log aspect method to declare failure. TODO: should return a JSON string.
159 @GetMapping(value = { "/portalApi/get_roles/{appId}" })
160 public void getRoles(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId)
163 EPUser user = EPUserUtils.getUserSession(request);
164 EPApp requestedApp = appService.getApp(appId);
165 if (isAuthorizedUser(user, requestedApp)) {
166 fieldsValidation(requestedApp);
167 if (requestedApp.getRolesInAAF()) {
168 List<CentralV2Role> answer = null;
169 Map<String, Object> model = new HashMap<>();
170 ObjectMapper mapper = new ObjectMapper();
171 answer = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey());
172 model.put("availableRoles", answer);
173 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
174 JSONObject j = new JSONObject(msg);
175 response.getWriter().write(j.toString());
177 throw new NonCentralizedAppException(requestedApp.getName());
179 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.getRoles, Unauthorized user");
180 SendErrorForUnauthorizedUser(response, user);
183 } catch (Exception e) {
184 logger.error(EELFLoggerDelegate.errorLogger, "getRoles failed", e);
188 @PostMapping(value = { "/portalApi/role_list/toggleRole/{appId}/{roleId}" })
189 public Map<String, Object> toggleRole(HttpServletRequest request, HttpServletResponse response,
190 @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception {
191 EPApp requestedApp = null;
192 String restcallStatus = null;
193 HashMap<String, Object> responseMap = new HashMap<>();
194 EPUser user = EPUserUtils.getUserSession(request);
196 requestedApp = appService.getApp(appId);
197 if (isAuthorizedUser(user, requestedApp)) {
198 fieldsValidation(requestedApp);
199 ObjectMapper mapper = new ObjectMapper();
200 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
201 CentralV2Role domainRole = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
202 // role. toggle active ind
203 boolean active = domainRole.getActive();
204 domainRole.setActive(!active);
206 String result = mapper.writeValueAsString(domainRole);
207 Role newRole = externalAccessRolesService.ConvertCentralRoleToRole(result);
208 ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService
209 .saveRoleForApplication(newRole, requestedApp.getUebKey());
210 boolean getAddResponse = externalRequestFieldsValidator.isResult();
211 if (getAddResponse) {
212 restcallStatus = "Success";
213 logger.info(EELFLoggerDelegate.auditLogger, "Toggle active status for role " + domainRole.getId());
215 restcallStatus = "Toggle Role Failed";
216 logger.info(EELFLoggerDelegate.auditLogger, "Toggle Role Failed " + domainRole.getId());
218 responseMap.put("restcallStatus", restcallStatus);
219 responseMap.put("availableRoles", externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()));
221 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.toggleRole, Unauthorized user");
222 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
223 responseMap.put("restcallStatus", " Unauthorized user");
225 } catch (Exception e) {
226 logger.error(EELFLoggerDelegate.errorLogger, "toggleRole failed", e);
232 @PostMapping(value = { "/portalApi/role_list/removeRole/{appId}/{roleId}" })
233 public Map<String, Object> removeRole(HttpServletRequest request, HttpServletResponse response,
234 @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception {
236 EPUser user = EPUserUtils.getUserSession(request);
237 EPApp requestedApp = null;
238 String restCallStatus = null;
239 HashMap<String, Object> responseMap = new HashMap<>();
240 ExternalRequestFieldsValidator externalRequestFieldsValidator = null;
242 requestedApp = appService.getApp(appId);
243 if (isAuthorizedUser(user, requestedApp)) {
244 fieldsValidation(requestedApp);
245 if (requestedApp.getRolesInAAF()) {
246 externalRequestFieldsValidator = externalAccessRolesService.deleteDependencyRoleRecord(roleId,
247 requestedApp.getUebKey(), user.getOrgUserId());
248 boolean deleteResponse = externalRequestFieldsValidator.isResult();
249 if (deleteResponse) {
250 restCallStatus = "Success";
251 EPUser requestedUser = (EPUser) externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
252 EPApp app = (EPApp) externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
253 logger.info(EELFLoggerDelegate.applicationLogger, "deleteRole: succeeded for app {}, role {}",
254 app.getId(), roleId);
255 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE;
256 AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
257 auditLog.setComments(EcompPortalUtils.truncateString(
258 "Deleted role for app:" + app.getId() + " and role:'" + roleId + "'",
259 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
260 auditService.logActivity(auditLog, null);
261 String auditMessageInfo = EPLogUtil.formatAuditLogMessage("RoleManageController.removeRole",
262 EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE,
263 String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(),
266 EPLogUtil.logAuditMessage(logger, auditMessageInfo);
269 restCallStatus = "Remove Role failed";
270 responseMap.put("error", externalRequestFieldsValidator.getDetailMessage());
271 logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed");
273 responseMap.put("restCallStatus", restCallStatus);
274 responseMap.put("availableRoles",
275 externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()));
277 throw new NonCentralizedAppException(requestedApp.getName());
279 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.removeRole, Unauthorized user");
280 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
281 responseMap.put("restCallStatus", " Unauthorized user");
283 } catch (Exception e) {
284 logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed", e);
290 @PostMapping(value = { "/portalApi/role/saveRole/{appId}" })
291 public Map<String, Object> saveRole(HttpServletRequest request, HttpServletResponse response,
292 @PathVariable("appId") Long appId) throws Exception {
293 EPUser user = EPUserUtils.getUserSession(request);
294 String responseString = null;
295 HashMap<String, Object> responseMap = new HashMap<>();
297 EPApp requestedApp = appService.getApp(appId);
298 if (isAuthorizedUser(user, requestedApp)) {
299 fieldsValidation(requestedApp);
300 if (requestedApp != null && requestedApp.getRolesInAAF().equals(true)) {
301 ObjectMapper mapper = new ObjectMapper();
302 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
303 JsonNode root = mapper.readTree(request.getReader());
304 CentralV2Role role = mapper.readValue(root.get("role").toString(), CentralV2Role.class);
306 List<CentralV2Role> childRoles = mapper.readValue(root.get("childRoles").toString(),
307 TypeFactory.defaultInstance().constructCollectionType(List.class, CentralV2Role.class));
308 List<CentralV2RoleFunction> roleFunctions = mapper.readValue(root.get("roleFunctions").toString(),
309 TypeFactory.defaultInstance().constructCollectionType(List.class,
310 CentralV2RoleFunction.class));
311 if (role.getId() != null && StringUtils.containsAny(role.getName(), ROLE_INVALID_CHARS)) {
312 throw new InvalidRoleException("Invalid role name found for '" + role.getName()
313 + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
315 CentralV2Role domainRole;
316 if (role.getId() != null) {
317 domainRole = externalAccessRolesService.getRoleInfo(role.getId(), requestedApp.getUebKey());
318 domainRole.setName(role.getName());
319 domainRole.setPriority(role.getPriority());
321 // check for existing role of same name
322 List<CentralV2Role> roles = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey());
323 for (CentralV2Role existRole : roles)
324 if (existRole.getName().equalsIgnoreCase(role.getName()))
325 throw new DuplicateRecordException("Role already exists: " + existRole.getName());
327 domainRole = new CentralV2Role.CentralV2RoleBuilder().createCentralV2Role();
328 domainRole.setName(role.getName());
329 domainRole.setPriority(role.getPriority());
330 domainRole.setActive(role.getActive());
331 if (role.getChildRoles() != null && role.getChildRoles().size() > 0) {
332 for (Object childRole : childRoles) {
333 domainRole.addChildRole((CentralV2Role) childRole);
337 if (role.getRoleFunctions() != null && role.getRoleFunctions().size() > 0) {
338 domainRole.setRoleFunctions(new TreeSet<CentralV2RoleFunction>());
339 for (CentralV2RoleFunction roleFunction : roleFunctions) {
340 if (roleFunction.getType() == null && roleFunction.getAction() == null) {
341 throw new InvalidRoleException("Invalid role function type:" + roleFunction.getType()
342 + " and action: " + roleFunction.getAction() + " found while saving!");
344 if (EcompPortalUtils.checkFunctionCodeHasEncodePattern(roleFunction.getCode()))
345 roleFunction.setCode(roleFunction.getType() + PIPE
346 + EcompPortalUtils.encodeFunctionCode(roleFunction.getCode()) + PIPE
347 + roleFunction.getAction());
349 roleFunction.setCode(roleFunction.getType() + PIPE + roleFunction.getCode() + PIPE
350 + roleFunction.getAction());
351 domainRole.addRoleFunction((CentralV2RoleFunction) roleFunction);
354 domainRole.setRoleFunctions(new TreeSet<>());
356 String result = mapper.writeValueAsString(domainRole);
357 Role newRole = externalAccessRolesService.ConvertCentralRoleToRole(result);
358 ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService
359 .saveRoleForApplication(newRole, requestedApp.getUebKey());
360 boolean getAddResponse = externalRequestFieldsValidator.isResult();
361 if (getAddResponse) {
362 String activityCode = (role.getId() == null) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_ROLE
363 : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
364 logger.info(EELFLoggerDelegate.applicationLogger, "saveRole: succeeded for app {}, role {}",
365 requestedApp.getId(), role.getName());
366 AuditLog auditLog = new AuditLog();
367 auditLog.setUserId(user.getId());
368 auditLog.setActivityCode(activityCode);
369 auditLog.setComments(EcompPortalUtils.truncateString(
370 "saveRole role for app:" + requestedApp.getId() + " and role:'" + role.getName() + "'",
371 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
372 auditLog.setAffectedRecordId(user.getOrgUserId());
373 auditService.logActivity(auditLog, null);
374 String auditMessageInfo = EPLogUtil.formatAuditLogMessage("RoleManageController.saveRole", activityCode,
375 String.valueOf(user.getId()), user.getOrgUserId(), role.getName());
377 EPLogUtil.logAuditMessage(logger, auditMessageInfo);
379 responseMap.put("status", "Success");
380 responseMap.put("role", domainRole);
382 if (externalRequestFieldsValidator.getDetailMessage().contains("406")) {
383 externalRequestFieldsValidator.setDetailMessage("Failed to save role for '" + role.getName()
384 + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
386 responseMap.put("status", "SaveRole Failed");
387 responseMap.put("role", responseString);
388 responseMap.put("error", externalRequestFieldsValidator.getDetailMessage());
389 logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed");
393 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRole, Unauthorized user");
394 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
395 responseMap.put("error", " Unauthorized user");
397 } catch (Exception e) {
398 logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e);
399 responseMap.put("error", e.getMessage());
404 @PostMapping(value = { "/portalApi/role/removeRoleFunction" })
405 public ModelAndView removeRoleRoleFunction(HttpServletRequest request, HttpServletResponse response)
407 return getRoleController().removeRoleFunction(request, response);
410 @PostMapping(value = { "/portalApi/role/addRoleFunction" })
411 public ModelAndView addRoleRoRoleFunction(HttpServletRequest request, HttpServletResponse response)
413 return getRoleController().addRoleFunction(request, response);
416 @PostMapping(value = { "/portalApi/role/removeChildRole" })
417 public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
418 return getRoleController().removeChildRole(request, response);
421 @PostMapping(value = { "/portalApi/role/addChildRole" })
422 public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
423 return getRoleController().addChildRole(request, response);
426 @GetMapping(value = { "/portalApi/get_role/{appId}/{roleId}" })
427 public void getRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
428 @PathVariable("roleId") Long roleId) throws Exception {
430 EPUser user = EPUserUtils.getUserSession(request);
431 ObjectMapper mapper = new ObjectMapper();
432 EPApp requestedApp = appService.getApp(appId);
433 if (isAuthorizedUser(user, requestedApp)) {
434 fieldsValidation(requestedApp);
435 if (requestedApp.getRolesInAAF()) {
436 CentralV2Role answer = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
437 logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + roleId);
438 Map<String, Object> model = new HashMap<>();
439 model.put("availableRoleFunctions", mapper
440 .writeValueAsString(externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey())));
441 model.put("availableRoles",
442 mapper.writeValueAsString(getAvailableChildRoles(requestedApp.getUebKey(), roleId)));
443 model.put("role", mapper.writeValueAsString(answer));
444 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
445 JSONObject j = new JSONObject(msg);
446 response.getWriter().write(j.toString());
448 throw new NonCentralizedAppException(requestedApp.getName());
450 logger.info(EELFLoggerDelegate.auditLogger,
451 "RoleManageController.getRoleFunctionList, Unauthorized user");
452 SendErrorForUnauthorizedUser(response, user);
454 } catch (Exception e) {
455 logger.error(EELFLoggerDelegate.errorLogger, "getRole failed", e);
460 @GetMapping(value = { "/portalApi/get_role_functions/{appId}" })
461 public void getRoleFunctionList(HttpServletRequest request, HttpServletResponse response,
462 @PathVariable("appId") Long appId) throws Exception {
464 EPUser user = EPUserUtils.getUserSession(request);
465 EPApp requestedApp = appService.getApp(appId);
466 if (isAuthorizedUser(user, requestedApp)) {
467 fieldsValidation(requestedApp);
468 if (requestedApp.getRolesInAAF()) {
469 List<CentralV2RoleFunction> answer = null;
470 Map<String, Object> model = new HashMap<>();
471 ObjectMapper mapper = new ObjectMapper();
472 answer = externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey());
473 model.put("availableRoleFunctions", answer);
474 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
475 JSONObject j = new JSONObject(msg);
476 response.getWriter().write(j.toString());
478 throw new NonCentralizedAppException(requestedApp.getName());
480 logger.info(EELFLoggerDelegate.auditLogger,
481 "RoleManageController.getRoleFunctionList, Unauthorized user");
482 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
483 response.getWriter().write("Unauthorized User");
485 } catch (Exception e) {
486 logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunctionList failed", e);
491 @PostMapping(value = { "/portalApi/role_function_list/saveRoleFunction/{appId}" })
492 public PortalRestResponse<String> saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @Valid @RequestBody CentralV2RoleFunction roleFunc,
493 @PathVariable("appId") Long appId) throws Exception {
494 if (roleFunc!=null) {
495 Validator validator = VALIDATOR_FACTORY.getValidator();
496 Set<ConstraintViolation<CentralV2RoleFunction>> constraintViolations = validator.validate(roleFunc);
498 if(!constraintViolations.isEmpty()){
499 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed");
500 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR");
504 EPUser user = EPUserUtils.getUserSession(request);
505 boolean saveOrUpdateResponse = false;
507 EPApp requestedApp = appService.getApp(appId);
508 if (isAuthorizedUser(user, requestedApp)) {
509 fieldsValidation(requestedApp);
510 if (requestedApp.getRolesInAAF() && roleFunc!=null) {
511 String code = roleFunc.getType() + PIPE + roleFunc.getCode() + PIPE + roleFunc.getAction();
512 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
513 requestedApp.getUebKey());
514 if (domainRoleFunction != null
515 && (domainRoleFunction.getType() == null || domainRoleFunction.getAction() == null)) {
516 addIfTypeActionDoesNotExits(domainRoleFunction);
518 boolean isSave = true;
519 if (domainRoleFunction != null && domainRoleFunction.getCode().equals(roleFunc.getCode())
520 && domainRoleFunction.getType().equals(roleFunc.getType())
521 && domainRoleFunction.getAction().equals(roleFunc.getAction())) {
522 domainRoleFunction.setName(roleFunc.getName());
523 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(domainRoleFunction,
527 roleFunc.setAppId(requestedApp.getId());
528 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(roleFunc,
531 if (saveOrUpdateResponse) {
532 EPUser requestedUser = externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
533 EPApp app = externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
534 String activityCode = (isSave) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION
535 : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION;
536 logExterlaAuthRoleFunctionActivity(code, requestedUser, app, activityCode);
539 throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
541 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRoleFunction, Unauthorized user");
542 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
543 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
545 } catch (Exception e) {
546 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed", e);
547 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure");
549 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Saved Successfully!", "Success");
552 private void logExterlaAuthRoleFunctionActivity(String code, EPUser requestedUser, EPApp app, String activityCode) {
553 logger.info(EELFLoggerDelegate.applicationLogger, "saveRoleFunction: succeeded for app {}, function {}",
555 AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
556 auditLog.setComments(EcompPortalUtils.truncateString(
557 "saveRoleFunction role for app:" + app.getId() + " and function:'" + code + "'",
558 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
559 auditService.logActivity(auditLog, null);
560 String auditMessageInfo = EPLogUtil.formatAuditLogMessage("RoleManageController.saveRoleFunction", activityCode,
561 String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(), code);
563 EPLogUtil.logAuditMessage(logger, auditMessageInfo);
566 private void addIfTypeActionDoesNotExits(CentralV2RoleFunction domainRoleFunction) {
567 if (domainRoleFunction.getCode().contains(PIPE)) {
568 String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(domainRoleFunction.getCode());
569 String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(domainRoleFunction.getCode());
570 String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(domainRoleFunction.getCode());
571 domainRoleFunction.setType(newfunctionTypeFormat);
572 domainRoleFunction.setAction(newfunctionActionFormat);
573 domainRoleFunction.setCode(newfunctionCodeFormat);
575 String type = externalAccessRolesService.getFunctionCodeType(domainRoleFunction.getCode());
576 String action = externalAccessRolesService.getFunctionCodeAction(domainRoleFunction.getCode());
577 domainRoleFunction.setType(type);
578 domainRoleFunction.setAction(action);
582 @PostMapping(value = { "/portalApi/role_function_list/removeRoleFunction/{appId}" })
583 public PortalRestResponse<String> removeRoleFunction(HttpServletRequest request, HttpServletResponse response,
584 @RequestBody String roleFunc, @PathVariable("appId") Long appId) throws Exception {
585 EPUser user = EPUserUtils.getUserSession(request);
587 if (roleFunc!=null) {
588 SecureString secureString = new SecureString(roleFunc);
590 Validator validator = VALIDATOR_FACTORY.getValidator();
591 Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
593 if(!constraintViolations.isEmpty()){
594 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed");
595 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR");
600 EPApp requestedApp = appService.getApp(appId);
601 if (isAuthorizedUser(user, requestedApp)) {
602 fieldsValidation(requestedApp);
603 if (requestedApp.getRolesInAAF()) {
604 ObjectMapper mapper = new ObjectMapper();
605 String data = roleFunc;
606 boolean getDelFuncResponse = false;
607 CentralV2RoleFunction availableRoleFunction = mapper.readValue(data, CentralV2RoleFunction.class);
608 String code = availableRoleFunction.getType() + PIPE + availableRoleFunction.getCode() + PIPE
609 + availableRoleFunction.getAction();
610 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
611 requestedApp.getUebKey());
612 getDelFuncResponse = externalAccessRolesService
613 .deleteCentralRoleFunction(domainRoleFunction.getCode(), requestedApp);
614 if (getDelFuncResponse) {
615 logger.info(EELFLoggerDelegate.applicationLogger,
616 "deleteRoleFunction: succeeded for app {}, role {}", requestedApp.getId(),
617 domainRoleFunction.getCode());
618 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION;
619 AuditLog auditLog = getAuditInfo(user, activityCode);
620 auditLog.setComments(
621 EcompPortalUtils.truncateString(
622 "Deleted function for app:" + requestedApp.getId() + " and function code:'"
623 + domainRoleFunction.getCode() + "'",
624 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
625 auditService.logActivity(auditLog, null);
626 String auditMessageInfo = EPLogUtil.formatAuditLogMessage("RoleManageController.removeRoleFunction",
627 EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION,
628 String.valueOf(user.getId()), user.getOrgUserId(),
629 domainRoleFunction.getCode());
631 EPLogUtil.logAuditMessage(logger, auditMessageInfo);
632 logger.info(EELFLoggerDelegate.auditLogger,
633 "Remove role function " + domainRoleFunction.getName());
636 throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
638 logger.info(EELFLoggerDelegate.auditLogger,
639 "RoleManageController.removeRoleFunction, Unauthorized user");
640 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
641 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
643 } catch (Exception e) {
644 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed", e);
645 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure");
647 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Deleted Successfully!", "Success");
650 @GetMapping(value = { "/portalApi/centralizedApps" })
651 public List<CentralizedApp> getCentralizedAppRoles(HttpServletRequest request, HttpServletResponse response, String userId) {
653 SecureString secureString = new SecureString(userId);
655 Validator validator = VALIDATOR_FACTORY.getValidator();
656 Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
658 if(!constraintViolations.isEmpty()){
659 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed");
664 EPUser user = EPUserUtils.getUserSession(request);
665 List<CentralizedApp> applicationsList = null;
666 if (adminRolesService.isAccountAdmin(user) || adminRolesService.isSuperAdmin(user)
667 || adminRolesService.isRoleAdmin(user)) {
668 applicationsList = externalAccessRolesService.getCentralizedAppsOfUser(userId);
670 logger.info(EELFLoggerDelegate.auditLogger,
671 "RoleManageController.getCentralizedAppRoles, Unauthorized user");
672 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
674 return applicationsList;
677 public RoleListController getRoleListController() {
678 return roleListController;
681 public void setRoleListController(RoleListController roleListController) {
682 this.roleListController = roleListController;
685 public RoleController getRoleController() {
686 return roleController;
689 public void setRoleController(RoleController roleController) {
690 this.roleController = roleController;
693 @PostMapping(value = { "/portalApi/syncRoles" }, produces = "application/json")
694 public PortalRestResponse<String> syncRoles(HttpServletRequest request, HttpServletResponse response,
695 @RequestBody Long appId) {
696 EPUser user = EPUserUtils.getUserSession(request);
698 EPApp app = appService.getApp(appId);
699 if (isAuthorizedUser(user, app)) {
700 fieldsValidation(app);
701 externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
703 logger.info(EELFLoggerDelegate.auditLogger,
704 "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
705 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
706 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
708 } catch (Exception e) {
709 logger.error(EELFLoggerDelegate.errorLogger, "failed syncRoles", e);
710 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
712 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync roles completed successfully!", "Success");
715 @PostMapping(value = { "/portalApi/syncFunctions" }, produces = "application/json")
716 public PortalRestResponse<String> syncFunctions(HttpServletRequest request, HttpServletResponse response,
717 @RequestBody Long appId) {
718 EPUser user = EPUserUtils.getUserSession(request);
720 EPApp app = appService.getApp(appId);
721 if (isAuthorizedUser(user, app)) {
722 fieldsValidation(app);
723 externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);
725 logger.info(EELFLoggerDelegate.auditLogger,
726 "RoleManageController.syncFunctions, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
727 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
728 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
730 } catch (Exception e) {
731 logger.error(EELFLoggerDelegate.errorLogger, "failed syncFunctions", e);
732 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
734 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync Functions completed successfully!", "Success");
737 public List<CentralV2Role> getAvailableChildRoles(String uebKey, Long roleId) throws Exception {
738 List<CentralV2Role> availableChildRoles = externalAccessRolesService.getRolesForApp(uebKey);
739 if (roleId == null || roleId == 0) {
740 return availableChildRoles;
742 CentralV2Role currentRole = externalAccessRolesService.getRoleInfo(roleId, uebKey);
743 Set<CentralV2Role> allParentRoles = new TreeSet<>();
744 allParentRoles = getAllParentRolesAsList(currentRole, allParentRoles);
745 Iterator<CentralV2Role> availableChildRolesIterator = availableChildRoles.iterator();
746 while (availableChildRolesIterator.hasNext()) {
747 CentralV2Role role = availableChildRolesIterator.next();
748 if (!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) {
749 availableChildRolesIterator.remove();
752 return availableChildRoles;
755 private Set<CentralV2Role> getAllParentRolesAsList(CentralV2Role role, Set<CentralV2Role> allParentRoles) {
756 Set<CentralV2Role> parentRoles = role.getParentRoles();
757 allParentRoles.addAll(parentRoles);
758 Iterator<CentralV2Role> parentRolesIterator = parentRoles.iterator();
759 while (parentRolesIterator.hasNext()) {
760 getAllParentRolesAsList(parentRolesIterator.next(), allParentRoles);
762 return allParentRoles;
765 public AuditLog getAuditInfo(EPUser user, String activityCode) {
766 AuditLog auditLog = new AuditLog();
767 auditLog.setUserId(user.getId());
768 auditLog.setActivityCode(activityCode);
769 auditLog.setAffectedRecordId(user.getOrgUserId());
774 private void fieldsValidation(EPApp app) throws Exception {
776 List<EPApp> appInfo = externalAccessRolesService.getApp(app.getUebKey());
777 if (appInfo.isEmpty()) {
778 throw new InvalidApplicationException("Invalid credentials");
780 if (!appInfo.isEmpty() && EcompPortalUtils.checkIfRemoteCentralAccessAllowed()
781 && appInfo.get(0).getRolesInAAF()) {
782 ResponseEntity<String> response = externalAccessRolesService.getNameSpaceIfExists(appInfo.get(0));
783 if (response.getStatusCode().value() == HttpServletResponse.SC_NOT_FOUND)
784 throw new InvalidApplicationException("Invalid NameSpace");
788 private boolean isAuthorizedUser(EPUser user, EPApp requestedApp) {
789 if (user != null && (adminRolesService.isAccountAdminOfApplication(user, requestedApp)
790 || (adminRolesService.isSuperAdmin(user) && requestedApp.getId().equals(PortalConstants.PORTAL_APP_ID))))
795 private void SendErrorForUnauthorizedUser(HttpServletResponse response, EPUser user) throws IOException {
796 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
797 response.getWriter().write("Unauthorized User");
800 @PostMapping(value = {
801 "/portalApi/uploadRoleFunction/{appId}" }, produces = "application/json")
802 public PortalRestResponse<String> bulkUploadRoleFunc(HttpServletRequest request, HttpServletResponse response,
803 @RequestBody UploadRoleFunctionExtSystem data, @PathVariable("appId") Long appId) {
804 EPUser user = EPUserUtils.getUserSession(request);
806 EPApp app = appService.getApp(appId);
807 if (isAuthorizedUser(user, app)) {
808 fieldsValidation(app);
809 externalAccessRolesService.bulkUploadRoleFunc(data, app);
810 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
811 String code = data.getName() + "," + data.getType() + PIPE + data.getInstance() + PIPE
813 logExterlaAuthRoleFunctionActivity(code, user, app, activityCode);
815 logger.info(EELFLoggerDelegate.auditLogger,
816 "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
817 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
818 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
820 } catch (Exception e) {
821 logger.error(EELFLoggerDelegate.errorLogger, "Failed bulkUploadRoleFunc!", e);
822 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
824 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Uploaded Role Function successfully!", "Success");