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