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