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