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============================================
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.ecomp.model.UploadRoleFunctionExtSystem;
64 import org.onap.portalapp.portal.exceptions.DuplicateRecordException;
65 import org.onap.portalapp.portal.exceptions.InvalidApplicationException;
66 import org.onap.portalapp.portal.exceptions.InvalidRoleException;
67 import org.onap.portalapp.portal.exceptions.NonCentralizedAppException;
68 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
69 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
70 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
71 import org.onap.portalapp.portal.service.AdminRolesService;
72 import org.onap.portalapp.portal.service.EPAppService;
73 import org.onap.portalapp.portal.service.ExternalAccessRolesService;
74 import org.onap.portalapp.portal.transport.CentralV2Role;
75 import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator;
76 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
77 import org.onap.portalapp.portal.utils.EcompPortalUtils;
78 import org.onap.portalapp.portal.utils.PortalConstants;
79 import org.onap.portalapp.util.EPUserUtils;
80 import org.onap.portalsdk.core.domain.AuditLog;
81 import org.onap.portalsdk.core.domain.Role;
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.getActive();
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 domainRole.setActive(role.getActive());
333 if (role.getChildRoles() != null && role.getChildRoles().size() > 0) {
334 for (Object childRole : childRoles) {
335 domainRole.addChildRole((CentralV2Role) childRole);
339 if (role.getRoleFunctions() != null && role.getRoleFunctions().size() > 0) {
340 domainRole.setRoleFunctions(new TreeSet<CentralV2RoleFunction>());
341 for (CentralV2RoleFunction roleFunction : roleFunctions) {
342 if (roleFunction.getType() == null && roleFunction.getAction() == null) {
343 throw new InvalidRoleException("Invalid role function type:" + roleFunction.getType()
344 + " and action: " + roleFunction.getAction() + " found while saving!");
346 roleFunction.setCode(externalAccessRolesService.encodeFunctionCode(roleFunction.getCode()));
347 roleFunction.setCode(roleFunction.getType() + PIPE + roleFunction.getCode() + PIPE
348 + roleFunction.getAction());
349 domainRole.addRoleFunction((CentralV2RoleFunction) roleFunction);
352 domainRole.setRoleFunctions(new TreeSet<>());
354 String result = mapper.writeValueAsString(domainRole);
355 Role newRole = externalAccessRolesService.ConvertCentralRoleToRole(result);
356 ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService
357 .saveRoleForApplication(newRole, requestedApp.getUebKey());
358 boolean getAddResponse = externalRequestFieldsValidator.isResult();
359 if (getAddResponse) {
360 String activityCode = (role.getId() == null) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_ROLE
361 : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
362 logger.info(EELFLoggerDelegate.applicationLogger, "saveRole: succeeded for app {}, role {}",
363 requestedApp.getId(), role.getName());
364 AuditLog auditLog = new AuditLog();
365 auditLog.setUserId(user.getId());
366 auditLog.setActivityCode(activityCode);
367 auditLog.setComments(EcompPortalUtils.truncateString(
368 "saveRole role for app:" + requestedApp.getId() + " and role:'" + role.getName() + "'",
369 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
370 auditLog.setAffectedRecordId(user.getOrgUserId());
371 auditService.logActivity(auditLog, null);
372 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
373 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
374 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
375 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
376 EcompPortalUtils.calculateDateTimeDifferenceForLog(
377 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
378 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
379 logger.info(EELFLoggerDelegate.auditLogger,
380 EPLogUtil.formatAuditLogMessage("RoleManageController.saveRole", activityCode,
381 String.valueOf(user.getId()), user.getOrgUserId(), role.getName()));
382 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
383 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
384 MDC.remove(SystemProperties.MDC_TIMER);
385 responseMap.put("status", "Success");
386 responseMap.put("role", domainRole);
388 if (externalRequestFieldsValidator.getDetailMessage().contains("406")) {
389 externalRequestFieldsValidator.setDetailMessage("Failed to save role for '" + role.getName()
390 + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
392 responseMap.put("status", "SaveRole Failed");
393 responseMap.put("role", responseString);
394 responseMap.put("error", externalRequestFieldsValidator.getDetailMessage());
395 logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed");
399 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRole, Unauthorized user");
400 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
401 responseMap.put("error", " Unauthorized user");
403 } catch (Exception e) {
404 logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e);
405 responseMap.put("error", e.getMessage());
410 @RequestMapping(value = { "/portalApi/role/removeRoleFunction" }, method = RequestMethod.POST)
411 public ModelAndView removeRoleRoleFunction(HttpServletRequest request, HttpServletResponse response)
413 return getRoleController().removeRoleFunction(request, response);
416 @RequestMapping(value = { "/portalApi/role/addRoleFunction" }, method = RequestMethod.POST)
417 public ModelAndView addRoleRoRoleFunction(HttpServletRequest request, HttpServletResponse response)
419 return getRoleController().addRoleFunction(request, response);
422 @RequestMapping(value = { "/portalApi/role/removeChildRole" }, method = RequestMethod.POST)
423 public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
424 return getRoleController().removeChildRole(request, response);
427 @RequestMapping(value = { "/portalApi/role/addChildRole" }, method = RequestMethod.POST)
428 public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
429 return getRoleController().addChildRole(request, response);
432 @RequestMapping(value = { "/portalApi/get_role/{appId}/{roleId}" }, method = RequestMethod.GET)
433 public void getRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
434 @PathVariable("roleId") Long roleId) throws Exception {
436 EPUser user = EPUserUtils.getUserSession(request);
437 ObjectMapper mapper = new ObjectMapper();
438 EPApp requestedApp = appService.getApp(appId);
439 if (isAuthorizedUser(user, requestedApp)) {
440 fieldsValidation(requestedApp);
441 if (requestedApp.getCentralAuth()) {
442 CentralV2Role answer = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
443 logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + roleId);
444 Map<String, Object> model = new HashMap<>();
445 model.put("availableRoleFunctions", mapper.writeValueAsString(
446 externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey())));
447 model.put("availableRoles",
448 mapper.writeValueAsString(getAvailableChildRoles(requestedApp.getUebKey(), roleId)));
449 model.put("role", mapper.writeValueAsString(answer));
450 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
451 JSONObject j = new JSONObject(msg);
452 response.getWriter().write(j.toString());
454 throw new NonCentralizedAppException(requestedApp.getName());
456 logger.info(EELFLoggerDelegate.auditLogger,
457 "RoleManageController.getRoleFunctionList, Unauthorized user");
458 SendErrorForUnauthorizedUser(response, user);
460 } catch (Exception e) {
461 logger.error(EELFLoggerDelegate.errorLogger, "getRole failed", e);
466 @RequestMapping(value = { "/portalApi/get_role_functions/{appId}" }, method = RequestMethod.GET)
467 public void getRoleFunctionList(HttpServletRequest request, HttpServletResponse response,
468 @PathVariable("appId") Long appId) throws Exception {
470 EPUser user = EPUserUtils.getUserSession(request);
471 EPApp requestedApp = appService.getApp(appId);
472 if (isAuthorizedUser(user, requestedApp)) {
473 fieldsValidation(requestedApp);
474 if (requestedApp.getCentralAuth()) {
475 List<CentralV2RoleFunction> answer = null;
476 Map<String, Object> model = new HashMap<>();
477 ObjectMapper mapper = new ObjectMapper();
478 answer = externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey());
479 model.put("availableRoleFunctions", answer);
480 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
481 JSONObject j = new JSONObject(msg);
482 response.getWriter().write(j.toString());
484 throw new NonCentralizedAppException(requestedApp.getName());
486 logger.info(EELFLoggerDelegate.auditLogger,
487 "RoleManageController.getRoleFunctionList, Unauthorized user");
488 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
489 response.getWriter().write("Unauthorized User");
491 } catch (Exception e) {
492 logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunctionList failed", e);
497 @RequestMapping(value = { "/portalApi/role_function_list/saveRoleFunction/{appId}" }, method = RequestMethod.POST)
498 public PortalRestResponse<String> saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @RequestBody CentralV2RoleFunction roleFunc,
499 @PathVariable("appId") Long appId) throws Exception {
500 EPUser user = EPUserUtils.getUserSession(request);
501 boolean saveOrUpdateResponse = false;
503 EPApp requestedApp = appService.getApp(appId);
504 if (isAuthorizedUser(user, requestedApp)) {
505 fieldsValidation(requestedApp);
506 if (requestedApp.getCentralAuth()) {
507 String code = roleFunc.getType()+PIPE+roleFunc.getCode()+PIPE+roleFunc.getAction();
508 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
509 requestedApp.getUebKey());
510 if(domainRoleFunction != null && (domainRoleFunction.getType() == null || domainRoleFunction.getAction() == null)) {
511 addIfTypeActionDoesNotExits(domainRoleFunction);
513 boolean isSave = true;
514 if (domainRoleFunction != null && domainRoleFunction.getCode().equals(roleFunc.getCode())
515 && domainRoleFunction.getType().equals(roleFunc.getType())
516 && domainRoleFunction.getAction().equals(roleFunc.getAction())) {
517 domainRoleFunction.setName(roleFunc.getName());
518 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(domainRoleFunction,
522 roleFunc.setAppId(requestedApp.getId());
523 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(roleFunc,
526 if (saveOrUpdateResponse) {
527 EPUser requestedUser = externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
528 EPApp app = externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
529 String activityCode = (isSave)
530 ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION
531 : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION;
532 logExterlaAuthRoleFunctionActivity(code, requestedUser, app, activityCode);
535 throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
537 logger.info(EELFLoggerDelegate.auditLogger,
538 "RoleManageController.saveRoleFunction, Unauthorized user");
539 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
540 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
542 } catch (Exception e) {
543 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed", e);
544 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure");
546 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Saved Successfully!", "Success");
549 private void logExterlaAuthRoleFunctionActivity(String code, EPUser requestedUser, EPApp app, String activityCode) {
550 logger.info(EELFLoggerDelegate.applicationLogger,
551 "saveRoleFunction: succeeded for app {}, function {}", app.getId(), code);
552 AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
553 auditLog.setComments(EcompPortalUtils.truncateString("saveRoleFunction role for app:"
554 + app.getId() + " and function:'" + code + "'",
555 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
556 auditService.logActivity(auditLog, null);
557 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
558 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
559 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
560 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
561 EcompPortalUtils.calculateDateTimeDifferenceForLog(
562 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
563 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
564 logger.info(EELFLoggerDelegate.auditLogger,
565 EPLogUtil.formatAuditLogMessage("RoleManageController.saveRoleFunction", activityCode,
566 String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(),
568 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
569 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
570 MDC.remove(SystemProperties.MDC_TIMER);
575 private void addIfTypeActionDoesNotExits(CentralV2RoleFunction domainRoleFunction) {
576 if(domainRoleFunction.getCode().contains(PIPE)) {
577 String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(domainRoleFunction.getCode());
578 String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(domainRoleFunction.getCode());
579 String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(domainRoleFunction.getCode());
580 domainRoleFunction.setType(newfunctionTypeFormat);
581 domainRoleFunction.setAction(newfunctionActionFormat);
582 domainRoleFunction.setCode(newfunctionCodeFormat);
584 String type = externalAccessRolesService.getFunctionCodeType(domainRoleFunction.getCode());
585 String action = externalAccessRolesService.getFunctionCodeAction(domainRoleFunction.getCode());
586 domainRoleFunction.setType(type);
587 domainRoleFunction.setAction(action);
591 @RequestMapping(value = { "/portalApi/role_function_list/removeRoleFunction/{appId}" }, method = RequestMethod.POST)
592 public PortalRestResponse<String> removeRoleFunction(HttpServletRequest request, HttpServletResponse response,
593 @RequestBody String roleFunc, @PathVariable("appId") Long appId) throws Exception {
594 EPUser user = EPUserUtils.getUserSession(request);
596 EPApp requestedApp = appService.getApp(appId);
597 if (isAuthorizedUser(user, requestedApp)) {
598 fieldsValidation(requestedApp);
599 if (requestedApp.getCentralAuth()) {
600 ObjectMapper mapper = new ObjectMapper();
601 String data = roleFunc;
602 boolean getDelFuncResponse = false;
603 CentralV2RoleFunction availableRoleFunction = mapper.readValue(data, CentralV2RoleFunction.class);
604 String code = availableRoleFunction.getType() + PIPE + availableRoleFunction.getCode() + PIPE
605 + availableRoleFunction.getAction();
606 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
607 requestedApp.getUebKey());
608 getDelFuncResponse = externalAccessRolesService
609 .deleteCentralRoleFunction(domainRoleFunction.getCode(), requestedApp);
610 if (getDelFuncResponse) {
611 logger.info(EELFLoggerDelegate.applicationLogger,
612 "deleteRoleFunction: succeeded for app {}, role {}", requestedApp.getId(),
613 domainRoleFunction.getCode());
614 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION;
615 AuditLog auditLog = getAuditInfo(user, activityCode);
616 auditLog.setComments(
617 EcompPortalUtils.truncateString(
618 "Deleted function for app:" + requestedApp.getId() + " and function code:'"
619 + domainRoleFunction.getCode() + "'",
620 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
621 auditService.logActivity(auditLog, null);
622 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
623 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
624 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
625 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
626 EcompPortalUtils.calculateDateTimeDifferenceForLog(
627 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
628 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
629 logger.info(EELFLoggerDelegate.auditLogger,
630 EPLogUtil.formatAuditLogMessage("RoleManageController.removeRoleFunction",
631 EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION,
632 String.valueOf(user.getId()), user.getOrgUserId(),
633 domainRoleFunction.getCode()));
634 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
635 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
636 MDC.remove(SystemProperties.MDC_TIMER);
637 logger.info(EELFLoggerDelegate.auditLogger,
638 "Remove role function " + domainRoleFunction.getName());
641 throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
643 logger.info(EELFLoggerDelegate.auditLogger,
644 "RoleManageController.removeRoleFunction, Unauthorized user");
645 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
646 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
648 } catch (Exception e) {
649 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed", e);
650 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure");
652 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Deleted Successfully!", "Success");
655 @RequestMapping(value = { "/portalApi/centralizedApps" }, method = RequestMethod.GET)
656 public List<CentralizedApp> getCentralizedAppRoles(HttpServletRequest request, HttpServletResponse response, String userId) throws IOException {
657 EPUser user = EPUserUtils.getUserSession(request);
658 List<CentralizedApp> applicationsList = null;
659 if (adminRolesService.isAccountAdmin(user) || adminRolesService.isSuperAdmin(user) || adminRolesService.isRoleAdmin(user)) {
660 applicationsList = externalAccessRolesService.getCentralizedAppsOfUser(userId);
662 logger.info(EELFLoggerDelegate.auditLogger,
663 "RoleManageController.getCentralizedAppRoles, Unauthorized user");
664 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
666 return applicationsList;
669 public RoleListController getRoleListController() {
670 return roleListController;
673 public void setRoleListController(RoleListController roleListController) {
674 this.roleListController = roleListController;
677 public RoleController getRoleController() {
678 return roleController;
681 public void setRoleController(RoleController roleController) {
682 this.roleController = roleController;
686 @RequestMapping(value = { "/portalApi/syncRoles" }, method = RequestMethod.POST, produces = "application/json")
687 public PortalRestResponse<String> syncRoles(HttpServletRequest request, HttpServletResponse response,
688 @RequestBody Long appId) {
689 EPUser user = EPUserUtils.getUserSession(request);
691 EPApp app = appService.getApp(appId);
692 if (isAuthorizedUser(user, app)) {
693 fieldsValidation(app);
694 externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
696 logger.info(EELFLoggerDelegate.auditLogger,
697 "RoleManageController.syncRoles, Unauthorized user:" + user.getOrgUserId());
698 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
699 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
701 } catch (Exception e) {
702 logger.error(EELFLoggerDelegate.errorLogger, "failed syncRoles", e);
703 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
705 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync roles completed successfully!", "Success");
708 @RequestMapping(value = { "/portalApi/syncFunctions" }, method = RequestMethod.POST, produces = "application/json")
709 public PortalRestResponse<String> syncFunctions(HttpServletRequest request, HttpServletResponse response,
710 @RequestBody Long appId) {
711 EPUser user = EPUserUtils.getUserSession(request);
713 EPApp app = appService.getApp(appId);
714 if (isAuthorizedUser(user, app)) {
715 fieldsValidation(app);
716 externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);;
718 logger.info(EELFLoggerDelegate.auditLogger,
719 "RoleManageController.syncFunctions, Unauthorized user:" + user.getOrgUserId());
720 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
721 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
723 } catch (Exception e) {
724 logger.error(EELFLoggerDelegate.errorLogger, "failed syncFunctions", e);
725 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
727 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync Functions completed successfully!", "Success");
730 public List<CentralV2Role> getAvailableChildRoles(String uebKey, Long roleId) throws Exception {
731 List<CentralV2Role> availableChildRoles = externalAccessRolesService.getRolesForApp(uebKey);
732 if (roleId == null || roleId == 0) {
733 return availableChildRoles;
735 CentralV2Role currentRole = externalAccessRolesService.getRoleInfo(roleId, uebKey);
736 Set<CentralV2Role> allParentRoles = new TreeSet<>();
737 allParentRoles = getAllParentRolesAsList(currentRole, allParentRoles);
738 Iterator<CentralV2Role> availableChildRolesIterator = availableChildRoles.iterator();
739 while (availableChildRolesIterator.hasNext()) {
740 CentralV2Role role = availableChildRolesIterator.next();
741 if (!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) {
742 availableChildRolesIterator.remove();
745 return availableChildRoles;
748 private Set<CentralV2Role> getAllParentRolesAsList(CentralV2Role role, Set<CentralV2Role> allParentRoles) {
749 Set<CentralV2Role> parentRoles = role.getParentRoles();
750 allParentRoles.addAll(parentRoles);
751 Iterator<CentralV2Role> parentRolesIterator = parentRoles.iterator();
752 while (parentRolesIterator.hasNext()) {
753 getAllParentRolesAsList(parentRolesIterator.next(), allParentRoles);
755 return allParentRoles;
758 public AuditLog getAuditInfo(EPUser user, String activityCode)
760 AuditLog auditLog = new AuditLog();
761 auditLog.setUserId(user.getId());
762 auditLog.setActivityCode(activityCode);
763 auditLog.setAffectedRecordId(user.getOrgUserId());
768 private void fieldsValidation(EPApp app) throws Exception{
770 List<EPApp> appInfo = externalAccessRolesService.getApp(app.getUebKey());
771 if(appInfo.isEmpty()){
772 throw new InvalidApplicationException("Invalid credentials");
774 if(!appInfo.isEmpty() && EcompPortalUtils.checkIfRemoteCentralAccessAllowed() && appInfo.get(0).getCentralAuth()){
775 ResponseEntity<String> response = externalAccessRolesService.getNameSpaceIfExists(appInfo.get(0));
776 if (response.getStatusCode().value() == HttpServletResponse.SC_NOT_FOUND)
777 throw new InvalidApplicationException("Invalid NameSpace");
781 private boolean isAuthorizedUser(EPUser user, EPApp requestedApp) {
782 if (user != null && (adminRolesService.isAccountAdminOfApplication(user, requestedApp)
783 || (adminRolesService.isSuperAdmin(user) && requestedApp.getId() == PortalConstants.PORTAL_APP_ID)))
788 private void SendErrorForUnauthorizedUser(HttpServletResponse response, EPUser user) throws IOException {
789 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
790 response.getWriter().write("Unauthorized User");
793 @RequestMapping(value = { "/portalApi/uploadRoleFunction/{appId}" }, method = RequestMethod.POST, produces = "application/json")
794 public PortalRestResponse<String> bulkUploadRoleFunc(HttpServletRequest request, HttpServletResponse response,
795 @RequestBody UploadRoleFunctionExtSystem data, @PathVariable("appId") Long appId) {
796 EPUser user = EPUserUtils.getUserSession(request);
798 EPApp app = appService.getApp(appId);
799 if (isAuthorizedUser(user, app)) {
800 fieldsValidation(app);
801 externalAccessRolesService.bulkUploadRoleFunc(data, app);
802 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
803 String code = data.getName()+","+data.getType()+ PIPE + data.getInstance() + PIPE + data.getAction();
804 logExterlaAuthRoleFunctionActivity(code , user, app, activityCode);
806 logger.info(EELFLoggerDelegate.auditLogger,
807 "RoleManageController.syncRoles, Unauthorized user:" + user.getOrgUserId());
808 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
809 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
811 } catch (Exception e) {
812 logger.error(EELFLoggerDelegate.errorLogger, "Failed bulkUploadRoleFunc!", e);
813 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
815 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Uploaded Role Function successfully!", "Success");