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