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 ROLE_INVALID_CHARS = "%=():,\"\"";
113 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleManageController.class);
116 private RoleController roleController;
119 private RoleListController roleListController;
122 private EPAppService appService;
125 private AuditService auditService;
128 private ExternalAccessRolesService externalAccessRolesService;
132 private AdminRolesService adminRolesService;
135 * Calls an SDK-Core library method that gets the available roles and writes
136 * them to the request object. Portal specifies a Hibernate mappings from
137 * the Role class to the fn_role_v view, which ensures that only Portal
138 * (app_id is null) roles are fetched.
140 * Any method declared void (no return value) or returning null causes the
141 * audit log aspect method to declare failure. TODO: should return a JSON
149 @RequestMapping(value = { "/portalApi/get_roles/{appId}" }, method = RequestMethod.GET)
150 public void getRoles(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId) throws Exception {
152 EPUser user = EPUserUtils.getUserSession(request);
153 EPApp requestedApp = appService.getApp(appId);
154 if (isAuthorizedUser(user, requestedApp)) {
155 fieldsValidation(requestedApp);
156 if (requestedApp.getCentralAuth()) {
157 List<CentralV2Role> answer = null;
158 Map<String, Object> model = new HashMap<>();
159 ObjectMapper mapper = new ObjectMapper();
160 answer = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey());
161 model.put("availableRoles", answer);
162 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
163 JSONObject j = new JSONObject(msg);
164 response.getWriter().write(j.toString());
166 throw new NonCentralizedAppException(requestedApp.getName());
168 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.getRoles, Unauthorized user");
169 SendErrorForUnauthorizedUser(response, user);
172 } catch (Exception e) {
173 logger.error(EELFLoggerDelegate.errorLogger, "getRoles failed", e);
179 @RequestMapping(value = { "/portalApi/role_list/toggleRole/{appId}/{roleId}" }, method = RequestMethod.POST)
180 public Map<String, Object> toggleRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
181 @PathVariable("roleId") Long roleId) throws Exception {
182 EPApp requestedApp = null;
183 String restcallStatus = null;
184 HashMap<String, Object> responseMap = new HashMap<>();
185 EPUser user = EPUserUtils.getUserSession(request);
187 requestedApp = appService.getApp(appId);
188 if (isAuthorizedUser(user, requestedApp)) {
189 fieldsValidation(requestedApp);
190 ObjectMapper mapper = new ObjectMapper();
191 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
192 CentralV2Role domainRole = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
193 // role. toggle active ind
194 boolean active = domainRole.isActive();
195 domainRole.setActive(!active);
197 String result = mapper.writeValueAsString(domainRole);
198 Role newRole = externalAccessRolesService.ConvertCentralRoleToRole(result);
199 ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService
200 .saveRoleForApplication(newRole, requestedApp.getUebKey());
201 boolean getAddResponse = externalRequestFieldsValidator.isResult();
202 if (getAddResponse) {
203 restcallStatus = "Success";
204 logger.info(EELFLoggerDelegate.auditLogger, "Toggle active status for role " + domainRole.getId());
206 restcallStatus = "Toggle Role Failed";
207 logger.info(EELFLoggerDelegate.auditLogger, "Toggle Role Failed " + domainRole.getId());
209 responseMap.put("restcallStatus", restcallStatus);
210 responseMap.put("availableRoles", externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()));
212 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.toggleRole, Unauthorized user");
213 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
214 responseMap.put("restcallStatus", " Unauthorized user");
216 } catch (Exception e) {
217 logger.error(EELFLoggerDelegate.errorLogger, "toggleRole failed", e);
223 @RequestMapping(value = { "/portalApi/role_list/removeRole/{appId}/{roleId}" }, method = RequestMethod.POST)
224 public Map<String, Object> removeRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
225 @PathVariable("roleId") Long roleId) throws Exception {
227 EPUser user = EPUserUtils.getUserSession(request);
228 EPApp requestedApp = null;
229 String restCallStatus = null;
230 HashMap<String, Object> responseMap = new HashMap<>();
231 ExternalRequestFieldsValidator externalRequestFieldsValidator = null;
233 requestedApp = appService.getApp(appId);
234 if (isAuthorizedUser(user, requestedApp)) {
235 fieldsValidation(requestedApp);
236 if (requestedApp.getCentralAuth()) {
237 externalRequestFieldsValidator = externalAccessRolesService.deleteDependencyRoleRecord(roleId,
238 requestedApp.getUebKey(), user.getOrgUserId());
239 boolean deleteResponse = externalRequestFieldsValidator.isResult();
240 if (deleteResponse) {
241 restCallStatus = "Success";
242 EPUser requestedUser = (EPUser) externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
243 EPApp app = (EPApp) externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
244 logger.info(EELFLoggerDelegate.applicationLogger, "deleteRole: succeeded for app {}, role {}",
245 app.getId(), roleId);
246 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE;
247 AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
248 auditLog.setComments(EcompPortalUtils.truncateString(
249 "Deleted role for app:" + app.getId() + " and role:'" + roleId + "'",
250 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
251 auditService.logActivity(auditLog, null);
252 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
253 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
254 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
255 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
256 EcompPortalUtils.calculateDateTimeDifferenceForLog(
257 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
258 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
259 logger.info(EELFLoggerDelegate.auditLogger,
260 EPLogUtil.formatAuditLogMessage("RoleManageController.removeRole",
261 EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE,
262 String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(),
264 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
265 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
266 MDC.remove(SystemProperties.MDC_TIMER);
268 restCallStatus = "Remove Role failed";
269 responseMap.put("error", externalRequestFieldsValidator.getDetailMessage());
270 logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed");
272 responseMap.put("restCallStatus", restCallStatus);
273 responseMap.put("availableRoles",
274 externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()));
276 throw new NonCentralizedAppException(requestedApp.getName());
278 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.removeRole, Unauthorized user");
279 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
280 responseMap.put("restCallStatus", " Unauthorized user");
282 } catch (Exception e) {
283 logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed", e);
289 @RequestMapping(value = { "/portalApi/role/saveRole/{appId}" }, method = RequestMethod.POST)
290 public Map<String, Object> saveRole(HttpServletRequest request, HttpServletResponse response,
291 @PathVariable("appId") Long appId) throws Exception {
292 EPUser user = EPUserUtils.getUserSession(request);
293 String responseString = null;
294 HashMap<String, Object> responseMap = new HashMap<>();
296 EPApp requestedApp = appService.getApp(appId);
297 if (isAuthorizedUser(user, requestedApp)) {
298 fieldsValidation(requestedApp);
299 if (requestedApp != null && requestedApp.getCentralAuth().equals(true)) {
300 ObjectMapper mapper = new ObjectMapper();
301 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
302 JsonNode root = mapper.readTree(request.getReader());
303 CentralV2Role role = mapper.readValue(root.get("role").toString(), CentralV2Role.class);
305 List<CentralV2Role> childRoles = mapper.readValue(root.get("childRoles").toString(),
306 TypeFactory.defaultInstance().constructCollectionType(List.class, CentralV2Role.class));
307 List<CentralV2RoleFunction> roleFunctions = mapper.readValue(root.get("roleFunctions").toString(),
308 TypeFactory.defaultInstance().constructCollectionType(List.class,
309 CentralV2RoleFunction.class));
310 if (role.getId() != null && StringUtils.containsAny(role.getName(), ROLE_INVALID_CHARS)) {
311 throw new InvalidRoleException("Invalid role name found for '" + role.getName()
312 + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
314 CentralV2Role domainRole;
315 if (role.getId() != null) {
316 domainRole = externalAccessRolesService.getRoleInfo(role.getId(), requestedApp.getUebKey());
317 domainRole.setName(role.getName());
318 domainRole.setPriority(role.getPriority());
320 // check for existing role of same name
321 List<CentralV2Role> roles = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey());
322 for (CentralV2Role existRole : roles)
323 if (existRole.getName().equalsIgnoreCase(role.getName()))
324 throw new DuplicateRecordException("role already exists: " + existRole.getName());
326 domainRole = new CentralV2Role();
327 domainRole.setName(role.getName());
328 domainRole.setPriority(role.getPriority());
329 if (role.getChildRoles() != null && role.getChildRoles().size() > 0) {
330 for (Object childRole : childRoles) {
331 domainRole.addChildRole((CentralV2Role) childRole);
335 if (role.getRoleFunctions() != null && role.getRoleFunctions().size() > 0) {
336 domainRole.setRoleFunctions(new TreeSet<CentralV2RoleFunction>());
337 for (CentralV2RoleFunction roleFunction : roleFunctions) {
338 if (roleFunction.getType() == null && roleFunction.getAction() == null) {
339 throw new InvalidRoleException("Invalid role function type:" + roleFunction.getType()
340 + " and action: " + roleFunction.getAction() + " found while saving!");
342 roleFunction.setCode(externalAccessRolesService.encodeFunctionCode(roleFunction.getCode()));
343 roleFunction.setCode(roleFunction.getType() + "|" + roleFunction.getCode() + "|"
344 + roleFunction.getAction());
345 domainRole.addRoleFunction((CentralV2RoleFunction) roleFunction);
348 domainRole.setRoleFunctions(new TreeSet<>());
350 String result = mapper.writeValueAsString(domainRole);
351 Role newRole = externalAccessRolesService.ConvertCentralRoleToRole(result);
352 ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService
353 .saveRoleForApplication(newRole, requestedApp.getUebKey());
354 boolean getAddResponse = externalRequestFieldsValidator.isResult();
355 if (getAddResponse) {
356 String activityCode = (role.getId() == null) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_ROLE
357 : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
358 logger.info(EELFLoggerDelegate.applicationLogger, "saveRole: succeeded for app {}, role {}",
359 requestedApp.getId(), role.getName());
360 AuditLog auditLog = new AuditLog();
361 auditLog.setUserId(user.getId());
362 auditLog.setActivityCode(activityCode);
363 auditLog.setComments(EcompPortalUtils.truncateString(
364 "saveRole role for app:" + requestedApp.getId() + " and role:'" + role.getName() + "'",
365 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
366 auditLog.setAffectedRecordId(user.getOrgUserId());
367 auditService.logActivity(auditLog, null);
368 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
369 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
370 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
371 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
372 EcompPortalUtils.calculateDateTimeDifferenceForLog(
373 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
374 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
375 logger.info(EELFLoggerDelegate.auditLogger,
376 EPLogUtil.formatAuditLogMessage("RoleManageController.saveRole", activityCode,
377 String.valueOf(user.getId()), user.getOrgUserId(), role.getName()));
378 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
379 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
380 MDC.remove(SystemProperties.MDC_TIMER);
381 responseMap.put("status", "Success");
382 responseMap.put("role", domainRole);
384 if (externalRequestFieldsValidator.getDetailMessage().contains("406")) {
385 externalRequestFieldsValidator.setDetailMessage("Failed to save role for '" + role.getName()
386 + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
388 responseMap.put("status", "SaveRole Failed");
389 responseMap.put("role", responseString);
390 responseMap.put("error", externalRequestFieldsValidator.getDetailMessage());
391 logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed");
395 logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRole, Unauthorized user");
396 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
397 responseMap.put("error", " Unauthorized user");
399 } catch (Exception e) {
400 logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e);
401 responseMap.put("error", e.getMessage());
406 @RequestMapping(value = { "/portalApi/role/removeRoleFunction" }, method = RequestMethod.POST)
407 public ModelAndView removeRoleRoleFunction(HttpServletRequest request, HttpServletResponse response)
409 return getRoleController().removeRoleFunction(request, response);
412 @RequestMapping(value = { "/portalApi/role/addRoleFunction" }, method = RequestMethod.POST)
413 public ModelAndView addRoleRoRoleFunction(HttpServletRequest request, HttpServletResponse response)
415 return getRoleController().addRoleFunction(request, response);
418 @RequestMapping(value = { "/portalApi/role/removeChildRole" }, method = RequestMethod.POST)
419 public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
420 return getRoleController().removeChildRole(request, response);
423 @RequestMapping(value = { "/portalApi/role/addChildRole" }, method = RequestMethod.POST)
424 public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
425 return getRoleController().addChildRole(request, response);
428 @RequestMapping(value = { "/portalApi/get_role/{appId}/{roleId}" }, method = RequestMethod.GET)
429 public void getRole(HttpServletRequest request, HttpServletResponse response, @PathVariable("appId") Long appId,
430 @PathVariable("roleId") Long roleId) throws Exception {
432 EPUser user = EPUserUtils.getUserSession(request);
433 ObjectMapper mapper = new ObjectMapper();
434 EPApp requestedApp = appService.getApp(appId);
435 if (isAuthorizedUser(user, requestedApp)) {
436 fieldsValidation(requestedApp);
437 if (requestedApp.getCentralAuth()) {
438 CentralV2Role answer = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
439 logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + roleId);
440 Map<String, Object> model = new HashMap<>();
441 model.put("availableRoleFunctions", mapper.writeValueAsString(
442 externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey())));
443 model.put("availableRoles",
444 mapper.writeValueAsString(getAvailableChildRoles(requestedApp.getUebKey(), roleId)));
445 model.put("role", mapper.writeValueAsString(answer));
446 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
447 JSONObject j = new JSONObject(msg);
448 response.getWriter().write(j.toString());
450 throw new NonCentralizedAppException(requestedApp.getName());
452 logger.info(EELFLoggerDelegate.auditLogger,
453 "RoleManageController.getRoleFunctionList, Unauthorized user");
454 SendErrorForUnauthorizedUser(response, user);
456 } catch (Exception e) {
457 logger.error(EELFLoggerDelegate.errorLogger, "getRole failed", e);
462 @RequestMapping(value = { "/portalApi/get_role_functions/{appId}" }, method = RequestMethod.GET)
463 public void getRoleFunctionList(HttpServletRequest request, HttpServletResponse response,
464 @PathVariable("appId") Long appId) throws Exception {
466 EPUser user = EPUserUtils.getUserSession(request);
467 EPApp requestedApp = appService.getApp(appId);
468 if (isAuthorizedUser(user, requestedApp)) {
469 fieldsValidation(requestedApp);
470 if (requestedApp.getCentralAuth()) {
471 List<CentralV2RoleFunction> answer = null;
472 Map<String, Object> model = new HashMap<>();
473 ObjectMapper mapper = new ObjectMapper();
474 answer = externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey());
475 model.put("availableRoleFunctions", answer);
476 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
477 JSONObject j = new JSONObject(msg);
478 response.getWriter().write(j.toString());
480 throw new NonCentralizedAppException(requestedApp.getName());
482 logger.info(EELFLoggerDelegate.auditLogger,
483 "RoleManageController.getRoleFunctionList, Unauthorized user");
484 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
485 response.getWriter().write("Unauthorized User");
487 } catch (Exception e) {
488 logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunctionList failed", e);
493 @RequestMapping(value = { "/portalApi/role_function_list/saveRoleFunction/{appId}" }, method = RequestMethod.POST)
494 public PortalRestResponse<String> saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @RequestBody CentralV2RoleFunction roleFunc,
495 @PathVariable("appId") Long appId) throws Exception {
496 EPUser user = EPUserUtils.getUserSession(request);
497 boolean saveOrUpdateResponse = false;
499 EPApp requestedApp = appService.getApp(appId);
500 if (isAuthorizedUser(user, requestedApp)) {
501 fieldsValidation(requestedApp);
502 if (requestedApp.getCentralAuth()) {
503 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(roleFunc, requestedApp);
504 if (saveOrUpdateResponse) {
505 EPUser requestedUser = externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
506 EPApp app = externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
507 CentralV2RoleFunction function = externalAccessRolesService.getRoleFunction(roleFunc.getCode(),
508 requestedApp.getUebKey());
509 String activityCode = (function.getCode() == null)
510 ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION
511 : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION;
512 logger.info(EELFLoggerDelegate.applicationLogger,
513 "saveRoleFunction: succeeded for app {}, function {}", app.getId(), roleFunc.getCode());
514 AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
515 auditLog.setComments(EcompPortalUtils.truncateString("saveRoleFunction role for app:"
516 + app.getId() + " and function:'" + roleFunc.getCode() + "'",
517 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
518 auditService.logActivity(auditLog, null);
519 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
520 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
521 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
522 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
523 EcompPortalUtils.calculateDateTimeDifferenceForLog(
524 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
525 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
526 logger.info(EELFLoggerDelegate.auditLogger,
527 EPLogUtil.formatAuditLogMessage("RoleManageController.saveRoleFunction", activityCode,
528 String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(),
529 roleFunc.getCode()));
530 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
531 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
532 MDC.remove(SystemProperties.MDC_TIMER);
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 @RequestMapping(value = { "/portalApi/role_function_list/removeRoleFunction/{appId}" }, method = RequestMethod.POST)
550 public PortalRestResponse<String> removeRoleFunction(HttpServletRequest request, HttpServletResponse response,
551 @RequestBody String roleFunc, @PathVariable("appId") Long appId) throws Exception {
552 EPUser user = EPUserUtils.getUserSession(request);
554 EPApp requestedApp = appService.getApp(appId);
555 if (isAuthorizedUser(user, requestedApp)) {
556 fieldsValidation(requestedApp);
557 if (requestedApp.getCentralAuth()) {
558 ObjectMapper mapper = new ObjectMapper();
559 String data = roleFunc;
560 CentralV2RoleFunction availableRoleFunction = mapper.readValue(data, CentralV2RoleFunction.class);
561 CentralV2RoleFunction domainRoleFunction = externalAccessRolesService
562 .getRoleFunction(availableRoleFunction.getCode(), requestedApp.getUebKey());
563 boolean getDelFuncResponse = externalAccessRolesService
564 .deleteCentralRoleFunction(domainRoleFunction.getCode(), requestedApp);
565 if (getDelFuncResponse) {
566 logger.info(EELFLoggerDelegate.applicationLogger,
567 "deleteRoleFunction: succeeded for app {}, role {}", requestedApp.getId(),
568 domainRoleFunction.getCode());
569 String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION;
570 AuditLog auditLog = getAuditInfo(user, activityCode);
571 auditLog.setComments(
572 EcompPortalUtils.truncateString(
573 "Deleted function for app:" + requestedApp.getId() + " and function code:'"
574 + domainRoleFunction.getCode() + "'",
575 PortalConstants.AUDIT_LOG_COMMENT_SIZE));
576 auditService.logActivity(auditLog, null);
577 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
578 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
579 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
580 EPEELFLoggerAdvice.getCurrentDateTimeUTC());
581 EcompPortalUtils.calculateDateTimeDifferenceForLog(
582 MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
583 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
584 logger.info(EELFLoggerDelegate.auditLogger,
585 EPLogUtil.formatAuditLogMessage("RoleManageController.removeRoleFunction",
586 EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION,
587 String.valueOf(user.getId()), user.getOrgUserId(),
588 domainRoleFunction.getCode()));
589 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
590 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
591 MDC.remove(SystemProperties.MDC_TIMER);
592 logger.info(EELFLoggerDelegate.auditLogger,
593 "Remove role function " + domainRoleFunction.getName());
596 throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
598 logger.info(EELFLoggerDelegate.auditLogger,
599 "RoleManageController.removeRoleFunction, Unauthorized user");
600 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
601 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
603 } catch (Exception e) {
604 logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed", e);
605 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure");
607 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Deleted Successfully!", "Success");
610 @RequestMapping(value = { "/portalApi/centralizedApps" }, method = RequestMethod.GET)
611 public List<CentralizedApp> getCentralizedAppRoles(HttpServletRequest request, HttpServletResponse response, String userId) throws IOException {
612 EPUser user = EPUserUtils.getUserSession(request);
613 List<CentralizedApp> applicationsList = null;
614 if (adminRolesService.isAccountAdmin(user) || adminRolesService.isSuperAdmin(user)) {
615 applicationsList = externalAccessRolesService.getCentralizedAppsOfUser(userId);
617 logger.info(EELFLoggerDelegate.auditLogger,
618 "RoleManageController.getCentralizedAppRoles, Unauthorized user");
619 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
621 return applicationsList;
624 public RoleListController getRoleListController() {
625 return roleListController;
628 public void setRoleListController(RoleListController roleListController) {
629 this.roleListController = roleListController;
632 public RoleController getRoleController() {
633 return roleController;
636 public void setRoleController(RoleController roleController) {
637 this.roleController = roleController;
641 @RequestMapping(value = { "/portalApi/syncRoles" }, method = RequestMethod.POST, produces = "application/json")
642 public PortalRestResponse<String> syncRoles(HttpServletRequest request, HttpServletResponse response,
643 @RequestBody Long appId) {
644 EPUser user = EPUserUtils.getUserSession(request);
646 EPApp app = appService.getApp(appId);
647 if (isAuthorizedUser(user, app)) {
648 fieldsValidation(app);
649 externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
651 logger.info(EELFLoggerDelegate.auditLogger,
652 "RoleManageController.syncRoles, Unauthorized user:" + user.getOrgUserId());
653 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
654 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
656 } catch (Exception e) {
657 logger.error(EELFLoggerDelegate.errorLogger, "failed syncRoles", e);
658 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
660 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync roles completed successfully!", "Success");
663 @RequestMapping(value = { "/portalApi/syncFunctions" }, method = RequestMethod.POST, produces = "application/json")
664 public PortalRestResponse<String> syncFunctions(HttpServletRequest request, HttpServletResponse response,
665 @RequestBody Long appId) {
666 EPUser user = EPUserUtils.getUserSession(request);
668 EPApp app = appService.getApp(appId);
669 if (isAuthorizedUser(user, app)) {
670 fieldsValidation(app);
671 externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);;
673 logger.info(EELFLoggerDelegate.auditLogger,
674 "RoleManageController.syncFunctions, Unauthorized user:" + user.getOrgUserId());
675 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
676 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
678 } catch (Exception e) {
679 logger.error(EELFLoggerDelegate.errorLogger, "failed syncFunctions", e);
680 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
682 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync Functions completed successfully!", "Success");
685 public List<CentralV2Role> getAvailableChildRoles(String uebKey, Long roleId) throws Exception {
686 List<CentralV2Role> availableChildRoles = externalAccessRolesService.getRolesForApp(uebKey);
687 if (roleId == null || roleId == 0) {
688 return availableChildRoles;
690 CentralV2Role currentRole = externalAccessRolesService.getRoleInfo(roleId, uebKey);
691 Set<CentralV2Role> allParentRoles = new TreeSet<>();
692 allParentRoles = getAllParentRolesAsList(currentRole, allParentRoles);
693 Iterator<CentralV2Role> availableChildRolesIterator = availableChildRoles.iterator();
694 while (availableChildRolesIterator.hasNext()) {
695 CentralV2Role role = availableChildRolesIterator.next();
696 if (!role.isActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) {
697 availableChildRolesIterator.remove();
700 return availableChildRoles;
703 private Set<CentralV2Role> getAllParentRolesAsList(CentralV2Role role, Set<CentralV2Role> allParentRoles) {
704 Set<CentralV2Role> parentRoles = role.getParentRoles();
705 allParentRoles.addAll(parentRoles);
706 Iterator<CentralV2Role> parentRolesIterator = parentRoles.iterator();
707 while (parentRolesIterator.hasNext()) {
708 getAllParentRolesAsList(parentRolesIterator.next(), allParentRoles);
710 return allParentRoles;
713 public AuditLog getAuditInfo(EPUser user, String activityCode)
715 AuditLog auditLog = new AuditLog();
716 auditLog.setUserId(user.getId());
717 auditLog.setActivityCode(activityCode);
718 auditLog.setAffectedRecordId(user.getOrgUserId());
723 private void fieldsValidation(EPApp app) throws Exception{
725 List<EPApp> appInfo = externalAccessRolesService.getApp(app.getUebKey());
726 if(appInfo.isEmpty()){
727 throw new InvalidApplicationException("Invalid uebkey");
729 if(!appInfo.isEmpty() && EcompPortalUtils.checkIfRemoteCentralAccessAllowed() && appInfo.get(0).getCentralAuth()){
730 ResponseEntity<String> response = externalAccessRolesService.getNameSpaceIfExists(appInfo.get(0));
731 if (response.getStatusCode().value() == HttpServletResponse.SC_NOT_FOUND)
732 throw new InvalidApplicationException("Invalid NameSpace");
736 private boolean isAuthorizedUser(EPUser user, EPApp requestedApp) {
737 if (user != null && (adminRolesService.isAccountAdminOfApplication(user, requestedApp)
738 || (adminRolesService.isSuperAdmin(user) && requestedApp.getId() == PortalConstants.PORTAL_APP_ID)))
743 private void SendErrorForUnauthorizedUser(HttpServletResponse response, EPUser user) throws IOException {
744 EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
745 response.getWriter().write("Unauthorized User");