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