2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
8 * Unless otherwise specified, all software contained herein is licensed
9 * under the Apache License, Version 2.0 (the "License");
10 * you may not use this software except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * Unless otherwise specified, all documentation contained herein is licensed
22 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23 * you may not use this documentation except in compliance with the License.
24 * You may obtain a copy of the License at
26 * https://creativecommons.org/licenses/by/4.0/
28 * Unless required by applicable law or agreed to in writing, documentation
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
34 * ============LICENSE_END============================================
36 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
38 package org.onap.portalapp.portal.controller;
40 import java.io.IOException;
41 import java.util.HashMap;
42 import java.util.Iterator;
43 import java.util.List;
46 import java.util.TreeSet;
48 import javax.servlet.http.HttpServletRequest;
49 import javax.servlet.http.HttpServletResponse;
51 import org.apache.commons.lang.StringUtils;
52 import org.json.JSONObject;
53 import org.onap.portalapp.controller.EPRestrictedBaseController;
54 import org.onap.portalapp.controller.core.RoleController;
55 import org.onap.portalapp.controller.core.RoleListController;
56 import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
57 import org.onap.portalapp.portal.domain.CentralizedApp;
58 import org.onap.portalapp.portal.domain.EPApp;
59 import org.onap.portalapp.portal.domain.EPUser;
60 import org.onap.portalapp.portal.domain.EcompAuditLog;
61 import org.onap.portalapp.portal.ecomp.model.PortalRestResponse;
62 import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
63 import org.onap.portalapp.portal.exceptions.DuplicateRecordException;
64 import org.onap.portalapp.portal.exceptions.InvalidApplicationException;
65 import org.onap.portalapp.portal.exceptions.InvalidRoleException;
66 import org.onap.portalapp.portal.exceptions.NonCentralizedAppException;
67 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
68 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
69 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
70 import org.onap.portalapp.portal.service.AdminRolesService;
71 import org.onap.portalapp.portal.service.EPAppService;
72 import org.onap.portalapp.portal.service.ExternalAccessRolesService;
73 import org.onap.portalapp.portal.transport.CentralV2Role;
74 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
75 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
76 import org.onap.portalapp.portal.utils.EcompPortalUtils;
77 import org.onap.portalapp.portal.utils.PortalConstants;
78 import org.onap.portalapp.util.EPUserUtils;
79 import org.onap.portalsdk.core.domain.AuditLog;
80 import org.onap.portalsdk.core.domain.Role;
81 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
82 import org.onap.portalsdk.core.service.AuditService;
83 import org.onap.portalsdk.core.util.SystemProperties;
84 import org.onap.portalsdk.core.web.support.JsonMessage;
86 import org.springframework.beans.factory.annotation.Autowired;
87 import org.springframework.context.annotation.EnableAspectJAutoProxy;
88 import org.springframework.http.ResponseEntity;
89 import org.springframework.web.bind.annotation.PathVariable;
90 import org.springframework.web.bind.annotation.RequestBody;
91 import org.springframework.web.bind.annotation.RequestMapping;
92 import org.springframework.web.bind.annotation.RequestMethod;
93 import org.springframework.web.bind.annotation.RestController;
94 import org.springframework.web.servlet.ModelAndView;
96 import com.fasterxml.jackson.databind.DeserializationFeature;
97 import com.fasterxml.jackson.databind.JsonNode;
98 import com.fasterxml.jackson.databind.ObjectMapper;
99 import com.fasterxml.jackson.databind.type.TypeFactory;
102 * Proxies REST calls to role-management functions that arrive on paths
103 * /portalApi/* over to controller methods provided by the SDK-Core library.
104 * Those controller methods are mounted on paths not exposed by the Portal FE.
107 @org.springframework.context.annotation.Configuration
108 @EnableAspectJAutoProxy
110 public class RoleManageController extends EPRestrictedBaseController {
111 private static final String PIPE = "|";
113 private static final String ROLE_INVALID_CHARS = "%=():,\"\"";
115 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleManageController.class);
118 private RoleController roleController;
121 private RoleListController roleListController;
124 private EPAppService appService;
127 private AuditService auditService;
130 private ExternalAccessRolesService externalAccessRolesService;
134 private AdminRolesService adminRolesService;
137 * Calls an SDK-Core library method that gets the available roles and writes
138 * them to the request object. Portal specifies a Hibernate mappings from
139 * the Role class to the fn_role_v view, which ensures that only Portal
140 * (app_id is null) roles are fetched.
142 * Any method declared void (no return value) or returning null causes the
143 * audit log aspect method to declare failure. TODO: should return a JSON
151 @RequestMapping(value = { "/portalApi/get_roles/{appId}" }, method = RequestMethod.GET)
152 public void getRoles(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId) throws Exception {
154 EPUser user = EPUserUtils.getUserSession(request);
155 EPApp requestedApp = appService.getApp(appId);
156 if (isAuthorizedUser(user, requestedApp)) {
157 fieldsValidation(requestedApp);
158 if (requestedApp.getCentralAuth()) {
159 List<CentralV2Role> answer = null;
160 Map<String, Object> model = new HashMap<>();
161 ObjectMapper mapper = new ObjectMapper();
162 answer = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey());
163 model.put("availableRoles", answer);
164 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
165 JSONObject j = new JSONObject(msg);
166 response.getWriter().write(j.toString());
168 throw new NonCentralizedAppException(requestedApp.getName());
170 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.getRoles, Unauthorized user");
171 SendErrorForUnauthorizedUser(response, user);
174 } catch (Exception e) {
175 logger.error(EELFLoggerDelegate.errorLogger, "getRoles failed", e);
181 @RequestMapping(value = { "/portalApi/role_list/toggleRole/{appId}/{roleId}" }, method = RequestMethod.POST)
182 public Map<String, Object> toggleRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
183 @PathVariable("roleId") Long roleId) throws Exception {
184 EPApp requestedApp = null;
185 String restcallStatus = null;
186 HashMap<String, Object> responseMap = new HashMap<>();
187 EPUser user = EPUserUtils.getUserSession(request);
189 requestedApp = appService.getApp(appId);
190 if (isAuthorizedUser(user, requestedApp)) {
191 fieldsValidation(requestedApp);
192 ObjectMapper mapper = new ObjectMapper();
193 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
194 CentralV2Role domainRole = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
195 // role. toggle active ind
196 boolean active = domainRole.isActive();
197 domainRole.setActive(!active);
199 String result = mapper.writeValueAsString(domainRole);
200 Role newRole = externalAccessRolesService.ConvertCentralRoleToRole(result);
201 ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService
202 .saveRoleForApplication(newRole, requestedApp.getUebKey());
203 boolean getAddResponse = externalRequestFieldsValidator.isResult();
204 if (getAddResponse) {
205 restcallStatus = "Success";
206 logger.info(EELFLoggerDelegate.auditLogger, "Toggle active status for role " + domainRole.getId());
208 restcallStatus = "Toggle Role Failed";
209 logger.info(EELFLoggerDelegate.auditLogger, "Toggle Role Failed " + domainRole.getId());
211 responseMap.put("restcallStatus", restcallStatus);
212 responseMap.put("availableRoles", externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()));
214 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.toggleRole, Unauthorized user");
215 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
216 responseMap.put("restcallStatus", " Unauthorized user");
218 } catch (Exception e) {
219 logger.error(EELFLoggerDelegate.errorLogger, "toggleRole failed", e);
225 @RequestMapping(value = { "/portalApi/role_list/removeRole/{appId}/{roleId}" }, method = RequestMethod.POST)
226 public Map<String, Object> removeRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
227 @PathVariable("roleId") Long roleId) throws Exception {
229 EPUser user = EPUserUtils.getUserSession(request);
230 EPApp requestedApp = null;
231 String restCallStatus = null;
232 HashMap<String, Object> responseMap = new HashMap<>();
233 ExternalRequestFieldsValidator externalRequestFieldsValidator = null;
235 requestedApp = appService.getApp(appId);
236 if (isAuthorizedUser(user, requestedApp)) {
237 fieldsValidation(requestedApp);
238 if (requestedApp.getCentralAuth()) {
239 externalRequestFieldsValidator = externalAccessRolesService.deleteDependencyRoleRecord(roleId,
240 requestedApp.getUebKey(), user.getOrgUserId());
241 boolean deleteResponse = externalRequestFieldsValidator.isResult();
242 if (deleteResponse) {
243 restCallStatus = "Success";
244 EPUser requestedUser = (EPUser) externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
245 EPApp app = (EPApp) externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
246 logger.info(EELFLoggerDelegate.applicationLogger, "deleteRole: succeeded for app {}, role {}",
247 app.getId(), roleId);
248 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE;
249 AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
250 auditLog.setComments(EcompPortalUtils.truncateString(
251 "Deleted role for app:" + app.getId() + " and role:'" + roleId + "'",
252 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
253 auditService.logActivity(auditLog, null);
254 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
255 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
256 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
257 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
258 EcompPortalUtils.calculateDateTimeDifferenceForLog(
259 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
260 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
261 logger.info(EELFLoggerDelegate.auditLogger,
262 EPLogUtil.formatAuditLogMessage("RoleManageController.removeRole",
263 EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE,
264 String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(),
266 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
267 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
268 MDC.remove(SystemProperties.MDC_TIMER);
270 restCallStatus = "Remove Role failed";
271 responseMap.put("error", externalRequestFieldsValidator.getDetailMessage());
272 logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed");
274 responseMap.put("restCallStatus", restCallStatus);
275 responseMap.put("availableRoles",
276 externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()));
278 throw new NonCentralizedAppException(requestedApp.getName());
280 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.removeRole, Unauthorized user");
281 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
282 responseMap.put("restCallStatus", " Unauthorized user");
284 } catch (Exception e) {
285 logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed", e);
291 @RequestMapping(value = { "/portalApi/role/saveRole/{appId}" }, method = RequestMethod.POST)
292 public Map<String, Object> saveRole(HttpServletRequest request, HttpServletResponse response,
293 @PathVariable("appId") Long appId) throws Exception {
294 EPUser user = EPUserUtils.getUserSession(request);
295 String responseString = null;
296 HashMap<String, Object> responseMap = new HashMap<>();
298 EPApp requestedApp = appService.getApp(appId);
299 if (isAuthorizedUser(user, requestedApp)) {
300 fieldsValidation(requestedApp);
301 if (requestedApp != null && requestedApp.getCentralAuth().equals(true)) {
302 ObjectMapper mapper = new ObjectMapper();
303 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
304 JsonNode root = mapper.readTree(request.getReader());
305 CentralV2Role role = mapper.readValue(root.get("role").toString(), CentralV2Role.class);
307 List<CentralV2Role> childRoles = mapper.readValue(root.get("childRoles").toString(),
308 TypeFactory.defaultInstance().constructCollectionType(List.class, CentralV2Role.class));
309 List<CentralV2RoleFunction> roleFunctions = mapper.readValue(root.get("roleFunctions").toString(),
310 TypeFactory.defaultInstance().constructCollectionType(List.class,
311 CentralV2RoleFunction.class));
312 if (role.getId() != null && StringUtils.containsAny(role.getName(), ROLE_INVALID_CHARS)) {
313 throw new InvalidRoleException("Invalid role name found for '" + role.getName()
314 + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
316 CentralV2Role domainRole;
317 if (role.getId() != null) {
318 domainRole = externalAccessRolesService.getRoleInfo(role.getId(), requestedApp.getUebKey());
319 domainRole.setName(role.getName());
320 domainRole.setPriority(role.getPriority());
322 // check for existing role of same name
323 List<CentralV2Role> roles = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey());
324 for (CentralV2Role existRole : roles)
325 if (existRole.getName().equalsIgnoreCase(role.getName()))
326 throw new DuplicateRecordException("Role already exists: " + existRole.getName());
328 domainRole = new CentralV2Role();
329 domainRole.setName(role.getName());
330 domainRole.setPriority(role.getPriority());
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 roleFunction.setCode(externalAccessRolesService.encodeFunctionCode(roleFunction.getCode()));
345 roleFunction.setCode(roleFunction.getType() + PIPE + roleFunction.getCode() + PIPE
346 + roleFunction.getAction());
347 domainRole.addRoleFunction((CentralV2RoleFunction) roleFunction);
350 domainRole.setRoleFunctions(new TreeSet<>());
352 String result = mapper.writeValueAsString(domainRole);
353 Role newRole = externalAccessRolesService.ConvertCentralRoleToRole(result);
354 ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService
355 .saveRoleForApplication(newRole, requestedApp.getUebKey());
356 boolean getAddResponse = externalRequestFieldsValidator.isResult();
357 if (getAddResponse) {
358 String activityCode = (role.getId() == null) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_ROLE
359 : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
360 logger.info(EELFLoggerDelegate.applicationLogger, "saveRole: succeeded for app {}, role {}",
361 requestedApp.getId(), role.getName());
362 AuditLog auditLog = new AuditLog();
363 auditLog.setUserId(user.getId());
364 auditLog.setActivityCode(activityCode);
365 auditLog.setComments(EcompPortalUtils.truncateString(
366 "saveRole role for app:" + requestedApp.getId() + " and role:'" + role.getName() + "'",
367 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
368 auditLog.setAffectedRecordId(user.getOrgUserId());
369 auditService.logActivity(auditLog, null);
370 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
371 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
372 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
373 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
374 EcompPortalUtils.calculateDateTimeDifferenceForLog(
375 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
376 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
377 logger.info(EELFLoggerDelegate.auditLogger,
378 EPLogUtil.formatAuditLogMessage("RoleManageController.saveRole", activityCode,
379 String.valueOf(user.getId()), user.getOrgUserId(), role.getName()));
380 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
381 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
382 MDC.remove(SystemProperties.MDC_TIMER);
383 responseMap.put("status", "Success");
384 responseMap.put("role", domainRole);
386 if (externalRequestFieldsValidator.getDetailMessage().contains("406")) {
387 externalRequestFieldsValidator.setDetailMessage("Failed to save role for '" + role.getName()
388 + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
390 responseMap.put("status", "SaveRole Failed");
391 responseMap.put("role", responseString);
392 responseMap.put("error", externalRequestFieldsValidator.getDetailMessage());
393 logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed");
397 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRole, Unauthorized user");
398 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
399 responseMap.put("error", " Unauthorized user");
401 } catch (Exception e) {
402 logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e);
403 responseMap.put("error", e.getMessage());
408 @RequestMapping(value = { "/portalApi/role/removeRoleFunction" }, method = RequestMethod.POST)
409 public ModelAndView removeRoleRoleFunction(HttpServletRequest request, HttpServletResponse response)
411 return getRoleController().removeRoleFunction(request, response);
414 @RequestMapping(value = { "/portalApi/role/addRoleFunction" }, method = RequestMethod.POST)
415 public ModelAndView addRoleRoRoleFunction(HttpServletRequest request, HttpServletResponse response)
417 return getRoleController().addRoleFunction(request, response);
420 @RequestMapping(value = { "/portalApi/role/removeChildRole" }, method = RequestMethod.POST)
421 public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
422 return getRoleController().removeChildRole(request, response);
425 @RequestMapping(value = { "/portalApi/role/addChildRole" }, method = RequestMethod.POST)
426 public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
427 return getRoleController().addChildRole(request, response);
430 @RequestMapping(value = { "/portalApi/get_role/{appId}/{roleId}" }, method = RequestMethod.GET)
431 public void getRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
432 @PathVariable("roleId") Long roleId) throws Exception {
434 EPUser user = EPUserUtils.getUserSession(request);
435 ObjectMapper mapper = new ObjectMapper();
436 EPApp requestedApp = appService.getApp(appId);
437 if (isAuthorizedUser(user, requestedApp)) {
438 fieldsValidation(requestedApp);
439 if (requestedApp.getCentralAuth()) {
440 CentralV2Role answer = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
441 logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + roleId);
442 Map<String, Object> model = new HashMap<>();
443 model.put("availableRoleFunctions", mapper.writeValueAsString(
444 externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey())));
445 model.put("availableRoles",
446 mapper.writeValueAsString(getAvailableChildRoles(requestedApp.getUebKey(), roleId)));
447 model.put("role", mapper.writeValueAsString(answer));
448 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
449 JSONObject j = new JSONObject(msg);
450 response.getWriter().write(j.toString());
452 throw new NonCentralizedAppException(requestedApp.getName());
454 logger.info(EELFLoggerDelegate.auditLogger,
455 "RoleManageController.getRoleFunctionList, Unauthorized user");
456 SendErrorForUnauthorizedUser(response, user);
458 } catch (Exception e) {
459 logger.error(EELFLoggerDelegate.errorLogger, "getRole failed", e);
464 @RequestMapping(value = { "/portalApi/get_role_functions/{appId}" }, method = RequestMethod.GET)
465 public void getRoleFunctionList(HttpServletRequest request, HttpServletResponse response,
466 @PathVariable("appId") Long appId) throws Exception {
468 EPUser user = EPUserUtils.getUserSession(request);
469 EPApp requestedApp = appService.getApp(appId);
470 if (isAuthorizedUser(user, requestedApp)) {
471 fieldsValidation(requestedApp);
472 if (requestedApp.getCentralAuth()) {
473 List<CentralV2RoleFunction> answer = null;
474 Map<String, Object> model = new HashMap<>();
475 ObjectMapper mapper = new ObjectMapper();
476 answer = externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey());
477 model.put("availableRoleFunctions", answer);
478 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
479 JSONObject j = new JSONObject(msg);
480 response.getWriter().write(j.toString());
482 throw new NonCentralizedAppException(requestedApp.getName());
484 logger.info(EELFLoggerDelegate.auditLogger,
485 "RoleManageController.getRoleFunctionList, Unauthorized user");
486 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
487 response.getWriter().write("Unauthorized User");
489 } catch (Exception e) {
490 logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunctionList failed", e);
495 @RequestMapping(value = { "/portalApi/role_function_list/saveRoleFunction/{appId}" }, method = RequestMethod.POST)
496 public PortalRestResponse<String> saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @RequestBody CentralV2RoleFunction roleFunc,
497 @PathVariable("appId") Long appId) throws Exception {
498 EPUser user = EPUserUtils.getUserSession(request);
499 boolean saveOrUpdateResponse = false;
501 EPApp requestedApp = appService.getApp(appId);
502 if (isAuthorizedUser(user, requestedApp)) {
503 fieldsValidation(requestedApp);
504 if (requestedApp.getCentralAuth()) {
505 String code = roleFunc.getType()+PIPE+roleFunc.getCode()+PIPE+roleFunc.getAction();
506 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
507 requestedApp.getUebKey());
508 if(domainRoleFunction != null && (domainRoleFunction.getType() == null || domainRoleFunction.getAction() == null)) {
509 addIfTypeActionDoesNotExits(domainRoleFunction);
511 boolean isSave = true;
512 if (domainRoleFunction != null && domainRoleFunction.getCode().equals(roleFunc.getCode())
513 && domainRoleFunction.getType().equals(roleFunc.getType())
514 && domainRoleFunction.getAction().equals(roleFunc.getAction())) {
515 domainRoleFunction.setName(roleFunc.getName());
516 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(domainRoleFunction,
520 roleFunc.setAppId(requestedApp.getId());
521 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(roleFunc,
524 if (saveOrUpdateResponse) {
525 EPUser requestedUser = externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
526 EPApp app = externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
527 String activityCode = (isSave)
528 ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION
529 : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION;
530 logger.info(EELFLoggerDelegate.applicationLogger,
531 "saveRoleFunction: succeeded for app {}, function {}", app.getId(), code);
532 AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
533 auditLog.setComments(EcompPortalUtils.truncateString("saveRoleFunction role for app:"
534 + app.getId() + " and function:'" + code + "'",
535 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
536 auditService.logActivity(auditLog, null);
537 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
538 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
539 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
540 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
541 EcompPortalUtils.calculateDateTimeDifferenceForLog(
542 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
543 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
544 logger.info(EELFLoggerDelegate.auditLogger,
545 EPLogUtil.formatAuditLogMessage("RoleManageController.saveRoleFunction", activityCode,
546 String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(),
548 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
549 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
550 MDC.remove(SystemProperties.MDC_TIMER);
553 throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
555 logger.info(EELFLoggerDelegate.auditLogger,
556 "RoleManageController.saveRoleFunction, Unauthorized user");
557 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
558 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
560 } catch (Exception e) {
561 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed", e);
562 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure");
564 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Saved Successfully!", "Success");
569 private void addIfTypeActionDoesNotExits(CentralV2RoleFunction domainRoleFunction) {
570 if(domainRoleFunction.getCode().contains(PIPE)) {
571 String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(domainRoleFunction.getCode());
572 String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(domainRoleFunction.getCode());
573 String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(domainRoleFunction.getCode());
574 domainRoleFunction.setType(newfunctionTypeFormat);
575 domainRoleFunction.setAction(newfunctionActionFormat);
576 domainRoleFunction.setCode(newfunctionCodeFormat);
578 String type = externalAccessRolesService.getFunctionCodeType(domainRoleFunction.getCode());
579 String action = externalAccessRolesService.getFunctionCodeAction(domainRoleFunction.getCode());
580 domainRoleFunction.setType(type);
581 domainRoleFunction.setAction(action);
585 @RequestMapping(value = { "/portalApi/role_function_list/removeRoleFunction/{appId}" }, method = RequestMethod.POST)
586 public PortalRestResponse<String> removeRoleFunction(HttpServletRequest request, HttpServletResponse response,
587 @RequestBody String roleFunc, @PathVariable("appId") Long appId) throws Exception {
588 EPUser user = EPUserUtils.getUserSession(request);
590 EPApp requestedApp = appService.getApp(appId);
591 if (isAuthorizedUser(user, requestedApp)) {
592 fieldsValidation(requestedApp);
593 if (requestedApp.getCentralAuth()) {
594 ObjectMapper mapper = new ObjectMapper();
595 String data = roleFunc;
596 boolean getDelFuncResponse = false;
597 CentralV2RoleFunction availableRoleFunction = mapper.readValue(data, CentralV2RoleFunction.class);
598 String code = availableRoleFunction.getType() + PIPE + availableRoleFunction.getCode() + PIPE
599 + availableRoleFunction.getAction();
600 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
601 requestedApp.getUebKey());
602 getDelFuncResponse = externalAccessRolesService
603 .deleteCentralRoleFunction(domainRoleFunction.getCode(), requestedApp);
604 if (getDelFuncResponse) {
605 logger.info(EELFLoggerDelegate.applicationLogger,
606 "deleteRoleFunction: succeeded for app {}, role {}", requestedApp.getId(),
607 domainRoleFunction.getCode());
608 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION;
609 AuditLog auditLog = getAuditInfo(user, activityCode);
610 auditLog.setComments(
611 EcompPortalUtils.truncateString(
612 "Deleted function for app:" + requestedApp.getId() + " and function code:'"
613 + domainRoleFunction.getCode() + "'",
614 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
615 auditService.logActivity(auditLog, null);
616 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
617 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
618 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
619 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
620 EcompPortalUtils.calculateDateTimeDifferenceForLog(
621 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
622 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
623 logger.info(EELFLoggerDelegate.auditLogger,
624 EPLogUtil.formatAuditLogMessage("RoleManageController.removeRoleFunction",
625 EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION,
626 String.valueOf(user.getId()), user.getOrgUserId(),
627 domainRoleFunction.getCode()));
628 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
629 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
630 MDC.remove(SystemProperties.MDC_TIMER);
631 logger.info(EELFLoggerDelegate.auditLogger,
632 "Remove role function " + domainRoleFunction.getName());
635 throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
637 logger.info(EELFLoggerDelegate.auditLogger,
638 "RoleManageController.removeRoleFunction, Unauthorized user");
639 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
640 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
642 } catch (Exception e) {
643 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed", e);
644 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure");
646 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Deleted Successfully!", "Success");
649 @RequestMapping(value = { "/portalApi/centralizedApps" }, method = RequestMethod.GET)
650 public List<CentralizedApp> getCentralizedAppRoles(HttpServletRequest request, HttpServletResponse response, String userId) throws IOException {
651 EPUser user = EPUserUtils.getUserSession(request);
652 List<CentralizedApp> applicationsList = null;
653 if (adminRolesService.isAccountAdmin(user) || adminRolesService.isSuperAdmin(user)) {
654 applicationsList = externalAccessRolesService.getCentralizedAppsOfUser(userId);
656 logger.info(EELFLoggerDelegate.auditLogger,
657 "RoleManageController.getCentralizedAppRoles, Unauthorized user");
658 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
660 return applicationsList;
663 public RoleListController getRoleListController() {
664 return roleListController;
667 public void setRoleListController(RoleListController roleListController) {
668 this.roleListController = roleListController;
671 public RoleController getRoleController() {
672 return roleController;
675 public void setRoleController(RoleController roleController) {
676 this.roleController = roleController;
680 @RequestMapping(value = { "/portalApi/syncRoles" }, method = RequestMethod.POST, produces = "application/json")
681 public PortalRestResponse<String> syncRoles(HttpServletRequest request, HttpServletResponse response,
682 @RequestBody Long appId) {
683 EPUser user = EPUserUtils.getUserSession(request);
685 EPApp app = appService.getApp(appId);
686 if (isAuthorizedUser(user, app)) {
687 fieldsValidation(app);
688 externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
690 logger.info(EELFLoggerDelegate.auditLogger,
691 "RoleManageController.syncRoles, Unauthorized user:" + user.getOrgUserId());
692 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
693 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
695 } catch (Exception e) {
696 logger.error(EELFLoggerDelegate.errorLogger, "failed syncRoles", e);
697 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
699 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync roles completed successfully!", "Success");
702 @RequestMapping(value = { "/portalApi/syncFunctions" }, method = RequestMethod.POST, produces = "application/json")
703 public PortalRestResponse<String> syncFunctions(HttpServletRequest request, HttpServletResponse response,
704 @RequestBody Long appId) {
705 EPUser user = EPUserUtils.getUserSession(request);
707 EPApp app = appService.getApp(appId);
708 if (isAuthorizedUser(user, app)) {
709 fieldsValidation(app);
710 externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);;
712 logger.info(EELFLoggerDelegate.auditLogger,
713 "RoleManageController.syncFunctions, Unauthorized user:" + user.getOrgUserId());
714 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
715 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
717 } catch (Exception e) {
718 logger.error(EELFLoggerDelegate.errorLogger, "failed syncFunctions", e);
719 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
721 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync Functions completed successfully!", "Success");
724 public List<CentralV2Role> getAvailableChildRoles(String uebKey, Long roleId) throws Exception {
725 List<CentralV2Role> availableChildRoles = externalAccessRolesService.getRolesForApp(uebKey);
726 if (roleId == null || roleId == 0) {
727 return availableChildRoles;
729 CentralV2Role currentRole = externalAccessRolesService.getRoleInfo(roleId, uebKey);
730 Set<CentralV2Role> allParentRoles = new TreeSet<>();
731 allParentRoles = getAllParentRolesAsList(currentRole, allParentRoles);
732 Iterator<CentralV2Role> availableChildRolesIterator = availableChildRoles.iterator();
733 while (availableChildRolesIterator.hasNext()) {
734 CentralV2Role role = availableChildRolesIterator.next();
735 if (!role.isActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) {
736 availableChildRolesIterator.remove();
739 return availableChildRoles;
742 private Set<CentralV2Role> getAllParentRolesAsList(CentralV2Role role, Set<CentralV2Role> allParentRoles) {
743 Set<CentralV2Role> parentRoles = role.getParentRoles();
744 allParentRoles.addAll(parentRoles);
745 Iterator<CentralV2Role> parentRolesIterator = parentRoles.iterator();
746 while (parentRolesIterator.hasNext()) {
747 getAllParentRolesAsList(parentRolesIterator.next(), allParentRoles);
749 return allParentRoles;
752 public AuditLog getAuditInfo(EPUser user, String activityCode)
754 AuditLog auditLog = new AuditLog();
755 auditLog.setUserId(user.getId());
756 auditLog.setActivityCode(activityCode);
757 auditLog.setAffectedRecordId(user.getOrgUserId());
762 private void fieldsValidation(EPApp app) throws Exception{
764 List<EPApp> appInfo = externalAccessRolesService.getApp(app.getUebKey());
765 if(appInfo.isEmpty()){
766 throw new InvalidApplicationException("Invalid uebkey");
768 if(!appInfo.isEmpty() && EcompPortalUtils.checkIfRemoteCentralAccessAllowed() && appInfo.get(0).getCentralAuth()){
769 ResponseEntity<String> response = externalAccessRolesService.getNameSpaceIfExists(appInfo.get(0));
770 if (response.getStatusCode().value() == HttpServletResponse.SC_NOT_FOUND)
771 throw new InvalidApplicationException("Invalid NameSpace");
775 private boolean isAuthorizedUser(EPUser user, EPApp requestedApp) {
776 if (user != null && (adminRolesService.isAccountAdminOfApplication(user, requestedApp)
777 || (adminRolesService.isSuperAdmin(user) && requestedApp.getId() == PortalConstants.PORTAL_APP_ID)))
782 private void SendErrorForUnauthorizedUser(HttpServletResponse response, EPUser user) throws IOException {
783 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
784 response.getWriter().write("Unauthorized User");