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.domain.RoleFunction;
82 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
83 import org.onap.portalsdk.core.service.AuditService;
84 import org.onap.portalsdk.core.util.SystemProperties;
85 import org.onap.portalsdk.core.web.support.JsonMessage;
87 import org.springframework.beans.factory.annotation.Autowired;
88 import org.springframework.context.annotation.EnableAspectJAutoProxy;
89 import org.springframework.http.ResponseEntity;
90 import org.springframework.web.bind.annotation.PathVariable;
91 import org.springframework.web.bind.annotation.RequestBody;
92 import org.springframework.web.bind.annotation.RequestMapping;
93 import org.springframework.web.bind.annotation.RequestMethod;
94 import org.springframework.web.bind.annotation.RestController;
95 import org.springframework.web.servlet.ModelAndView;
97 import com.fasterxml.jackson.databind.DeserializationFeature;
98 import com.fasterxml.jackson.databind.JsonNode;
99 import com.fasterxml.jackson.databind.ObjectMapper;
100 import com.fasterxml.jackson.databind.type.TypeFactory;
103 * Proxies REST calls to role-management functions that arrive on paths
104 * /portalApi/* over to controller methods provided by the SDK-Core library.
105 * Those controller methods are mounted on paths not exposed by the Portal FE.
108 @org.springframework.context.annotation.Configuration
109 @EnableAspectJAutoProxy
111 public class RoleManageController extends EPRestrictedBaseController {
112 private static final String PIPE = "|";
114 private static final String ROLE_INVALID_CHARS = "%=():,\"\"";
116 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleManageController.class);
119 private RoleController roleController;
122 private RoleListController roleListController;
125 private EPAppService appService;
128 private AuditService auditService;
131 private ExternalAccessRolesService externalAccessRolesService;
135 private AdminRolesService adminRolesService;
138 * Calls an SDK-Core library method that gets the available roles and writes
139 * them to the request object. Portal specifies a Hibernate mappings from
140 * the Role class to the fn_role_v view, which ensures that only Portal
141 * (app_id is null) roles are fetched.
143 * Any method declared void (no return value) or returning null causes the
144 * audit log aspect method to declare failure. TODO: should return a JSON
152 @RequestMapping(value = { "/portalApi/get_roles/{appId}" }, method = RequestMethod.GET)
153 public void getRoles(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId) throws Exception {
155 EPUser user = EPUserUtils.getUserSession(request);
156 EPApp requestedApp = appService.getApp(appId);
157 if (isAuthorizedUser(user, requestedApp)) {
158 fieldsValidation(requestedApp);
159 if (requestedApp.getCentralAuth()) {
160 List<CentralV2Role> answer = null;
161 Map<String, Object> model = new HashMap<>();
162 ObjectMapper mapper = new ObjectMapper();
163 answer = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey());
164 model.put("availableRoles", answer);
165 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
166 JSONObject j = new JSONObject(msg);
167 response.getWriter().write(j.toString());
169 throw new NonCentralizedAppException(requestedApp.getName());
171 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.getRoles, Unauthorized user");
172 SendErrorForUnauthorizedUser(response, user);
175 } catch (Exception e) {
176 logger.error(EELFLoggerDelegate.errorLogger, "getRoles failed", e);
182 @RequestMapping(value = { "/portalApi/role_list/toggleRole/{appId}/{roleId}" }, method = RequestMethod.POST)
183 public Map<String, Object> toggleRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
184 @PathVariable("roleId") Long roleId) throws Exception {
185 EPApp requestedApp = null;
186 String restcallStatus = null;
187 HashMap<String, Object> responseMap = new HashMap<>();
188 EPUser user = EPUserUtils.getUserSession(request);
190 requestedApp = appService.getApp(appId);
191 if (isAuthorizedUser(user, requestedApp)) {
192 fieldsValidation(requestedApp);
193 ObjectMapper mapper = new ObjectMapper();
194 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
195 CentralV2Role domainRole = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
196 // role. toggle active ind
197 boolean active = domainRole.isActive();
198 domainRole.setActive(!active);
200 String result = mapper.writeValueAsString(domainRole);
201 Role newRole = externalAccessRolesService.ConvertCentralRoleToRole(result);
202 ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService
203 .saveRoleForApplication(newRole, requestedApp.getUebKey());
204 boolean getAddResponse = externalRequestFieldsValidator.isResult();
205 if (getAddResponse) {
206 restcallStatus = "Success";
207 logger.info(EELFLoggerDelegate.auditLogger, "Toggle active status for role " + domainRole.getId());
209 restcallStatus = "Toggle Role Failed";
210 logger.info(EELFLoggerDelegate.auditLogger, "Toggle Role Failed " + domainRole.getId());
212 responseMap.put("restcallStatus", restcallStatus);
213 responseMap.put("availableRoles", externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()));
215 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.toggleRole, Unauthorized user");
216 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
217 responseMap.put("restcallStatus", " Unauthorized user");
219 } catch (Exception e) {
220 logger.error(EELFLoggerDelegate.errorLogger, "toggleRole failed", e);
226 @RequestMapping(value = { "/portalApi/role_list/removeRole/{appId}/{roleId}" }, method = RequestMethod.POST)
227 public Map<String, Object> removeRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
228 @PathVariable("roleId") Long roleId) throws Exception {
230 EPUser user = EPUserUtils.getUserSession(request);
231 EPApp requestedApp = null;
232 String restCallStatus = null;
233 HashMap<String, Object> responseMap = new HashMap<>();
234 ExternalRequestFieldsValidator externalRequestFieldsValidator = null;
236 requestedApp = appService.getApp(appId);
237 if (isAuthorizedUser(user, requestedApp)) {
238 fieldsValidation(requestedApp);
239 if (requestedApp.getCentralAuth()) {
240 externalRequestFieldsValidator = externalAccessRolesService.deleteDependencyRoleRecord(roleId,
241 requestedApp.getUebKey(), user.getOrgUserId());
242 boolean deleteResponse = externalRequestFieldsValidator.isResult();
243 if (deleteResponse) {
244 restCallStatus = "Success";
245 EPUser requestedUser = (EPUser) externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
246 EPApp app = (EPApp) externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
247 logger.info(EELFLoggerDelegate.applicationLogger, "deleteRole: succeeded for app {}, role {}",
248 app.getId(), roleId);
249 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE;
250 AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
251 auditLog.setComments(EcompPortalUtils.truncateString(
252 "Deleted role for app:" + app.getId() + " and role:'" + roleId + "'",
253 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
254 auditService.logActivity(auditLog, null);
255 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
256 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
257 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
258 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
259 EcompPortalUtils.calculateDateTimeDifferenceForLog(
260 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
261 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
262 logger.info(EELFLoggerDelegate.auditLogger,
263 EPLogUtil.formatAuditLogMessage("RoleManageController.removeRole",
264 EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE,
265 String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(),
267 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
268 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
269 MDC.remove(SystemProperties.MDC_TIMER);
271 restCallStatus = "Remove Role failed";
272 responseMap.put("error", externalRequestFieldsValidator.getDetailMessage());
273 logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed");
275 responseMap.put("restCallStatus", restCallStatus);
276 responseMap.put("availableRoles",
277 externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()));
279 throw new NonCentralizedAppException(requestedApp.getName());
281 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.removeRole, Unauthorized user");
282 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
283 responseMap.put("restCallStatus", " Unauthorized user");
285 } catch (Exception e) {
286 logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed", e);
292 @RequestMapping(value = { "/portalApi/role/saveRole/{appId}" }, method = RequestMethod.POST)
293 public Map<String, Object> saveRole(HttpServletRequest request, HttpServletResponse response,
294 @PathVariable("appId") Long appId) throws Exception {
295 EPUser user = EPUserUtils.getUserSession(request);
296 String responseString = null;
297 HashMap<String, Object> responseMap = new HashMap<>();
299 EPApp requestedApp = appService.getApp(appId);
300 if (isAuthorizedUser(user, requestedApp)) {
301 fieldsValidation(requestedApp);
302 if (requestedApp != null && requestedApp.getCentralAuth().equals(true)) {
303 ObjectMapper mapper = new ObjectMapper();
304 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
305 JsonNode root = mapper.readTree(request.getReader());
306 CentralV2Role role = mapper.readValue(root.get("role").toString(), CentralV2Role.class);
308 List<CentralV2Role> childRoles = mapper.readValue(root.get("childRoles").toString(),
309 TypeFactory.defaultInstance().constructCollectionType(List.class, CentralV2Role.class));
310 List<CentralV2RoleFunction> roleFunctions = mapper.readValue(root.get("roleFunctions").toString(),
311 TypeFactory.defaultInstance().constructCollectionType(List.class,
312 CentralV2RoleFunction.class));
313 if (role.getId() != null && StringUtils.containsAny(role.getName(), ROLE_INVALID_CHARS)) {
314 throw new InvalidRoleException("Invalid role name found for '" + role.getName()
315 + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
317 CentralV2Role domainRole;
318 if (role.getId() != null) {
319 domainRole = externalAccessRolesService.getRoleInfo(role.getId(), requestedApp.getUebKey());
320 domainRole.setName(role.getName());
321 domainRole.setPriority(role.getPriority());
323 // check for existing role of same name
324 List<CentralV2Role> roles = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey());
325 for (CentralV2Role existRole : roles)
326 if (existRole.getName().equalsIgnoreCase(role.getName()))
327 throw new DuplicateRecordException("Role already exists: " + existRole.getName());
329 domainRole = new CentralV2Role();
330 domainRole.setName(role.getName());
331 domainRole.setPriority(role.getPriority());
332 if (role.getChildRoles() != null && role.getChildRoles().size() > 0) {
333 for (Object childRole : childRoles) {
334 domainRole.addChildRole((CentralV2Role) childRole);
338 if (role.getRoleFunctions() != null && role.getRoleFunctions().size() > 0) {
339 domainRole.setRoleFunctions(new TreeSet<CentralV2RoleFunction>());
340 for (CentralV2RoleFunction roleFunction : roleFunctions) {
341 if (roleFunction.getType() == null && roleFunction.getAction() == null) {
342 throw new InvalidRoleException("Invalid role function type:" + roleFunction.getType()
343 + " and action: " + roleFunction.getAction() + " found while saving!");
345 roleFunction.setCode(externalAccessRolesService.encodeFunctionCode(roleFunction.getCode()));
346 roleFunction.setCode(roleFunction.getType() + PIPE + roleFunction.getCode() + PIPE
347 + roleFunction.getAction());
348 domainRole.addRoleFunction((CentralV2RoleFunction) roleFunction);
351 domainRole.setRoleFunctions(new TreeSet<>());
353 String result = mapper.writeValueAsString(domainRole);
354 Role newRole = externalAccessRolesService.ConvertCentralRoleToRole(result);
355 ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService
356 .saveRoleForApplication(newRole, requestedApp.getUebKey());
357 boolean getAddResponse = externalRequestFieldsValidator.isResult();
358 if (getAddResponse) {
359 String activityCode = (role.getId() == null) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_ROLE
360 : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
361 logger.info(EELFLoggerDelegate.applicationLogger, "saveRole: succeeded for app {}, role {}",
362 requestedApp.getId(), role.getName());
363 AuditLog auditLog = new AuditLog();
364 auditLog.setUserId(user.getId());
365 auditLog.setActivityCode(activityCode);
366 auditLog.setComments(EcompPortalUtils.truncateString(
367 "saveRole role for app:" + requestedApp.getId() + " and role:'" + role.getName() + "'",
368 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
369 auditLog.setAffectedRecordId(user.getOrgUserId());
370 auditService.logActivity(auditLog, null);
371 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
372 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
373 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
374 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
375 EcompPortalUtils.calculateDateTimeDifferenceForLog(
376 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
377 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
378 logger.info(EELFLoggerDelegate.auditLogger,
379 EPLogUtil.formatAuditLogMessage("RoleManageController.saveRole", activityCode,
380 String.valueOf(user.getId()), user.getOrgUserId(), role.getName()));
381 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
382 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
383 MDC.remove(SystemProperties.MDC_TIMER);
384 responseMap.put("status", "Success");
385 responseMap.put("role", domainRole);
387 if (externalRequestFieldsValidator.getDetailMessage().contains("406")) {
388 externalRequestFieldsValidator.setDetailMessage("Failed to save role for '" + role.getName()
389 + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
391 responseMap.put("status", "SaveRole Failed");
392 responseMap.put("role", responseString);
393 responseMap.put("error", externalRequestFieldsValidator.getDetailMessage());
394 logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed");
398 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRole, Unauthorized user");
399 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
400 responseMap.put("error", " Unauthorized user");
402 } catch (Exception e) {
403 logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e);
404 responseMap.put("error", e.getMessage());
409 @RequestMapping(value = { "/portalApi/role/removeRoleFunction" }, method = RequestMethod.POST)
410 public ModelAndView removeRoleRoleFunction(HttpServletRequest request, HttpServletResponse response)
412 return getRoleController().removeRoleFunction(request, response);
415 @RequestMapping(value = { "/portalApi/role/addRoleFunction" }, method = RequestMethod.POST)
416 public ModelAndView addRoleRoRoleFunction(HttpServletRequest request, HttpServletResponse response)
418 return getRoleController().addRoleFunction(request, response);
421 @RequestMapping(value = { "/portalApi/role/removeChildRole" }, method = RequestMethod.POST)
422 public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
423 return getRoleController().removeChildRole(request, response);
426 @RequestMapping(value = { "/portalApi/role/addChildRole" }, method = RequestMethod.POST)
427 public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
428 return getRoleController().addChildRole(request, response);
431 @RequestMapping(value = { "/portalApi/get_role/{appId}/{roleId}" }, method = RequestMethod.GET)
432 public void getRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
433 @PathVariable("roleId") Long roleId) throws Exception {
435 EPUser user = EPUserUtils.getUserSession(request);
436 ObjectMapper mapper = new ObjectMapper();
437 EPApp requestedApp = appService.getApp(appId);
438 if (isAuthorizedUser(user, requestedApp)) {
439 fieldsValidation(requestedApp);
440 if (requestedApp.getCentralAuth()) {
441 CentralV2Role answer = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
442 logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + roleId);
443 Map<String, Object> model = new HashMap<>();
444 model.put("availableRoleFunctions", mapper.writeValueAsString(
445 externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey())));
446 model.put("availableRoles",
447 mapper.writeValueAsString(getAvailableChildRoles(requestedApp.getUebKey(), roleId)));
448 model.put("role", mapper.writeValueAsString(answer));
449 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
450 JSONObject j = new JSONObject(msg);
451 response.getWriter().write(j.toString());
453 throw new NonCentralizedAppException(requestedApp.getName());
455 logger.info(EELFLoggerDelegate.auditLogger,
456 "RoleManageController.getRoleFunctionList, Unauthorized user");
457 SendErrorForUnauthorizedUser(response, user);
459 } catch (Exception e) {
460 logger.error(EELFLoggerDelegate.errorLogger, "getRole failed", e);
465 @RequestMapping(value = { "/portalApi/get_role_functions/{appId}" }, method = RequestMethod.GET)
466 public void getRoleFunctionList(HttpServletRequest request, HttpServletResponse response,
467 @PathVariable("appId") Long appId) throws Exception {
469 EPUser user = EPUserUtils.getUserSession(request);
470 EPApp requestedApp = appService.getApp(appId);
471 if (isAuthorizedUser(user, requestedApp)) {
472 fieldsValidation(requestedApp);
473 if (requestedApp.getCentralAuth()) {
474 List<CentralV2RoleFunction> answer = null;
475 Map<String, Object> model = new HashMap<>();
476 ObjectMapper mapper = new ObjectMapper();
477 answer = externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey());
478 model.put("availableRoleFunctions", answer);
479 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
480 JSONObject j = new JSONObject(msg);
481 response.getWriter().write(j.toString());
483 throw new NonCentralizedAppException(requestedApp.getName());
485 logger.info(EELFLoggerDelegate.auditLogger,
486 "RoleManageController.getRoleFunctionList, Unauthorized user");
487 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
488 response.getWriter().write("Unauthorized User");
490 } catch (Exception e) {
491 logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunctionList failed", e);
496 @RequestMapping(value = { "/portalApi/role_function_list/saveRoleFunction/{appId}" }, method = RequestMethod.POST)
497 public PortalRestResponse<String> saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @RequestBody CentralV2RoleFunction roleFunc,
498 @PathVariable("appId") Long appId) throws Exception {
499 EPUser user = EPUserUtils.getUserSession(request);
500 boolean saveOrUpdateResponse = false;
502 EPApp requestedApp = appService.getApp(appId);
503 if (isAuthorizedUser(user, requestedApp)) {
504 fieldsValidation(requestedApp);
505 if (requestedApp.getCentralAuth()) {
506 String code = roleFunc.getType()+PIPE+roleFunc.getCode()+PIPE+roleFunc.getAction();
507 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
508 requestedApp.getUebKey());
509 if(domainRoleFunction != null && (domainRoleFunction.getType() == null || domainRoleFunction.getAction() == null)) {
510 addIfTypeActionDoesNotExits(domainRoleFunction);
512 boolean isSave = true;
513 if (domainRoleFunction != null && domainRoleFunction.getCode().equals(roleFunc.getCode())
514 && domainRoleFunction.getType().equals(roleFunc.getType())
515 && domainRoleFunction.getAction().equals(roleFunc.getAction())) {
516 domainRoleFunction.setName(roleFunc.getName());
517 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(domainRoleFunction,
521 roleFunc.setAppId(requestedApp.getId());
522 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(roleFunc,
525 if (saveOrUpdateResponse) {
526 EPUser requestedUser = externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
527 EPApp app = externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
528 String activityCode = (isSave)
529 ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION
530 : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION;
531 logger.info(EELFLoggerDelegate.applicationLogger,
532 "saveRoleFunction: succeeded for app {}, function {}", app.getId(), code);
533 AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
534 auditLog.setComments(EcompPortalUtils.truncateString("saveRoleFunction role for app:"
535 + app.getId() + " and function:'" + code + "'",
536 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
537 auditService.logActivity(auditLog, null);
538 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
539 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
540 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
541 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
542 EcompPortalUtils.calculateDateTimeDifferenceForLog(
543 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
544 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
545 logger.info(EELFLoggerDelegate.auditLogger,
546 EPLogUtil.formatAuditLogMessage("RoleManageController.saveRoleFunction", activityCode,
547 String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(),
549 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
550 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
551 MDC.remove(SystemProperties.MDC_TIMER);
554 throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
556 logger.info(EELFLoggerDelegate.auditLogger,
557 "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");
570 private void addIfTypeActionDoesNotExits(CentralV2RoleFunction domainRoleFunction) {
571 if(domainRoleFunction.getCode().contains(PIPE)) {
572 String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(domainRoleFunction.getCode());
573 String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(domainRoleFunction.getCode());
574 String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(domainRoleFunction.getCode());
575 domainRoleFunction.setType(newfunctionTypeFormat);
576 domainRoleFunction.setAction(newfunctionActionFormat);
577 domainRoleFunction.setCode(newfunctionCodeFormat);
579 String type = externalAccessRolesService.getFunctionCodeType(domainRoleFunction.getCode());
580 String action = externalAccessRolesService.getFunctionCodeAction(domainRoleFunction.getCode());
581 domainRoleFunction.setType(type);
582 domainRoleFunction.setAction(action);
586 @RequestMapping(value = { "/portalApi/role_function_list/removeRoleFunction/{appId}" }, method = RequestMethod.POST)
587 public PortalRestResponse<String> removeRoleFunction(HttpServletRequest request, HttpServletResponse response,
588 @RequestBody String roleFunc, @PathVariable("appId") Long appId) throws Exception {
589 EPUser user = EPUserUtils.getUserSession(request);
591 EPApp requestedApp = appService.getApp(appId);
592 if (isAuthorizedUser(user, requestedApp)) {
593 fieldsValidation(requestedApp);
594 if (requestedApp.getCentralAuth()) {
595 ObjectMapper mapper = new ObjectMapper();
596 String data = roleFunc;
597 boolean getDelFuncResponse = false;
598 CentralV2RoleFunction availableRoleFunction = mapper.readValue(data, CentralV2RoleFunction.class);
599 String code = availableRoleFunction.getType() + PIPE + availableRoleFunction.getCode() + PIPE
600 + availableRoleFunction.getAction();
601 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
602 requestedApp.getUebKey());
603 getDelFuncResponse = externalAccessRolesService
604 .deleteCentralRoleFunction(domainRoleFunction.getCode(), requestedApp);
605 if (getDelFuncResponse) {
606 logger.info(EELFLoggerDelegate.applicationLogger,
607 "deleteRoleFunction: succeeded for app {}, role {}", requestedApp.getId(),
608 domainRoleFunction.getCode());
609 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION;
610 AuditLog auditLog = getAuditInfo(user, activityCode);
611 auditLog.setComments(
612 EcompPortalUtils.truncateString(
613 "Deleted function for app:" + requestedApp.getId() + " and function code:'"
614 + domainRoleFunction.getCode() + "'",
615 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
616 auditService.logActivity(auditLog, null);
617 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
618 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
619 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
620 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
621 EcompPortalUtils.calculateDateTimeDifferenceForLog(
622 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
623 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
624 logger.info(EELFLoggerDelegate.auditLogger,
625 EPLogUtil.formatAuditLogMessage("RoleManageController.removeRoleFunction",
626 EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION,
627 String.valueOf(user.getId()), user.getOrgUserId(),
628 domainRoleFunction.getCode()));
629 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
630 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
631 MDC.remove(SystemProperties.MDC_TIMER);
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 @RequestMapping(value = { "/portalApi/centralizedApps" }, method = RequestMethod.GET)
651 public List<CentralizedApp> getCentralizedAppRoles(HttpServletRequest request, HttpServletResponse response, String userId) throws IOException {
652 EPUser user = EPUserUtils.getUserSession(request);
653 List<CentralizedApp> applicationsList = null;
654 if (adminRolesService.isAccountAdmin(user) || adminRolesService.isSuperAdmin(user)) {
655 applicationsList = externalAccessRolesService.getCentralizedAppsOfUser(userId);
657 logger.info(EELFLoggerDelegate.auditLogger,
658 "RoleManageController.getCentralizedAppRoles, Unauthorized user");
659 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
661 return applicationsList;
664 public RoleListController getRoleListController() {
665 return roleListController;
668 public void setRoleListController(RoleListController roleListController) {
669 this.roleListController = roleListController;
672 public RoleController getRoleController() {
673 return roleController;
676 public void setRoleController(RoleController roleController) {
677 this.roleController = roleController;
681 @RequestMapping(value = { "/portalApi/syncRoles" }, method = RequestMethod.POST, produces = "application/json")
682 public PortalRestResponse<String> syncRoles(HttpServletRequest request, HttpServletResponse response,
683 @RequestBody Long appId) {
684 EPUser user = EPUserUtils.getUserSession(request);
686 EPApp app = appService.getApp(appId);
687 if (isAuthorizedUser(user, app)) {
688 fieldsValidation(app);
689 externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
691 logger.info(EELFLoggerDelegate.auditLogger,
692 "RoleManageController.syncRoles, Unauthorized user:" + user.getOrgUserId());
693 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
694 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
696 } catch (Exception e) {
697 logger.error(EELFLoggerDelegate.errorLogger, "failed syncRoles", e);
698 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
700 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync roles completed successfully!", "Success");
703 @RequestMapping(value = { "/portalApi/syncFunctions" }, method = RequestMethod.POST, produces = "application/json")
704 public PortalRestResponse<String> syncFunctions(HttpServletRequest request, HttpServletResponse response,
705 @RequestBody Long appId) {
706 EPUser user = EPUserUtils.getUserSession(request);
708 EPApp app = appService.getApp(appId);
709 if (isAuthorizedUser(user, app)) {
710 fieldsValidation(app);
711 externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);;
713 logger.info(EELFLoggerDelegate.auditLogger,
714 "RoleManageController.syncFunctions, Unauthorized user:" + user.getOrgUserId());
715 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
716 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
718 } catch (Exception e) {
719 logger.error(EELFLoggerDelegate.errorLogger, "failed syncFunctions", e);
720 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
722 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync Functions completed successfully!", "Success");
725 public List<CentralV2Role> getAvailableChildRoles(String uebKey, Long roleId) throws Exception {
726 List<CentralV2Role> availableChildRoles = externalAccessRolesService.getRolesForApp(uebKey);
727 if (roleId == null || roleId == 0) {
728 return availableChildRoles;
730 CentralV2Role currentRole = externalAccessRolesService.getRoleInfo(roleId, uebKey);
731 Set<CentralV2Role> allParentRoles = new TreeSet<>();
732 allParentRoles = getAllParentRolesAsList(currentRole, allParentRoles);
733 Iterator<CentralV2Role> availableChildRolesIterator = availableChildRoles.iterator();
734 while (availableChildRolesIterator.hasNext()) {
735 CentralV2Role role = availableChildRolesIterator.next();
736 if (!role.isActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) {
737 availableChildRolesIterator.remove();
740 return availableChildRoles;
743 private Set<CentralV2Role> getAllParentRolesAsList(CentralV2Role role, Set<CentralV2Role> allParentRoles) {
744 Set<CentralV2Role> parentRoles = role.getParentRoles();
745 allParentRoles.addAll(parentRoles);
746 Iterator<CentralV2Role> parentRolesIterator = parentRoles.iterator();
747 while (parentRolesIterator.hasNext()) {
748 getAllParentRolesAsList(parentRolesIterator.next(), allParentRoles);
750 return allParentRoles;
753 public AuditLog getAuditInfo(EPUser user, String activityCode)
755 AuditLog auditLog = new AuditLog();
756 auditLog.setUserId(user.getId());
757 auditLog.setActivityCode(activityCode);
758 auditLog.setAffectedRecordId(user.getOrgUserId());
763 private void fieldsValidation(EPApp app) throws Exception{
765 List<EPApp> appInfo = externalAccessRolesService.getApp(app.getUebKey());
766 if(appInfo.isEmpty()){
767 throw new InvalidApplicationException("Invalid uebkey");
769 if(!appInfo.isEmpty() && EcompPortalUtils.checkIfRemoteCentralAccessAllowed() && appInfo.get(0).getCentralAuth()){
770 ResponseEntity<String> response = externalAccessRolesService.getNameSpaceIfExists(appInfo.get(0));
771 if (response.getStatusCode().value() == HttpServletResponse.SC_NOT_FOUND)
772 throw new InvalidApplicationException("Invalid NameSpace");
776 private boolean isAuthorizedUser(EPUser user, EPApp requestedApp) {
777 if (user != null && (adminRolesService.isAccountAdminOfApplication(user, requestedApp)
778 || (adminRolesService.isSuperAdmin(user) && requestedApp.getId() == PortalConstants.PORTAL_APP_ID)))
783 private void SendErrorForUnauthorizedUser(HttpServletResponse response, EPUser user) throws IOException {
784 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
785 response.getWriter().write("Unauthorized User");