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