059979d22f10450c54dbd04556da6f1dec610a97
[portal.git] / portal-BE / src / main / java / org / onap / portal / service / AdminRolesService.java
1 /*
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2019 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
41 package org.onap.portal.service;
42
43 import com.fasterxml.jackson.core.JsonProcessingException;
44 import com.fasterxml.jackson.databind.DeserializationFeature;
45 import com.fasterxml.jackson.databind.ObjectMapper;
46 import java.time.LocalDateTime;
47 import java.util.ArrayList;
48 import java.util.Arrays;
49 import java.util.Collection;
50 import java.util.Collections;
51 import java.util.HashMap;
52 import java.util.HashSet;
53 import java.util.List;
54 import java.util.Map;
55 import java.util.Optional;
56 import java.util.Set;
57 import java.util.SortedSet;
58 import java.util.TreeSet;
59 import java.util.stream.Collectors;
60 import javax.persistence.EntityManager;
61 import javax.persistence.Query;
62 import javax.persistence.Tuple;
63 import org.apache.commons.lang.StringUtils;
64 import org.apache.cxf.transport.http.HTTPException;
65 import org.hibernate.Session;
66 import org.hibernate.Transaction;
67 import org.json.JSONArray;
68 import org.json.JSONObject;
69 import org.onap.portal.domain.db.ep.EpAppFunction;
70 import org.onap.portal.domain.db.ep.EpUserRolesRequest;
71 import org.onap.portal.domain.db.ep.EpUserRolesRequestDet;
72 import org.onap.portal.domain.db.fn.FnApp;
73 import org.onap.portal.domain.db.fn.FnFunction;
74 import org.onap.portal.domain.db.fn.FnMenuFunctional;
75 import org.onap.portal.domain.db.fn.FnMenuFunctionalRoles;
76 import org.onap.portal.domain.db.fn.FnRole;
77 import org.onap.portal.domain.db.fn.FnRoleFunction;
78 import org.onap.portal.domain.db.fn.FnUser;
79 import org.onap.portal.domain.db.fn.FnUserRole;
80 import org.onap.portal.domain.dto.transport.AppNameIdIsAdmin;
81 import org.onap.portal.domain.dto.transport.AppWithRolesForUser;
82 import org.onap.portal.domain.dto.transport.AppsListWithAdminRole;
83 import org.onap.portal.domain.dto.transport.CentralV2Role;
84 import org.onap.portal.domain.dto.transport.EPUserAppCurrentRoles;
85 import org.onap.portal.domain.dto.transport.EcompUserAppRoles;
86 import org.onap.portal.domain.dto.transport.ExternalAccessUser;
87 import org.onap.portal.domain.dto.transport.ExternalAccessUserRoleDetail;
88 import org.onap.portal.domain.dto.transport.ExternalRequestFieldsValidator;
89 import org.onap.portal.domain.dto.transport.ExternalRoleDescription;
90 import org.onap.portal.domain.dto.transport.RemoteRoleV1;
91 import org.onap.portal.domain.dto.transport.Role;
92 import org.onap.portal.domain.dto.transport.RoleInAppForUser;
93 import org.onap.portal.domain.dto.transport.RolesInAppForUser;
94 import org.onap.portal.exception.DeleteDomainObjectFailedException;
95 import org.onap.portal.exception.SyncUserRolesException;
96 import org.onap.portal.logging.format.EPAppMessagesEnum;
97 import org.onap.portal.logging.logic.EPLogUtil;
98 import org.onap.portal.service.appFunction.EpAppFunctionService;
99 import org.onap.portal.service.userRolesRequestDet.EpUserRolesRequestDetService;
100 import org.onap.portal.service.userRolesRequest.EpUserRolesRequestService;
101 import org.onap.portal.service.app.FnAppService;
102 import org.onap.portal.service.menuFunctionalRoles.FnMenuFunctionalRolesService;
103 import org.onap.portal.service.menuFunctional.FnMenuFunctionalService;
104 import org.onap.portal.service.role.FnRoleService;
105 import org.onap.portal.service.userRole.FnUserRoleService;
106 import org.onap.portal.service.user.FnUserService;
107 import org.onap.portal.utils.EPCommonSystemProperties;
108 import org.onap.portal.utils.EPUserUtils;
109 import org.onap.portal.utils.EcompPortalUtils;
110 import org.onap.portal.utils.PortalConstants;
111 import org.onap.portalsdk.core.domain.RoleFunction;
112 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
113 import org.onap.portalsdk.core.restful.domain.EcompRole;
114 import org.onap.portalsdk.core.util.SystemProperties;
115 import org.springframework.beans.factory.annotation.Autowired;
116 import org.springframework.http.HttpEntity;
117 import org.springframework.http.HttpHeaders;
118 import org.springframework.http.HttpMethod;
119 import org.springframework.http.HttpStatus;
120 import org.springframework.http.ResponseEntity;
121 import org.springframework.stereotype.Service;
122 import org.springframework.transaction.annotation.Transactional;
123 import org.springframework.web.client.HttpClientErrorException;
124 import org.springframework.web.client.RestTemplate;
125
126 @Service
127 @Transactional
128 public class AdminRolesService {
129
130   private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesService.class);
131   private static final Object syncRests = new Object();
132   private final RestTemplate template = new RestTemplate();
133
134   private Long SYS_ADMIN_ROLE_ID = 38L;
135   private final Long ACCOUNT_ADMIN_ROLE_ID = 999L;
136   private final Long ECOMP_APP_ID = 1L;
137   private final String ADMIN_ACCOUNT = "Is account admin for user {}";
138
139   private final AppsCacheService appsCacheService;
140   private final EntityManager entityManager;
141   private final FnUserService fnUserService;
142   private final FnRoleService fnRoleService;
143   private final FnAppService fnAppService;
144   private final FnMenuFunctionalService fnMenuFunctionalService;
145   private final FnUserRoleService fnUserRoleService;
146   private final EpAppFunctionService epAppFunctionService;
147   private final EcompUserAppRolesService ecompUserAppRolesService;
148   private final FnMenuFunctionalRolesService fnMenuFunctionalRolesService;
149   private final ApplicationsRestClientService applicationsRestClientService;
150   private final EpUserRolesRequestDetService epUserRolesRequestDetService;
151   private final ExternalAccessRolesService externalAccessRolesService;
152   private final EpUserRolesRequestService epUserRolesRequestService;
153
154   @Autowired
155   public AdminRolesService(AppsCacheService appsCacheService,
156       final EntityManager entityManager,
157       final FnUserService fnUserService, FnRoleService fnRoleService,
158       FnAppService fnAppService,
159       FnMenuFunctionalService fnMenuFunctionalService,
160       final FnUserRoleService fnUserRoleService,
161       EpAppFunctionService epAppFunctionService,
162       EcompUserAppRolesService ecompUserAppRolesService,
163       FnMenuFunctionalRolesService fnMenuFunctionalRolesService,
164       ApplicationsRestClientService applicationsRestClientService,
165       EpUserRolesRequestDetService epUserRolesRequestDetService,
166       ExternalAccessRolesService externalAccessRolesService,
167       EpUserRolesRequestService epUserRolesRequestService) {
168     this.appsCacheService = appsCacheService;
169     this.entityManager = entityManager;
170     this.fnUserService = fnUserService;
171     this.fnRoleService = fnRoleService;
172     this.fnAppService = fnAppService;
173     this.fnMenuFunctionalService = fnMenuFunctionalService;
174     this.fnUserRoleService = fnUserRoleService;
175     this.epAppFunctionService = epAppFunctionService;
176     this.ecompUserAppRolesService = ecompUserAppRolesService;
177     this.fnMenuFunctionalRolesService = fnMenuFunctionalRolesService;
178     this.applicationsRestClientService = applicationsRestClientService;
179     this.epUserRolesRequestDetService = epUserRolesRequestDetService;
180     this.externalAccessRolesService = externalAccessRolesService;
181     this.epUserRolesRequestService = epUserRolesRequestService;
182   }
183
184   public boolean isSuperAdmin(final String loginId) {
185     boolean isSuperAdmin;
186     try {
187       isSuperAdmin = fnUserRoleService
188           .isSuperAdmin(loginId, SYS_ADMIN_ROLE_ID, ECOMP_APP_ID);
189     } catch (Exception e) {
190       logger.error("isSuperAdmin exception: " + e.toString());
191       throw e;
192     }
193     logger.info("isSuperAdmin " + isSuperAdmin);
194     return isSuperAdmin;
195   }
196
197   public boolean isAccountAdmin(final long userId, final String orgUserId, final Set<FnUserRole> userApps) {
198     try {
199       logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, userId);
200       List<Integer> userAdminApps = getAdminAppsForTheUser(userId);
201       logger.debug(EELFLoggerDelegate.debugLogger,
202           "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}",
203           orgUserId, userAdminApps.size());
204
205       for (FnUserRole userApp : userApps) {
206         if (userApp.getRoleId().getId().equals(ACCOUNT_ADMIN_ROLE_ID) || (
207             userAdminApps.size() > 1)) {
208           logger.debug(EELFLoggerDelegate.debugLogger,
209               "Is account admin for userAdminApps() - for user {}, found Id {}",
210               orgUserId, userApp.getRoleId().getId());
211           return true;
212         }
213       }
214     } catch (Exception e) {
215       EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
216       logger.error(EELFLoggerDelegate.errorLogger,
217           "Exception occurred while executing isAccountAdmin operation",
218           e);
219     }
220     return false;
221   }
222
223   public boolean isUser(final long userId) {
224     try {
225       FnUser currentUser = fnUserService.getUser(userId).orElseThrow(Exception::new);
226       if (currentUser != null && currentUser.getId() != null) {
227         for (FnUserRole userApp : currentUser.getUserApps()) {
228           if (!userApp.getFnAppId().getId().equals(ECOMP_APP_ID)) {
229             FnRole role = userApp.getRoleId();
230             if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId()
231                 .equals(ACCOUNT_ADMIN_ROLE_ID)) {
232               if (role.getActiveYn()) {
233                 return true;
234               }
235             }
236           }
237         }
238       }
239     } catch (Exception e) {
240       EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
241       logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation",
242           e);
243     }
244     return false;
245   }
246
247   public boolean isRoleAdmin(Long userId) {
248     try {
249       logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has isRoleAdmin access");
250       List getRoleFuncListOfUser = fnUserRoleService.getRoleFunctionsOfUserforAlltheApplications(userId);
251       logger.debug(EELFLoggerDelegate.debugLogger,
252           "Checking if user has isRoleAdmin access :: getRoleFuncListOfUser", getRoleFuncListOfUser);
253       Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfUser);
254       Set<String> getRoleFuncListOfPortalSet1 = new HashSet<>();
255       Set<String> roleFunSet;
256       roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|"))
257           .collect(Collectors.toSet());
258       if (!roleFunSet.isEmpty()) {
259         for (String roleFunction : roleFunSet) {
260           String type = externalAccessRolesService.getFunctionCodeType(roleFunction);
261           getRoleFuncListOfPortalSet1.add(type);
262         }
263       }
264
265       boolean checkIfFunctionsExits = getRoleFuncListOfPortalSet1.stream()
266           .anyMatch(roleFunction -> roleFunction.equalsIgnoreCase("Approver"));
267       logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has approver rolefunction",
268           checkIfFunctionsExits);
269
270       return checkIfFunctionsExits;
271
272     } catch (Exception e) {
273       EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
274       logger.error(EELFLoggerDelegate.errorLogger,
275           "Exception occurred while executing isRoleAdmin operation",
276           e);
277     }
278     return false;
279   }
280
281   private boolean isAccountAdminOfApplication(Long userId, FnApp app) {
282     boolean isApplicationAccountAdmin = false;
283     try {
284       logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, userId);
285       List<Integer> userAdminApps = getAdminAppsForTheUser(userId);
286       if (!userAdminApps.isEmpty()) {
287         isApplicationAccountAdmin = userAdminApps.contains(app.getId());
288         logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user is true{} ,appId {}", userId,
289             app.getId());
290       }
291     } catch (Exception e) {
292       EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
293       logger.error(EELFLoggerDelegate.errorLogger,
294           "Exception occurred while executing isAccountAdminOfApplication operation", e);
295     }
296     logger.debug(EELFLoggerDelegate.debugLogger,
297         "In AdminRolesServiceImpl() - isAccountAdminOfApplication = {} and userId ={} ", isApplicationAccountAdmin,
298         userId);
299     return isApplicationAccountAdmin;
300
301   }
302
303   private List<Integer> getAdminAppsForTheUser(final Long userId) {
304     String query = "select fa.app_id from fn_user_role ur,fn_app fa where ur.user_id =:userId and ur.app_id=fa.app_id and ur.role_id= 999 and (fa.enabled = 'Y' || fa.app_id=1)";
305     return entityManager.createQuery(query, Integer.class)
306         .setParameter("userId", userId).getResultList();
307   }
308
309   public ExternalRequestFieldsValidator setAppWithUserRoleStateForUser(FnUser user,
310       AppWithRolesForUser newAppRolesForUser) {
311     boolean result = false;
312     boolean epRequestValue = false;
313     String userId = "";
314     String reqMessage = "";
315     if (newAppRolesForUser != null && newAppRolesForUser.getOrgUserId() != null) {
316       userId = newAppRolesForUser.getOrgUserId().trim();
317     }
318     Long appId = newAppRolesForUser.getAppId();
319     List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.getAppRoles();
320
321     if (userId.length() > 0) {
322       ObjectMapper mapper = new ObjectMapper();
323       mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
324
325       try {
326         FnApp app = fnAppService.getById(appId);
327
328         boolean checkIfUserisApplicationAccAdmin = isAccountAdminOfApplication(user.getId(),
329             app);
330         Set<EcompRole> rolesGotDeletedFromApprover = new TreeSet<>();
331
332         boolean checkIfUserIsOnlyRoleAdmin =
333             isRoleAdmin(user.getId()) && !checkIfUserisApplicationAccAdmin;
334         if (checkIfUserIsOnlyRoleAdmin) {
335           for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
336             if (!roleInAppForUser.getIsApplied()) {
337               EcompRole ecompRole = new EcompRole();
338               ecompRole.setId(roleInAppForUser.getRoleId());
339               ecompRole.setName(roleInAppForUser.getRoleName());
340               rolesGotDeletedFromApprover.add(ecompRole);
341             }
342           }
343         }
344
345         applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
346
347         boolean systemUser = newAppRolesForUser.isSystemUser();
348
349         if ((app.getAuthCentral() || app.getId().equals(PortalConstants.PORTAL_APP_ID))
350             && systemUser) {
351
352           Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList);
353           RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId,
354               userRolesInLocalApp);
355           List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
356           Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
357           if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
358             // Apply changes in external Access system
359
360             updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(),
361                 roleAppUserList,
362                 epRequestValue, systemUser, rolesGotDeletedByApprover, false);
363           }
364           result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue,
365               "Portal",
366               systemUser, rolesGotDeletedByApprover, false);
367
368         } else if (!app.getAuthCentral() && systemUser) {
369           throw new Exception("For non-centralized application we cannot add systemUser");
370         } else {    // if centralized app
371           if (app.getAuthCentral()) {
372             if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
373               pushRemoteUser(roleInAppForUserList, userId, app, mapper,
374                   applicationsRestClientService, false);
375             }
376
377             Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(
378                 roleInAppForUserList);
379             RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId,
380                 appId,
381                 userRolesInLocalApp);
382             List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
383             if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
384
385               // Apply changes in external Access system
386               updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(),
387                   roleAppUserList,
388                   epRequestValue, false, rolesGotDeletedFromApprover,
389                   checkIfUserIsOnlyRoleAdmin);
390             }
391             result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
392                 epRequestValue, "Portal", systemUser, rolesGotDeletedFromApprover,
393                 checkIfUserIsOnlyRoleAdmin);
394           }
395           // In case if portal is not centralized then follow existing approach
396           else if (!app.getAuthCentral() && app.getId()
397               .equals(PortalConstants.PORTAL_APP_ID)) {
398             Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(
399                 roleInAppForUserList);
400             RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId,
401                 appId,
402                 userRolesInLocalApp);
403             Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
404             result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
405                 epRequestValue, "Portal", false, rolesGotDeletedByApprover, false);
406           } else {// remote app
407             FnUser remoteAppUser;
408             if (!app.getAuthCentral() && !app.getId()
409                 .equals(PortalConstants.PORTAL_APP_ID)) {
410
411               remoteAppUser = checkIfRemoteUserExits(userId, app,
412                   applicationsRestClientService);
413
414               if (remoteAppUser == null) {
415                 addRemoteUser(roleInAppForUserList, userId, app,
416                     mapper, applicationsRestClientService);
417               }
418               Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(
419                   roleInAppForUserList, mapper,
420                   applicationsRestClientService, appId, userId);
421               RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(
422                   userId, appId,
423                   userRolesInRemoteApp);
424               Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
425               result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser,
426                   epRequestValue, null, false, rolesGotDeletedByApprover, false);
427
428               // If no roles remain, request app to set user inactive.
429               if (userRolesInRemoteApp.size() == 0) {
430                 logger.debug(EELFLoggerDelegate.debugLogger,
431                     "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive",
432                     app,
433                     userId);
434                 postUserToRemoteApp(userId, app,
435                     applicationsRestClientService);
436               }
437             }
438           }
439         }
440       } catch (Exception e) {
441         String message = String.format(
442             "Failed to create user or update user roles for User %s, AppId %s",
443             userId, Long.toString(appId));
444         logger.error(EELFLoggerDelegate.errorLogger, message, e);
445         result = false;
446         reqMessage = e.getMessage();
447       }
448     }
449     //return result;
450     return new ExternalRequestFieldsValidator(result, reqMessage);
451
452   }
453
454   private void pushRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, FnApp app,
455       ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService, boolean appRoleIdUsed)
456       throws Exception {
457     pushUserOnRemoteApp(userId, app, applicationsRestClientService, mapper,
458         roleInAppForUserList, appRoleIdUsed);
459   }
460
461
462   private void postUserToRemoteApp(String userId, FnApp app,
463       ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
464
465     getUser(userId, app, applicationsRestClientService);
466
467   }
468
469   private FnUser getUser(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService)
470       throws HTTPException {
471     return applicationsRestClientService.get(FnUser.class, app.getId(), String.format("/user/%s", userId), true);
472
473   }
474
475   private void pushUserOnRemoteApp(String userId, FnApp app,
476       ApplicationsRestClientService applicationsRestClientService,
477       ObjectMapper mapper, List<RoleInAppForUser> roleInAppForUserList, boolean appRoleIdUsed)
478       throws Exception {
479
480     FnUser client;
481     client = fnUserService.loadUserByUsername(userId);
482
483     mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
484     if (client == null) {
485       String msg = "cannot create user " + userId + ", because he/she cannot be found in directory.";
486       logger.error(EELFLoggerDelegate.errorLogger, msg);
487       List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
488       if (!userList.isEmpty()) {
489         logger.debug(EELFLoggerDelegate.debugLogger,
490             userList.get(0).getOrgUserId() + " User was found in Portal");
491         client = userList.get(0);
492         client.setUserApps(Collections.EMPTY_SET);
493         client.setIsSystemUser(false);
494       } else {
495         logger.error(EELFLoggerDelegate.errorLogger, "user cannot be found be in directory or in portal");
496         throw new Exception(msg);
497       }
498
499     }
500
501     client.setLoginId(userId);
502     client.setActiveYn(true);
503     client.setOrgUserId(userId);
504
505     roleInAppForUserList.removeIf(role -> role.getIsApplied().equals(false));
506     SortedSet<Role> roles = new TreeSet<>();
507
508     List<FnRole> getAppRoles = fnRoleService.getAppRoles(app.getId());
509     List<FnApp> appList = new ArrayList<>();
510     appList.add(app);
511     List<CentralV2Role> roleList = new ArrayList<>();
512
513     List<FnRole> userRoles = new ArrayList<>();
514
515     for (RoleInAppForUser roleInappForUser : roleInAppForUserList) {
516       FnRole role = new FnRole();
517       role.setId(roleInappForUser.getRoleId());
518       role.setRoleName(roleInappForUser.getRoleName());
519       userRoles.add(role);
520     }
521
522     if (appRoleIdUsed) {
523       List<FnRole> userAppRoles = new ArrayList<>();
524       for (FnRole role : userRoles) {
525         FnRole appRole = getAppRoles.stream()
526             .filter(applicationRole -> role.getId().equals(applicationRole.getAppRoleId())).findAny()
527             .orElse(null);
528         FnRole epRole = new FnRole();
529         if (appRole != null) {
530           epRole.setId(appRole.getId());
531           epRole.setRoleName(appRole.getRoleName());
532         }
533         userAppRoles.add(epRole);
534       }
535       userRoles = new ArrayList<>(userAppRoles);
536     }
537     roleList = externalAccessRolesService.createCentralRoleObject(appList, userRoles, roleList);
538
539     for (CentralV2Role epRole : roleList) {
540       Role role = new Role();
541       FnRole appRole = getAppRoles.stream()
542           .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null);
543       if (appRole != null) {
544         role.setId(appRole.getAppRoleId());
545         role.setRoleName(epRole.getName());
546         role.setFnRoleFunctions(epRole.getRoleFunctions());
547       }
548       roles.add(role);
549     }
550     client.setRoles(roles.stream().map(this::roleToFnRole).collect(Collectors.toSet()));
551     String userInString;
552     userInString = mapper.writerFor(FnUser.class).writeValueAsString(client);
553     logger.debug(EELFLoggerDelegate.debugLogger,
554         "about to post a client to remote application, users json = " + userInString);
555     applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user/%s", userId));
556   }
557
558   private FnRole roleToFnRole(Role role) {
559     return FnRole.builder()
560         .id(role.getId())
561         .roleName(role.getRoleName())
562         .activeYn(role.getActiveYn())
563         .priority(role.getPriority())
564         .fnRoleFunctions(role.getFnRoleFunctions())
565         .childRoles(role.getChildRoles())
566         .parentRoles(role.getParentRoles())
567         .build();
568   }
569
570   private Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
571       ApplicationsRestClientService applicationsRestClientService, Long appId, String userId)
572       throws JsonProcessingException, HTTPException {
573     Set<EcompRole> updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList);
574     Set<EcompRole> updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList);
575     String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote);
576     FnApp externalApp;
577     externalApp = appsCacheService.getApp(appId);
578     String appBaseUri = null;
579     Set<RemoteRoleV1> updatedUserRolesinRemoteV1 = new TreeSet<>();
580     if (externalApp != null) {
581       appBaseUri = externalApp.getAppRestEndpoint();
582     }
583     if (appBaseUri != null && appBaseUri.endsWith("/api")) {
584       for (EcompRole eprole : updatedUserRolesinRemote) {
585         RemoteRoleV1 role = new RemoteRoleV1();
586         role.setId(eprole.getId());
587         role.setName(eprole.getName());
588         updatedUserRolesinRemoteV1.add(role);
589       }
590       userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1);
591     }
592     applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString,
593         String.format("/user/%s/roles", userId));
594     return updateUserRolesInEcomp;
595   }
596
597   private void addRemoteUser(List<RoleInAppForUser> roleInAppForUserList, String userId, FnApp app,
598       ObjectMapper mapper, ApplicationsRestClientService applicationsRestClientService) throws Exception {
599     if (remoteUserShouldBeCreated(roleInAppForUserList)) {
600       createNewUserOnRemoteApp(userId, app, applicationsRestClientService, mapper);
601     }
602   }
603
604   private void createNewUserOnRemoteApp(String userId, FnApp app,
605       ApplicationsRestClientService applicationsRestClientService, ObjectMapper mapper)
606       throws Exception {
607
608     FnUser client = fnUserService.loadUserByUsername(userId);
609
610     mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
611
612     if (client == null) {
613       String msg = "cannot create user " + userId + ", because he/she cannot be found in phonebook.";
614       logger.error(EELFLoggerDelegate.errorLogger, msg);
615       throw new Exception(msg);
616     }
617
618     client.setLoginId(userId);
619     client.setActiveYn(true);
620
621     String userInString;
622     userInString = mapper.writerFor(FnUser.class).writeValueAsString(client);
623     logger.debug(EELFLoggerDelegate.debugLogger,
624         "about to post new client to remote application, users json = " + userInString);
625     applicationsRestClientService.post(FnUser.class, app.getId(), userInString, String.format("/user", userId));
626
627   }
628
629   private boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
630     for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
631       if (roleInAppForUser.getIsApplied()) {
632         return true;
633       }
634     }
635     return false;
636   }
637
638   private Set<EcompRole> constructUsersRemoteAppRoles(List<RoleInAppForUser> roleInAppForUserList) {
639     Set<EcompRole> existingUserRoles = new TreeSet<>();
640     for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
641       if (roleInAppForUser.getIsApplied() && !roleInAppForUser.getRoleId()
642           .equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
643         EcompRole ecompRole = new EcompRole();
644         ecompRole.setId(roleInAppForUser.getRoleId());
645         ecompRole.setName(roleInAppForUser.getRoleName());
646         existingUserRoles.add(ecompRole);
647       }
648     }
649     return existingUserRoles;
650   }
651
652   private void applyChangesToUserAppRolesForMyLoginsRequest(FnUser user, Long appId) {
653     List<EpUserRolesRequest> epRequestIdVal;
654     try {
655       epRequestIdVal = epUserRolesRequestService.userAppRolesRequestList(user.getId(), appId);
656       if (epRequestIdVal.size() > 0) {
657         EpUserRolesRequest epAppRolesRequestData = epRequestIdVal.get(0);
658         epAppRolesRequestData.setUpdatedDate(LocalDateTime.now());
659         epAppRolesRequestData.setRequestStatus("O");
660         epAppRolesRequestData.setUserId(user);
661         epUserRolesRequestService.saveOne(epAppRolesRequestData);
662         List<EpUserRolesRequestDet> epUserAppRolesDetailList = epUserRolesRequestDetService
663             .appRolesRequestDetailList(epAppRolesRequestData.getReqId());
664         if (epUserAppRolesDetailList.size() > 0) {
665           for (EpUserRolesRequestDet epRequestUpdateList : epUserAppRolesDetailList) {
666             epRequestUpdateList.setRequestType("O");
667             epRequestUpdateList.setReqId(epAppRolesRequestData);
668             epRequestUpdateList.setReqId(epAppRolesRequestData);
669             epUserRolesRequestDetService.saveOne(epRequestUpdateList);
670           }
671           logger.debug(EELFLoggerDelegate.debugLogger,
672               "User App roles request from User Page is overridden");
673         }
674       }
675
676     } catch (Exception e) {
677       logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToUserAppRolesRequest failed", e);
678     }
679   }
680
681   private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList) {
682     return constructUsersEcompRoles(roleInAppForUserList);
683   }
684
685   private Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
686     Set<EcompRole> existingUserRoles = new TreeSet<>();
687     for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
688       if (roleInAppForUser.getIsApplied()) {
689         EcompRole ecompRole = new EcompRole();
690         ecompRole.setId(roleInAppForUser.getRoleId());
691         ecompRole.setName(roleInAppForUser.getRoleName());
692         existingUserRoles.add(ecompRole);
693       }
694     }
695     return existingUserRoles;
696   }
697
698   public RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
699       Set<EcompRole> userRolesInRemoteApp) {
700     RolesInAppForUser result;
701     result = new RolesInAppForUser();
702     result.setAppId(appId);
703     result.setOrgUserId(userId);
704
705     for (EcompRole role : userRolesInRemoteApp) {
706       RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
707       roleInAppForUser.setRoleId(role.getId());
708       roleInAppForUser.setRoleName(role.getName());
709       roleInAppForUser.setIsApplied(true);
710       result.getRoles().add(roleInAppForUser);
711     }
712     return result;
713   }
714
715   private void updateUserRolesInExternalSystem(FnApp app, String orgUserId, List<RoleInAppForUser> roleInAppUser,
716       boolean isPortalRequest, boolean isSystemUser, Set<EcompRole> deletedRolesByApprover,
717       boolean isLoggedInUserRoleAdminofApp) throws Exception {
718     try {
719       List<FnUser> userInfo = checkIfUserExists(orgUserId);
720       if (userInfo.isEmpty()) {
721         createLocalUserIfNecessary(orgUserId, isSystemUser);
722       }
723       String name;
724       if (EPCommonSystemProperties
725           .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
726           && !isSystemUser) {
727         name = orgUserId
728             + SystemProperties
729             .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
730       } else {
731         name = orgUserId;
732       }
733       ObjectMapper mapper = new ObjectMapper();
734       HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
735       HttpEntity<String> getUserRolesEntity = new HttpEntity<>(headers);
736       ResponseEntity<String> getResponse = externalAccessRolesService
737           .getUserRolesFromExtAuthSystem(name, getUserRolesEntity);
738
739       List<ExternalAccessUserRoleDetail> userRoleDetailList = new ArrayList<>();
740       String res = getResponse.getBody();
741       JSONObject jsonObj;
742       JSONArray extRoles = null;
743       if (!res.equals("{}")) {
744         jsonObj = new JSONObject(res);
745         extRoles = jsonObj.getJSONArray("role");
746       }
747       ExternalAccessUserRoleDetail userRoleDetail;
748       if (extRoles != null) {
749         for (int i = 0; i < extRoles.length(); i++) {
750           if (extRoles.getJSONObject(i).getString("name").startsWith(app.getAuthNamespace() + ".")
751               && !extRoles.getJSONObject(i).getString("name")
752               .equals(app.getAuthNamespace() + ".admin")
753               && !extRoles.getJSONObject(i).getString("name")
754               .equals(app.getAuthNamespace() + ".owner")) {
755             if (extRoles.getJSONObject(i).has("description")) {
756               ExternalRoleDescription desc = new ExternalRoleDescription(
757                   extRoles.getJSONObject(i).getString("description"));
758               userRoleDetail = new ExternalAccessUserRoleDetail(
759                   extRoles.getJSONObject(i).getString("name"), desc);
760               userRoleDetailList.add(userRoleDetail);
761             } else {
762               userRoleDetail = new ExternalAccessUserRoleDetail(
763                   extRoles.getJSONObject(i).getString("name"), null);
764               userRoleDetailList.add(userRoleDetail);
765             }
766
767           }
768         }
769       }
770
771       List<ExternalAccessUserRoleDetail> userRoleListMatchingInExtAuthAndLocal = checkIfRoleAreMatchingInUserRoleDetailList(
772           userRoleDetailList, app);
773
774       List<EcompUserAppRoles> userAppList;
775       // If request coming from portal not from external role approval system then we have to check if user already
776       // have account admin or system admin as GUI will not send these roles
777       if (!isPortalRequest) {
778         FnUser user = fnUserService.getUserWithOrgUserId(orgUserId).get(0);
779         userAppList = ecompUserAppRolesService.getUserAppExistingRoles(app.getId(), user.getId());
780         if (!roleInAppUser.isEmpty()) {
781           for (EcompUserAppRoles userApp : userAppList) {
782             if (userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)
783                 || userApp.getRoleId()
784                 .equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) {
785               RoleInAppForUser addSpecialRole = new RoleInAppForUser();
786               addSpecialRole.setIsApplied(true);
787               addSpecialRole.setRoleId(userApp.getRoleId());
788               addSpecialRole.setRoleName(userApp.getRoleName());
789               roleInAppUser.add(addSpecialRole);
790             }
791           }
792         }
793       }
794       List<RoleInAppForUser> roleInAppUserNonDupls = roleInAppUser.stream().distinct()
795           .collect(Collectors.toList());
796       Map<String, RoleInAppForUser> currentUserRolesToUpdate = new HashMap<>();
797       for (RoleInAppForUser roleInAppUserNew : roleInAppUserNonDupls) {
798         currentUserRolesToUpdate.put(roleInAppUserNew.getRoleName()
799             .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
800                 "_"), roleInAppUserNew);
801       }
802       final Map<String, ExternalAccessUserRoleDetail> currentUserRolesInExternalSystem = new HashMap<>();
803       for (ExternalAccessUserRoleDetail extAccessUserRole : userRoleListMatchingInExtAuthAndLocal) {
804         currentUserRolesInExternalSystem.put(extAccessUserRole.getName(), extAccessUserRole);
805       }
806
807       if (isLoggedInUserRoleAdminofApp) {
808         if (deletedRolesByApprover.size() > 0) {
809           List<ExternalAccessUserRoleDetail> newUpdatedRoles = new ArrayList<>();
810           for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
811             for (EcompRole role : deletedRolesByApprover) {
812               if ((userRole.getName().substring(app.getAuthNamespace().length() + 1))
813                   .equals(role.getName())) {
814                 newUpdatedRoles.add(userRole);
815               }
816             }
817           }
818           if (newUpdatedRoles.size() > 0) {
819             userRoleListMatchingInExtAuthAndLocal = new ArrayList<>(newUpdatedRoles);
820           } else {
821             userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
822             currentUserRolesToUpdate = new HashMap<>();
823
824           }
825
826         } else {
827           userRoleListMatchingInExtAuthAndLocal = new ArrayList<>();
828           currentUserRolesToUpdate = new HashMap<>();
829
830         }
831       }
832
833       // Check if user roles does not exists in local but still there in External Central Auth System delete them all
834       for (ExternalAccessUserRoleDetail userRole : userRoleListMatchingInExtAuthAndLocal) {
835         if (!(currentUserRolesToUpdate
836             .containsKey(userRole.getName().substring(app.getAuthNamespace().length() + 1)))) {
837           HttpEntity<String> entity = new HttpEntity<>(headers);
838           logger.debug(EELFLoggerDelegate.debugLogger,
839               "updateUserRolesInExternalSystem: Connecting to external system to DELETE user role {}",
840               userRole.getName());
841           ResponseEntity<String> deleteResponse = template.exchange(
842               SystemProperties
843                   .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
844                   + "userRole/" + name + "/" + userRole.getName(),
845               HttpMethod.DELETE, entity, String.class);
846           logger.debug(EELFLoggerDelegate.debugLogger,
847               "updateUserRolesInExternalSystem: Finished DELETE operation in external system for user role {} and the response is {}",
848               userRole.getName(), deleteResponse.getBody());
849         }
850       }
851       // Check if user roles does not exists in External Central Auth System add them all
852       for (RoleInAppForUser addUserRole : roleInAppUserNonDupls) {
853         if (!(currentUserRolesInExternalSystem
854             .containsKey(app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll(
855                 EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
856                 "_")))) {
857           ExternalAccessUser extUser = new ExternalAccessUser(name,
858               app.getAuthNamespace() + "." + addUserRole.getRoleName().replaceAll(
859                   EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
860                   "_"));
861           String formattedUserRole = mapper.writeValueAsString(extUser);
862           HttpEntity<String> entity = new HttpEntity<>(formattedUserRole, headers);
863           logger.debug(EELFLoggerDelegate.debugLogger,
864               "updateUserRolesInExternalSystem: Connecting to external system for user {} and POST {}",
865               name, addUserRole.getRoleName());
866           ResponseEntity<String> addResponse = template
867               .exchange(SystemProperties
868                   .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
869                   + "userRole", HttpMethod.POST, entity, String.class);
870           logger.debug(EELFLoggerDelegate.debugLogger,
871               "updateUserRolesInExternalSystem: Finished adding user role in external system {} and added user role {}",
872               addResponse.getBody(), addUserRole.getRoleName());
873           if (addResponse.getStatusCode().value() != 201
874               && addResponse.getStatusCode().value() != 404) {
875             logger.debug(EELFLoggerDelegate.debugLogger,
876                 "Finished POST operation in external system but unable to save user role",
877                 addResponse.getBody(),
878                 addUserRole.getRoleName());
879             throw new Exception(addResponse.getBody());
880           }
881         }
882       }
883     } catch (HttpClientErrorException e) {
884       logger.error(EELFLoggerDelegate.errorLogger,
885           "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
886           app.getId(), e);
887       if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
888         logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid systemUser",
889             orgUserId);
890         throw new HttpClientErrorException(HttpStatus.FORBIDDEN,
891             "Please enter the valid systemUser");
892       }
893       if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
894         logger.error(EELFLoggerDelegate.errorLogger, "Please enter the valid role");
895         throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Please enter the valid role");
896       }
897       EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
898       throw e;
899     } catch (Exception e) {
900       logger.error(EELFLoggerDelegate.errorLogger,
901           "updateUserRolesInExternalSystem: Failed to add user role for application {} due to {}",
902           app.getId(), e);
903       EPLogUtil.logExternalAuthAccessAlarm(logger, HttpStatus.BAD_REQUEST);
904       throw e;
905     }
906   }
907
908   private List<ExternalAccessUserRoleDetail> checkIfRoleAreMatchingInUserRoleDetailList(
909       List<ExternalAccessUserRoleDetail> userRoleDetailList, FnApp app) {
910     Map<String, FnRole> epRoleList = externalAccessRolesService.getAppRoleNamesWithUnderscoreMap(app);
911     //Add Account Admin role for partner app to prevent conflict
912     if (!PortalConstants.PORTAL_APP_ID.equals(app.getId())) {
913       FnRole role = new FnRole();
914       role.setRoleName(PortalConstants.ADMIN_ROLE
915           .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
916       epRoleList.put(role.getRoleName(), role);
917     }
918     userRoleDetailList.removeIf(
919         userRoleDetail -> !epRoleList
920             .containsKey(userRoleDetail.getName().substring(app.getAuthNamespace().length() + 1)));
921     return userRoleDetailList;
922   }
923
924   private List<FnUser> checkIfUserExists(String userParams) {
925     return fnUserService.getUserWithOrgUserId(userParams);
926   }
927
928   @Transactional
929   private void createLocalUserIfNecessary(String userId, boolean isSystemUser) {
930     if (StringUtils.isEmpty(userId)) {
931       logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty userId!");
932       return;
933     }
934     try {
935       List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
936       if (userList.size() == 0) {
937         FnUser client;
938         if (!isSystemUser) {
939           client = fnUserService.loadUserByUsername(userId);
940         } else {
941           client = new FnUser();
942           client.setOrgUserId(userId);
943           client.setIsSystemUser(true);
944           client.setFirstName(userId.substring(0, userId.indexOf("@")));
945         }
946         if (client == null) {
947           String msg = "createLocalUserIfNecessary: cannot create user " + userId
948               + ", because not found in phonebook";
949           logger.error(EELFLoggerDelegate.errorLogger, msg);
950         } else {
951           client.setLoginId(userId);
952           client.setActiveYn(true);
953         }
954         fnUserService.saveFnUser(client);
955       }
956     } catch (Exception e) {
957       EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
958     }
959
960   }
961
962   private FnUser checkIfRemoteUserExits(String userId, FnApp app,
963       ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
964     FnUser checkRemoteUser = null;
965     try {
966       checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService);
967     } catch (HTTPException e) {
968       // Some apps are returning 400 if user is not found.
969       if (e.getResponseCode() == 400) {
970         logger.debug(EELFLoggerDelegate.debugLogger,
971             "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing",
972             e);
973       } else if (e.getResponseCode() == 404) {
974         logger.debug(EELFLoggerDelegate.debugLogger,
975             "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing",
976             e);
977       } else {
978         // Other response code, let it come thru.
979         throw e;
980       }
981     }
982     return checkRemoteUser;
983   }
984
985   private FnUser getUserFromApp(String userId, FnApp app, ApplicationsRestClientService applicationsRestClientService)
986       throws HTTPException {
987     if (PortalConstants.PORTAL_APP_ID.equals(app.getId())) {
988       List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
989       if (userList != null && !userList.isEmpty()) {
990         return userList.get(0);
991       } else {
992         return null;
993       }
994     }
995     return getUser(userId, app, applicationsRestClientService);
996   }
997
998   private boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser,
999       boolean externalSystemRequest, String reqType, boolean isSystemUser,
1000       Set<EcompRole> rolesDeletedByApprover, boolean isLoggedInUserRoleAdminOfApp) throws Exception {
1001     boolean result = false;
1002     String userId = rolesInAppForUser.getOrgUserId();
1003     Long appId = rolesInAppForUser.getAppId();
1004     synchronized (syncRests) {
1005       createLocalUserIfNecessary(userId, isSystemUser);
1006
1007       EcompRole[] userAppRoles = new EcompRole[(int) rolesInAppForUser.getRoles().stream().distinct().count()];
1008       for (int i = 0;
1009           i < rolesInAppForUser.getRoles().stream().distinct().count(); i++) {
1010         RoleInAppForUser roleInAppForUser = rolesInAppForUser.getRoles().get(i);
1011         EcompRole role = new EcompRole();
1012         role.setId(roleInAppForUser.getRoleId());
1013         role.setName(roleInAppForUser.getRoleName());
1014         userAppRoles[i] = role;
1015       }
1016       try {
1017         EcompRole[] applicationRoles = null;
1018
1019         if (isLoggedInUserRoleAdminOfApp) {
1020           List<EcompRole> roles = Arrays.stream(userAppRoles)
1021               .collect(Collectors.toList());
1022           List<EcompRole> roles1 = new ArrayList<>(rolesDeletedByApprover);
1023           roles.addAll(roles1);
1024           applicationRoles = roles.toArray(new EcompRole[0]);
1025         }
1026
1027         syncUserRoles(userId, appId, userAppRoles, externalSystemRequest,
1028             reqType, isLoggedInUserRoleAdminOfApp, applicationRoles);
1029         result = true;
1030       } catch (Exception e) {
1031         logger.error(EELFLoggerDelegate.errorLogger,
1032             "applyChangesInUserRolesForAppToEcompDB: failed to syncUserRoles for orgUserId "
1033                 + userId, e);
1034         if ("DELETE".equals(reqType)) {
1035           throw new Exception(e.getMessage());
1036         }
1037       }
1038     }
1039     return result;
1040   }
1041
1042   private void syncUserRoles(String userId, Long appId,
1043       EcompRole[] userAppRoles, Boolean extRequestValue, String reqType, boolean checkIfUserisRoleAdmin,
1044       EcompRole[] appRoles) throws Exception {
1045
1046     Transaction transaction = null;
1047     String roleActive;
1048     HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
1049     List<FnRole> roleInfo = externalAccessRolesService
1050         .getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
1051     FnRole adminRole = new FnRole();
1052     if (roleInfo.size() > 0) {
1053       adminRole = roleInfo.get(0);
1054       logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getRoleName());
1055     }
1056     try {
1057       List<FnUser> userList = fnUserService.getUserWithOrgUserId(userId);
1058       if (userList.size() > 0) {
1059         FnUser client = userList.get(0);
1060         roleActive = ("DELETE".equals(reqType)) ? "" : " and role.active = 'Y'";
1061         List<FnUserRole> userRoles = fnUserRoleService.retrieveByAppIdAndUserId(appId, userId);
1062         entityManager
1063             .createQuery("from EPUserApp where app.id=:appId and userId=:userId" + roleActive)
1064             .setParameter("appId", appId)
1065             .setParameter("userId", client.getId())
1066             .getResultList();
1067
1068         if ("DELETE".equals(reqType)) {
1069           for (FnUserRole userAppRoleList : userRoles) {
1070             List<FnRole> rolesList =
1071                 (!userAppRoleList.getRoleId().getRoleName()
1072                     .equals(adminRole.getRoleName()))
1073                     ? fnRoleService.retrieveAppRolesByRoleNameAndByAppId
1074                     (userAppRoleList.getRoleId().getRoleName(), appId)
1075                     : fnRoleService.retrieveAppRolesWhereAppIdIsNull();
1076             if (!rolesList.isEmpty()) {
1077               checkIfRoleInactive(rolesList.get(0));
1078             }
1079           }
1080         }
1081
1082         if (appRoles != null) {
1083           List<EcompRole> appRolesList = Arrays.stream(appRoles).collect(Collectors.toList());
1084           List<FnUserRole> finalUserRolesList = new ArrayList<>();
1085           if (checkIfUserisRoleAdmin) {
1086             for (EcompRole role : appRolesList) {
1087               for (FnUserRole userAppRoleList : userRoles) {
1088                 if (userAppRoleList.getRoleId().getRoleName()
1089                     .equals(role.getName())) {
1090                   finalUserRolesList.add(userAppRoleList);
1091                 }
1092
1093               }
1094             }
1095             userRoles = new ArrayList<>(finalUserRolesList);
1096           }
1097         }
1098
1099         for (FnUserRole userRole : userRoles) {
1100           if (!PortalConstants.ACCOUNT_ADMIN_ROLE_ID.equals(userRole.getRoleId().getId())
1101               && !PortalConstants.SYS_ADMIN_ROLE_ID
1102               .equals(userRole.getRoleId().getId())
1103               && !extRequestValue) {
1104             syncUserRolesExtension(userRole, appId,
1105                 newUserAppRolesMap);
1106           } else if (extRequestValue && ("PUT".equals(reqType) || "POST".equals(reqType)
1107               || "DELETE".equals(reqType))) {
1108             syncUserRolesExtension(userRole, appId,
1109                 newUserAppRolesMap);
1110           } else if (extRequestValue && !PortalConstants.ACCOUNT_ADMIN_ROLE_ID
1111               .equals(userRole.getRoleId().getId())) {
1112             syncUserRolesExtension(userRole, appId,
1113                 newUserAppRolesMap);
1114           }
1115         }
1116
1117         Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
1118         if (newRolesToAdd.size() > 0) {
1119           FnApp app = fnAppService.getById(appId);
1120
1121           HashMap<Long, FnRole> rolesMap = new HashMap<>();
1122           if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app
1123             String appIdValue = "";
1124             if (!extRequestValue) {
1125               appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID;
1126             }
1127             @SuppressWarnings("unchecked")
1128             List<FnRole> roles = entityManager
1129                 .createQuery(
1130                     "from " + FnRole.class.getName() + " where appId is null "
1131                         + appIdValue).getResultList();
1132             for (FnRole role : roles) {
1133               role.setAppId(1L);
1134               rolesMap.put(role.getId(), role);
1135             }
1136           } else { // remote app
1137             @SuppressWarnings("unchecked")
1138             List<FnRole> roles = entityManager
1139                 .createQuery("from EPRole where appId=:appId")
1140                 .setParameter("appId", appId)
1141                 .getResultList();
1142             for (FnRole role : roles) {
1143               if (!extRequestValue && app.getAuthCentral()) {
1144                 rolesMap.put(role.getId(), role);
1145               } else {
1146                 rolesMap.put(role.getAppRoleId(), role);
1147               }
1148             }
1149           }
1150
1151           FnRole role;
1152           for (EcompRole userRole : newRolesToAdd) {
1153             FnUserRole userApp = new FnUserRole();
1154             if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName()
1155                 .equals(adminRole.getRoleName())) {
1156               role = fnRoleService.getById(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
1157               userApp.setRoleId(role);
1158             } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID))
1159                 && !extRequestValue) {
1160               continue;
1161             } else if ((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app
1162                 .getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue) {
1163               continue;
1164             } else {
1165               userApp.setRoleId(rolesMap.get(userRole.getId()));
1166             }
1167
1168             userApp.setUserId(client);
1169             userApp.setFnAppId(app);
1170             fnUserRoleService.saveOne(userApp);
1171           }
1172
1173           if (PortalConstants.PORTAL_APP_ID.equals(appId)) {
1174             /*
1175              * for local app -- hack - always make sure fn_role
1176              * table's app_id is null and not 1 for primary app in
1177              * this case being onap portal app; reason: hibernate
1178              * is rightly setting this to 1 while persisting to
1179              * fn_role as per the mapping but SDK role management
1180              * code expects the app_id to be null as there is no
1181              * concept of App_id in SDK
1182              */
1183             Query query = entityManager.createQuery("update fn_role set app_id = null where app_id = 1 ");
1184             query.executeUpdate();
1185           }
1186         }
1187       }
1188       transaction.commit();
1189     } catch (Exception e) {
1190       logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e);
1191       EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1192       EcompPortalUtils.rollbackTransaction(transaction,
1193           "Exception occurred in syncUserRoles, Details: " + e.toString());
1194       if ("DELETE".equals(reqType)) {
1195         throw new SyncUserRolesException(e.getMessage());
1196       }
1197     }
1198   }
1199
1200   private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
1201     HashMap<Long, EcompRole> result = new HashMap<>();
1202     if (ecompRoles != null) {
1203       for (EcompRole ecompRole : ecompRoles) {
1204         if (ecompRole.getId() != null) {
1205           result.put(ecompRole.getId(), ecompRole);
1206         }
1207       }
1208     }
1209     return result;
1210   }
1211
1212   private void syncUserRolesExtension(FnUserRole userRole, Long appId,
1213       HashMap<Long, EcompRole> newUserAppRolesMap) {
1214
1215     Long userAppRoleId;
1216     if (PortalConstants.PORTAL_APP_ID.equals(appId)) { // local app
1217       userAppRoleId = userRole.getRoleId().getId();
1218     } else { // remote app
1219       userAppRoleId = userRole.getId();
1220     }
1221
1222     if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
1223       fnUserRoleService.deleteById(userRole.getId());
1224     } else {
1225       newUserAppRolesMap.remove(userAppRoleId);
1226     }
1227   }
1228
1229   private Role fnRoleToRole(final FnRole role) {
1230     return new Role(null, null, null, null, null, null, null, null, null, role.getRoleName(), null, role.getActiveYn(),
1231         role.getPriority(), role.getFnRoleFunctions(), role.getChildRoles(), role.getParentRoles());
1232   }
1233
1234   @SuppressWarnings("unchecked")
1235   public List<RoleInAppForUser> getAppRolesForUser(Long appId, String orgUserId, Boolean extRequestValue, Long userId) {
1236     List<RoleInAppForUser> rolesInAppForUser = null;
1237     FnApp app = fnAppService.getById(appId);
1238     logger.debug(EELFLoggerDelegate.debugLogger, "In getAppRolesForUser() - app = {}", app);
1239     try {
1240       // for onap portal app, no need to make a remote call
1241       List<Role> roleList = new ArrayList<>();
1242       if (!PortalConstants.PORTAL_APP_ID.equals(appId)) {
1243         if (app.getAuthCentral()) {
1244           List<CentralV2Role> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey());
1245           for (CentralV2Role cenRole : cenRoleList) {
1246             Role role = new Role();
1247             role.setActiveYn(cenRole.isActive());
1248             role.setId(cenRole.getId());
1249             role.setRoleName(cenRole.getName());
1250             role.setPriority(cenRole.getPriority());
1251             roleList.add(role);
1252           }
1253         } else {
1254           Optional<FnUser> user = fnUserService.getUser(userId);
1255           if (user.isPresent()) {
1256             roleList = user.get().getFnRoles().stream().map(this::fnRoleToRole).collect(Collectors.toList());
1257           }
1258         }
1259         List<Role> activeRoleList = new ArrayList<>();
1260         for (Role role : roleList) {
1261           if (role.getActiveYn()) {
1262             if (role.getId() != 1) { // prevent portal admin from being added
1263               activeRoleList.add(role);
1264             } else if (extRequestValue) {
1265               activeRoleList.add(role);
1266             }
1267           }
1268
1269         }
1270         FnUser localUser = getUserFromApp(Long.toString(userId), app, applicationsRestClientService);
1271         // If localUser does not exists return roles
1272         Set<FnRole> roleSet = null;
1273         FnRole[] roleSetList = null;
1274         if (localUser != null) {
1275           roleSet = localUser.getAppEPRoles(app);
1276           roleSetList = roleSet.toArray(new FnRole[0]);
1277         }
1278         rolesInAppForUser = fnUserRoleService
1279             .constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue);
1280         return rolesInAppForUser;
1281       }
1282
1283       EcompRole[] appRoles = null;
1284       boolean checkIfUserIsApplicationAccAdmin = false;
1285       List<EcompRole> roles = new ArrayList<>();
1286       if (app.getAuthCentral()) {
1287         List<FnRole> applicationRoles = fnRoleService.retrieveActiveRolesOfApplication(app.getId());
1288         FnApp application = fnAppService.getById(appId);
1289         checkIfUserIsApplicationAccAdmin = isAccountAdminOfApplication(userId,
1290             application);
1291
1292         List<FnRole> roleSetWithFunctioncds = new ArrayList<>();
1293         for (FnRole role : applicationRoles) {
1294           List<EpAppFunction> cenRoleFuncList = epAppFunctionService.getAppRoleFunctionList(role.getId(), app.getId());
1295           for (EpAppFunction roleFunc : cenRoleFuncList) {
1296
1297             String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
1298             functionCode = EPUserUtils.decodeFunctionCode(functionCode);
1299             String type = externalAccessRolesService.getFunctionCodeType(roleFunc.getFunctionCd());
1300             String action = externalAccessRolesService.getFunctionCodeAction(roleFunc.getFunctionCd());
1301             String name = roleFunc.getFunctionName();
1302
1303             FnFunction function = new FnFunction();
1304             function.setAction(action);
1305             function.setType(type);
1306             function.setCode(functionCode);
1307             function.setName(name);
1308             role.getFnRoleFunctions().add(new FnRoleFunction(role, function));
1309
1310           }
1311           roleSetWithFunctioncds.add(role);
1312
1313
1314         }
1315
1316         for (FnRole role1 : roleSetWithFunctioncds) {
1317           EcompRole ecompRole = new EcompRole();
1318           ecompRole.setId(role1.getId());
1319           ecompRole.setName(role1.getRoleName());
1320           ecompRole.setRoleFunctions(role1.getRoleFunctions());
1321           roles.add(ecompRole);
1322
1323         }
1324         if (checkIfUserIsApplicationAccAdmin) {
1325           appRoles = roles.toArray(new EcompRole[roles.size()]);
1326           logger.debug(EELFLoggerDelegate.debugLogger,
1327               "In getAppRolesForUser() If Logged in user checkIfUserisApplicationAccAdmin- appRoles = {}", appRoles);
1328         } else if (isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin) {
1329           List<EcompRole> roleAdminAppRoles = new ArrayList<>();
1330           List<String> roleAdminAppRolesNames = new ArrayList<>();
1331           String QUERY =
1332               "select distinct fr.role_name as roleName from fn_user_role fu, ep_app_role_function ep, ep_app_function ea, fn_role fr"
1333                   + " where fu.role_id = ep.role_id"
1334                   + " and fu.app_id = ep.app_id"
1335                   + " and fu.user_id = :userId"
1336                   + " and fu.role_id = fr.role_id and fr.active_yn='Y'"
1337                   + " and ea.function_cd = ep.function_cd and ea.function_cd like 'approver|%'"
1338                   + " and exists"
1339                   + " ("
1340                   + " select fa.app_id from fn_user fu, fn_user_role ur, fn_app fa where fu.user_id =:userId and fu.user_id = ur.user_id"
1341                   + " and ur.app_id = fa.app_id and fa.enabled = 'Y')";
1342           List<Tuple> tuples = entityManager.createNativeQuery(QUERY, Tuple.class)
1343               .setParameter("userId", userId)
1344               .getResultList();
1345           List<String> getUserApproverRoles = tuples.stream().map(tuple -> (String) tuple.get("roleName"))
1346               .collect(Collectors.toList());
1347
1348           List<EcompRole> userapproverRolesList = new ArrayList<>();
1349           for (String str : getUserApproverRoles) {
1350             EcompRole epRole = roles.stream().filter(x -> str.equals(x.getName())).findAny().orElse(null);
1351             if (epRole != null) {
1352               userapproverRolesList.add(epRole);
1353             }
1354           }
1355           for (EcompRole role : userapproverRolesList) {
1356
1357             List<RoleFunction> roleFunList = new ArrayList<>(role.getRoleFunctions());
1358             boolean checkIfFunctionsExits = roleFunList.stream()
1359                 .anyMatch(roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1360             if (checkIfFunctionsExits) {
1361               roleAdminAppRoles.add(role);
1362               List<RoleFunction> filteredList = roleFunList.stream()
1363                   .filter(x -> "Approver".equalsIgnoreCase(x.getType())).collect(Collectors.toList());
1364               roleAdminAppRolesNames.addAll(filteredList.stream().map(RoleFunction::getCode)
1365                   .collect(Collectors.toList()));
1366             }
1367           }
1368           for (String name : roleAdminAppRolesNames) {
1369             roles.stream().filter(x -> name.equals(x.getName())).findAny().ifPresent(roleAdminAppRoles::add);
1370
1371           }
1372           appRoles = roleAdminAppRoles.toArray(new EcompRole[0]);
1373
1374         }
1375       } else {
1376         appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
1377       }
1378       // Test this error case, for generating an internal ONAP Portal
1379       // error
1380       // EcompRole[] appRoles = null;
1381       // If there is an exception in the rest client api, then null will
1382       // be returned.
1383       if (appRoles != null) {
1384         if (!app.getAuthCentral()) {
1385           syncAppRoles(appId, appRoles);
1386         }
1387         EcompRole[] userAppRoles = null;
1388         try {
1389           try {
1390             if (app.getAuthCentral()) {
1391               List<FnUser> actualUser = fnUserService.getUserWithOrgUserId(Long.toString(userId));
1392               List<EPUserAppCurrentRoles> userAppsRolesList = entityManager
1393                   .createNamedQuery("EPUserAppCurrentRoles")
1394                   .setParameter("appId", app.getId())
1395                   .setParameter("userId", actualUser.get(0).getId())
1396                   .getResultList();
1397               List<EcompRole> setUserRoles = new ArrayList<>();
1398               for (EPUserAppCurrentRoles role : userAppsRolesList) {
1399                 logger.debug(EELFLoggerDelegate.debugLogger,
1400                     "In getAppRolesForUser() - userAppsRolesList get userRolename = {}", role.getRoleName());
1401                 EcompRole ecompRole = new EcompRole();
1402                 ecompRole.setId(role.getRoleId());
1403                 ecompRole.setName(role.getRoleName());
1404                 setUserRoles.add(ecompRole);
1405               }
1406
1407               boolean checkIfUserisAccAdmin = setUserRoles.stream()
1408                   .anyMatch(ecompRole -> ecompRole.getId() == 999L);
1409
1410               if (!checkIfUserisAccAdmin) {
1411                 List<EcompRole> appRolesList = Arrays.asList(appRoles);
1412                 Set<EcompRole> finalUserAppRolesList = new HashSet<>();
1413
1414                 List<String> roleNames = new ArrayList<>();
1415                 for (EcompRole role : setUserRoles) {
1416                   EcompRole epRole = appRolesList.stream()
1417                       .filter(x -> role.getName().equals(x.getName())).findAny().orElse(null);
1418                   List<RoleFunction> roleFunList = new ArrayList<>();
1419
1420                   if (epRole != null) {
1421                     if (epRole.getRoleFunctions().size() > 0) {
1422                       roleFunList.addAll(epRole.getRoleFunctions());
1423                     }
1424                     boolean checkIfFunctionsExits = roleFunList.stream().anyMatch(
1425                         roleFunction -> roleFunction.getType().equalsIgnoreCase("Approver"));
1426                     if (checkIfFunctionsExits) {
1427                       finalUserAppRolesList.add(role);
1428                       List<RoleFunction> filteredList = roleFunList.stream()
1429                           .filter(x -> "Approver".equalsIgnoreCase(x.getType()))
1430                           .collect(Collectors.toList());
1431                       roleNames = filteredList.stream().map(RoleFunction::getCode)
1432                           .collect(Collectors.toList());
1433                     } else {
1434                       roleNames.add(epRole.getName());
1435                     }
1436                   }
1437                   for (String name : roleNames) {
1438                     EcompRole ecompRole = appRolesList.stream()
1439                         .filter(x -> name.equals(x.getName())).findAny().orElse(null);
1440                     if (ecompRole != null) {
1441                       finalUserAppRolesList.add(ecompRole);
1442                     }
1443                   }
1444                 }
1445                 for (String name : roleNames) {
1446                   boolean checkIfFunctionsExits = userAppsRolesList.stream().anyMatch(
1447                       role -> role.getRoleName().equalsIgnoreCase(name));
1448                   if (checkIfFunctionsExits) {
1449                     appRolesList.stream().filter(x -> name.equals(x.getName()))
1450                         .findAny().ifPresent(setUserRoles::add);
1451                   }
1452                 }
1453                 userAppRoles = setUserRoles.toArray(new EcompRole[0]);
1454               }
1455             } else {
1456               userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId,
1457                   String.format("/user/%s/roles", userId));
1458             }
1459           } catch (HTTPException e) {
1460             // Some apps are returning 400 if user is not found.
1461             if (e.getResponseCode() == 400) {
1462               logger.debug(EELFLoggerDelegate.debugLogger,
1463                   "getAppRolesForUser caught exception with response code 400; continuing", e);
1464             } else {
1465               // Other response code, let it come thru.
1466               throw e;
1467             }
1468           }
1469           if (userAppRoles == null) {
1470             if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
1471               EcompPortalUtils.setExternalAppResponseCode(200);
1472               String message = String.format(
1473                   "getAppRolesForUser: App %s, User %, endpoint /user/{userid}/roles returned 400, "
1474                       + "assuming user doesn't exist, app is framework SDK based, and things are ok. "
1475                       + "Overriding to 200 until framework SDK returns a useful response.",
1476                   Long.toString(appId), userId);
1477               logger.warn(EELFLoggerDelegate.applicationLogger, message);
1478             }
1479           }
1480
1481           HashMap<Long, EcompRole> appRolesActiveMap = hashMapFromEcompRoles(appRoles);
1482           ArrayList<EcompRole> activeRoles = new ArrayList<>();
1483           if (userAppRoles != null) {
1484             for (EcompRole userAppRole : userAppRoles) {
1485               if (appRolesActiveMap.containsKey(userAppRole.getId())) {
1486                 EcompRole role = new EcompRole();
1487                 role.setId(userAppRole.getId());
1488                 role.setName(userAppRole.getName());
1489                 activeRoles.add(role);
1490               }
1491             }
1492           }
1493           EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[0]);
1494
1495           boolean checkIfUserisRoleAdmin = isRoleAdmin(userId) && !checkIfUserIsApplicationAccAdmin;
1496
1497           // If the remote application isn't down we MUST sync user
1498           // roles here in case we have this user here!
1499           syncUserRoles(Long.toString(userId), appId, userAppRolesActive, extRequestValue, null, checkIfUserisRoleAdmin,
1500               appRoles);
1501         } catch (Exception e) {
1502           // TODO: we may need to check if user exists, maybe remote
1503           // app is down.
1504           String message = String.format(
1505               "getAppRolesForUser: user %s does not exist in remote application %s", userId,
1506               Long.toString(appId));
1507           logger.error(EELFLoggerDelegate.errorLogger, message, e);
1508           userAppRoles = new EcompRole[0];
1509         }
1510         rolesInAppForUser = fnUserRoleService.constructRolesInAppForUserGet(appRoles, userAppRoles);
1511       }
1512     } catch (Exception e) {
1513       String message = String.format("getAppRolesForUser: failed for User %s, AppId %s", userId,
1514           Long.toString(appId));
1515       logger.error(EELFLoggerDelegate.errorLogger, message, e);
1516     }
1517     return rolesInAppForUser;
1518   }
1519
1520   private void syncAppRoles(Long appId, EcompRole[] appRoles) throws Exception {
1521     logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId);
1522     HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
1523     try {
1524       List<FnRole> currentAppRoles = fnRoleService.retrieveAppRolesByAppId(appId);
1525
1526       List<FnRole> obsoleteRoles = new ArrayList<>();
1527       for (FnRole oldAppRole : currentAppRoles) {
1528         if (oldAppRole.getAppRoleId() != null) {
1529           EcompRole role;
1530           role = newRolesMap.get(oldAppRole.getAppRoleId());
1531           if (role != null) {
1532             if (!(role.getName() == null || oldAppRole.getRoleName().equals(role.getName()))) {
1533               oldAppRole.setRoleName(role.getName());
1534             }
1535             oldAppRole.setActiveYn(true);
1536             newRolesMap.remove(oldAppRole.getAppRoleId());
1537           } else {
1538             obsoleteRoles.add(oldAppRole);
1539           }
1540         } else {
1541           obsoleteRoles.add(oldAppRole);
1542         }
1543       }
1544       Collection<EcompRole> newRolesToAdd = newRolesMap.values();
1545       if (obsoleteRoles.size() > 0) {
1546         logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: we have obsolete roles to delete");
1547         for (FnRole role : obsoleteRoles) {
1548           logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: obsolete role: " + role.toString());
1549           Long roleId = role.getId();
1550           List<FnUserRole> userRoles = fnUserRoleService.getUserRolesForRoleIdAndAppId(roleId, appId);
1551
1552           logger.debug(EELFLoggerDelegate.debugLogger,
1553               "syncAppRoles: number of userRoles to delete: " + userRoles.size());
1554           for (FnUserRole userRole : userRoles) {
1555             logger.debug(EELFLoggerDelegate.debugLogger,
1556                 "syncAppRoles: about to delete userRole: " + userRole.toString());
1557             fnUserRoleService.deleteById(userRole.getId());
1558             logger.debug(EELFLoggerDelegate.debugLogger,
1559                 "syncAppRoles: finished deleting userRole: " + userRole.toString());
1560           }
1561           List<FnMenuFunctionalRoles> funcMenuRoles = fnMenuFunctionalRolesService.retrieveByroleId(roleId);
1562           int numMenuRoles = funcMenuRoles.size();
1563           logger.debug(EELFLoggerDelegate.debugLogger,
1564               "syncAppRoles: number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles);
1565           for (FnMenuFunctionalRoles funcMenuRole : funcMenuRoles) {
1566             Long menuId = funcMenuRole.getMenuId().getMenuId();
1567             // If this is the only role for this menu item, then the
1568             // app and roles will be gone,
1569             // so must null out the url too, to be consistent
1570             List<FnMenuFunctionalRoles> funcMenuRoles2 = fnMenuFunctionalRolesService.retrieveByMenuId(menuId);
1571             int numMenuRoles2 = funcMenuRoles2.size();
1572             logger.debug(EELFLoggerDelegate.debugLogger,
1573                 "syncAppRoles: number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2);
1574             fnMenuFunctionalRolesService.delete(funcMenuRole);
1575
1576             if (numMenuRoles2 == 1) {
1577               // If this is the only role for this menu item, then
1578               // the app and roles will be gone,
1579               // so must null out the url too, to be consistent
1580               logger.debug(EELFLoggerDelegate.debugLogger,
1581                   "syncAppRoles: There is exactly 1 menu item for this role, so emptying the url");
1582               List<FnMenuFunctional> funcMenuItems = fnMenuFunctionalService.retrieveByMenuId(menuId);
1583               if (funcMenuItems.size() > 0) {
1584                 logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
1585                 FnMenuFunctional funcMenuItem = funcMenuItems.get(0);
1586                 funcMenuItem.setUrl("");
1587               }
1588             }
1589           }
1590           boolean isPortalRequest = true;
1591           deleteRoleDependencyRecords(roleId, appId, isPortalRequest);
1592           logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString());
1593           fnRoleService.delete(role);
1594           logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role");
1595         }
1596       }
1597       for (EcompRole role : newRolesToAdd) {
1598         logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to add missing role: " + role.toString());
1599         FnRole newRole = new FnRole();
1600         // Attention! All roles from remote application supposed to be
1601         // active!
1602         newRole.setActiveYn(true);
1603         newRole.setRoleName(role.getName());
1604         newRole.setAppId(appId);
1605         newRole.setAppRoleId(role.getId());
1606         fnRoleService.saveOne(newRole);
1607       }
1608       logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to commit the transaction");
1609       logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: committed the transaction");
1610     } catch (Exception e) {
1611       logger.error(EELFLoggerDelegate.errorLogger, "syncAppRoles failed", e);
1612       EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
1613       throw new Exception(e);
1614     }
1615   }
1616
1617   private void deleteRoleDependencyRecords(Long roleId, Long appId, boolean isPortalRequest)
1618       throws Exception {
1619     Session localSession = entityManager.unwrap(Session.class);
1620     try {
1621       String sql;
1622       Query query;
1623       // It should delete only when it portal's roleId
1624       if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
1625         // Delete from fn_role_function
1626         sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
1627         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1628         query = localSession.createSQLQuery(sql);
1629         query.executeUpdate();
1630         // Delete from fn_role_composite
1631         sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
1632         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1633         query = localSession.createSQLQuery(sql);
1634         query.executeUpdate();
1635       }
1636       // Delete from ep_app_role_function
1637       sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
1638       logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1639       query = localSession.createSQLQuery(sql);
1640       query.executeUpdate();
1641       // Delete from ep_role_notification
1642       sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
1643       logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1644       query = localSession.createSQLQuery(sql);
1645       query.executeUpdate();
1646       // Delete from fn_user_pseudo_role
1647       sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
1648       logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1649       query = localSession.createSQLQuery(sql);
1650       query.executeUpdate();
1651       // Delete form EP_WIDGET_CATALOG_ROLE
1652       sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
1653       logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1654       query = localSession.createSQLQuery(sql);
1655       query.executeUpdate();
1656       // Delete form EP_WIDGET_CATALOG_ROLE
1657       sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
1658       logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1659       query = localSession.createSQLQuery(sql);
1660       query.executeUpdate();
1661       if (!isPortalRequest) {
1662         // Delete form fn_menu_functional_roles
1663         sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
1664         logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
1665         query = localSession.createSQLQuery(sql);
1666         query.executeUpdate();
1667       }
1668     } catch (Exception e) {
1669       logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
1670       throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
1671     }
1672   }
1673
1674   private void checkIfRoleInactive(FnRole epRole) throws Exception {
1675     if (!epRole.getActiveYn()) {
1676       throw new Exception(epRole.getRoleName() + " role is unavailable");
1677     }
1678   }
1679
1680   public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles) {
1681     boolean result = false;
1682     // No changes if no new roles list or no userId.
1683     if (!org.apache.cxf.common.util.StringUtils.isEmpty(newAppsListWithAdminRoles.getOrgUserId())
1684         && newAppsListWithAdminRoles.getAppsRoles() != null) {
1685       synchronized (syncRests) {
1686         List<FnApp> apps = fnAppService.getAppsFullList();
1687         HashMap<Long, FnApp> enabledApps = new HashMap<>();
1688         for (FnApp app : apps) {
1689           enabledApps.put(app.getId(), app);
1690         }
1691         List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<>();
1692         for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.getAppsRoles()) {
1693           // user Admin role may be added only for enabled apps
1694           if (adminRole.getIsAdmin() && enabledApps.containsKey(adminRole.getId())) {
1695             newAppsWhereUserIsAdmin.add(adminRole);
1696           }
1697         }
1698         FnUser user = null;
1699         boolean createNewUser = false;
1700         String orgUserId = newAppsListWithAdminRoles.getOrgUserId().trim();
1701         List<FnUser> localUserList = fnUserService.getUserWithOrgUserId(orgUserId);
1702         List<FnUserRole> oldAppsWhereUserIsAdmin = new ArrayList<>();
1703         if (localUserList.size() > 0) {
1704           FnUser tmpUser = localUserList.get(0);
1705           oldAppsWhereUserIsAdmin = fnUserRoleService.retrieveByUserIdAndRoleId(tmpUser.getId(), ACCOUNT_ADMIN_ROLE_ID);
1706           if (oldAppsWhereUserIsAdmin.size() > 0 || newAppsWhereUserIsAdmin.size() > 0) {
1707             user = tmpUser;
1708           }
1709         } else if (newAppsWhereUserIsAdmin.size() > 0) {
1710           // we create new user only if he has Admin Role for any App
1711           createNewUser = true;
1712         }
1713         result = isResult(result, enabledApps, newAppsWhereUserIsAdmin, user, createNewUser, orgUserId,
1714             oldAppsWhereUserIsAdmin);
1715       }
1716     }
1717
1718     return result;
1719   }
1720
1721   @Transactional
1722   public boolean isResult(boolean result, HashMap<Long, FnApp> enabledApps,
1723       List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin, FnUser user, boolean createNewUser, String orgUserId,
1724       List<FnUserRole> oldAppsWhereUserIsAdmin) {
1725     if (user != null || createNewUser) {
1726       if (createNewUser) {
1727         user = fnUserService.getUserWithOrgUserId(orgUserId).stream().findFirst().get();
1728         if (user != null) {
1729           user.setActiveYn(true);
1730         }
1731       }
1732       for (FnUserRole oldUserApp : oldAppsWhereUserIsAdmin) {
1733         // user Admin role may be deleted only for enabled
1734         // apps
1735         if (enabledApps.containsKey(oldUserApp.getFnAppId())) {
1736           fnUserRoleService.saveOne(oldUserApp);
1737         }
1738       }
1739       for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
1740         FnApp app = fnAppService.getById(appNameIdIsAdmin.getId());
1741         FnRole role = fnRoleService.getById(ACCOUNT_ADMIN_ROLE_ID);
1742         FnUserRole newUserApp = new FnUserRole();
1743         newUserApp.setUserId(user);
1744         newUserApp.setFnAppId(app);
1745         newUserApp.setRoleId(role);
1746         fnUserRoleService.saveOne(newUserApp);
1747       }
1748       if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
1749         addAdminRoleInExternalSystem(user, newAppsWhereUserIsAdmin);
1750         result = true;
1751       }
1752     }
1753     return result;
1754   }
1755
1756   @Transactional()
1757   public boolean addAdminRoleInExternalSystem(FnUser user, List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin) {
1758     boolean result = false;
1759     try {
1760       // Reset All admin role for centralized applications
1761       List<FnApp> appList = fnAppService.getCentralizedApps();
1762       HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
1763       for (FnApp app : appList) {
1764         String name = "";
1765         if (EPCommonSystemProperties
1766             .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
1767           name = user.getOrgUserId() + SystemProperties
1768               .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1769         }
1770         String extRole = app.getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
1771         HttpEntity<String> entity = new HttpEntity<>(headers);
1772         logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
1773         try {
1774           ResponseEntity<String> getResponse = template
1775               .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1776                   + "roles/" + extRole, HttpMethod.GET, entity, String.class);
1777
1778           if (getResponse.getBody().equals("{}")) {
1779             String addDesc = "{\"name\":\"" + extRole + "\"}";
1780             HttpEntity<String> roleEntity = new HttpEntity<>(addDesc, headers);
1781             template.exchange(
1782                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1783                     + "role",
1784                 HttpMethod.POST, roleEntity, String.class);
1785           } else {
1786             try {
1787               HttpEntity<String> deleteUserRole = new HttpEntity<>(headers);
1788               template.exchange(
1789                   SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1790                       + "userRole/" + name + "/" + extRole,
1791                   HttpMethod.DELETE, deleteUserRole, String.class);
1792             } catch (Exception e) {
1793               logger.error(EELFLoggerDelegate.errorLogger,
1794                   " Role not found for this user may be it gets deleted before", e);
1795             }
1796           }
1797         } catch (Exception e) {
1798           if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1799             logger.debug(EELFLoggerDelegate.debugLogger, "Application Not found for app {}",
1800                 app.getAuthNamespace(), e.getMessage());
1801           } else {
1802             logger.error(EELFLoggerDelegate.errorLogger, "Application Not found for app {}",
1803                 app.getAuthNamespace(), e);
1804           }
1805         }
1806       }
1807       for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
1808         FnApp app = fnAppService.getById(appNameIdIsAdmin.getId());
1809         try {
1810           if (app.getAuthCentral()) {
1811             String extRole = app.getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
1812             HttpEntity<String> entity = new HttpEntity<>(headers);
1813             String name = "";
1814             if (EPCommonSystemProperties
1815                 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
1816               name = user.getOrgUserId() + SystemProperties
1817                   .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
1818             }
1819             logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
1820             ResponseEntity<String> getUserRolesResponse = template.exchange(
1821                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
1822                     + "userRoles/user/" + name,
1823                 HttpMethod.GET, entity, String.class);
1824             logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
1825             if (!getUserRolesResponse.getBody().equals("{}")) {
1826               JSONObject jsonObj = new JSONObject(getUserRolesResponse.getBody());
1827               JSONArray extRoles = jsonObj.getJSONArray("userRole");
1828               final Map<String, JSONObject> extUserRoles = new HashMap<>();
1829               for (int i = 0; i < extRoles.length(); i++) {
1830                 String userRole = extRoles.getJSONObject(i).getString("role");
1831                 if (userRole.startsWith(app.getAuthNamespace() + ".")
1832                     && !userRole.equals(app.getAuthNamespace() + ".admin")
1833                     && !userRole.equals(app.getAuthNamespace() + ".owner")) {
1834
1835                   extUserRoles.put(userRole, extRoles.getJSONObject(i));
1836                 }
1837               }
1838               if (!extUserRoles.containsKey(extRole)) {
1839                 // Assign with new apps user admin
1840                 try {
1841                   ExternalAccessUser extUser = new ExternalAccessUser(name, extRole);
1842                   // Assign user role for an application in external access system
1843                   ObjectMapper addUserRoleMapper = new ObjectMapper();
1844                   String userRole = addUserRoleMapper.writeValueAsString(extUser);
1845                   HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers);
1846                   template.exchange(
1847                       SystemProperties.getProperty(
1848                           EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
1849                       HttpMethod.POST, addUserRole, String.class);
1850                 } catch (Exception e) {
1851                   logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user admin role", e);
1852                 }
1853
1854               }
1855             }
1856           }
1857           result = true;
1858         } catch (Exception e) {
1859           if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
1860             logger.debug(EELFLoggerDelegate.errorLogger,
1861                 "Application name space not found in External system for app {} due to bad rquest name space ",
1862                 app.getAuthNamespace(), e.getMessage());
1863           } else {
1864             logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin role for application {}",
1865                 app.getAuthNamespace(), e);
1866             result = false;
1867           }
1868         }
1869       }
1870     } catch (Exception e) {
1871       result = false;
1872       logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin roles operation", e);
1873     }
1874     return result;
1875   }
1876 }