Application Onboarding page changes
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / service / AdminRolesServiceImpl.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ===================================================================
9  *
10  * Unless otherwise specified, all software contained herein is licensed
11  * under the Apache License, Version 2.0 (the "License");
12  * you may not use this software except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *             http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * Unless otherwise specified, all documentation contained herein is licensed
24  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25  * you may not use this documentation except in compliance with the License.
26  * You may obtain a copy of the License at
27  *
28  *             https://creativecommons.org/licenses/by/4.0/
29  *
30  * Unless required by applicable law or agreed to in writing, documentation
31  * distributed under the License is distributed on an "AS IS" BASIS,
32  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33  * See the License for the specific language governing permissions and
34  * limitations under the License.
35  *
36  * ============LICENSE_END============================================
37  *
38  * 
39  */
40 package org.onap.portalapp.portal.service;
41
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.HashMap;
45 import java.util.HashSet;
46 import java.util.List;
47 import java.util.Map;
48 import java.util.Set;
49 import java.util.SortedSet;
50 import java.util.TreeSet;
51 import java.util.stream.Collectors;
52
53 import javax.annotation.PostConstruct;
54
55 import org.apache.cxf.common.util.StringUtils;
56 import org.hibernate.Session;
57 import org.hibernate.SessionFactory;
58 import org.hibernate.Transaction;
59 import org.json.JSONArray;
60 import org.json.JSONObject;
61 import org.onap.portalapp.portal.domain.CentralV2RoleFunction;
62 import org.onap.portalapp.portal.domain.EPApp;
63 import org.onap.portalapp.portal.domain.EPRole;
64 import org.onap.portalapp.portal.domain.EPUser;
65 import org.onap.portalapp.portal.domain.EPUserApp;
66 import org.onap.portalapp.portal.domain.UserIdRoleId;
67 import org.onap.portalapp.portal.domain.UserRole;
68 import org.onap.portalapp.portal.exceptions.RoleFunctionException;
69 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
70 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
71 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
72 import org.onap.portalapp.portal.transport.AppNameIdIsAdmin;
73 import org.onap.portalapp.portal.transport.AppsListWithAdminRole;
74 import org.onap.portalapp.portal.transport.EPUserAppCurrentRoles;
75 import org.onap.portalapp.portal.transport.ExternalAccessUser;
76 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
77 import org.onap.portalapp.portal.utils.EcompPortalUtils;
78 import org.onap.portalapp.portal.utils.PortalConstants;
79 import org.onap.portalapp.util.EPUserUtils;
80 import org.onap.portalsdk.core.domain.RoleFunction;
81 import org.onap.portalsdk.core.domain.User;
82 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
83 import org.onap.portalsdk.core.restful.domain.EcompRole;
84 import org.onap.portalsdk.core.service.DataAccessService;
85 import org.onap.portalsdk.core.util.SystemProperties;
86 import org.springframework.beans.factory.annotation.Autowired;
87 import org.springframework.context.annotation.EnableAspectJAutoProxy;
88 import org.springframework.http.HttpEntity;
89 import org.springframework.http.HttpHeaders;
90 import org.springframework.http.HttpMethod;
91 import org.springframework.http.ResponseEntity;
92 import org.springframework.stereotype.Service;
93 import org.springframework.transaction.annotation.Transactional;
94 import org.springframework.web.client.RestTemplate;
95
96 import com.fasterxml.jackson.databind.ObjectMapper;
97
98 @Service("adminRolesService")
99 @Transactional
100 @org.springframework.context.annotation.Configuration
101 @EnableAspectJAutoProxy
102
103 public class AdminRolesServiceImpl implements AdminRolesService {
104
105         private Long SYS_ADMIN_ROLE_ID = 1L;
106         private Long ACCOUNT_ADMIN_ROLE_ID = 999L;
107         private Long ECOMP_APP_ID = 1L;
108         public static final String TYPE_APPROVER = "approver";
109
110         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesServiceImpl.class);
111
112         @Autowired
113         private SessionFactory sessionFactory;
114         @Autowired
115         private DataAccessService dataAccessService;
116         @Autowired
117         private SearchService searchService;
118         @Autowired
119         private EPAppService appsService;
120         @Autowired
121         private ExternalAccessRolesService externalAccessRolesService;
122
123         private RestTemplate template = new RestTemplate();
124
125         @PostConstruct
126         private void init() {
127                 try {
128                         SYS_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.SYS_ADMIN_ROLE_ID));
129                         ACCOUNT_ADMIN_ROLE_ID = Long
130                                         .valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID));
131                         ECOMP_APP_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID));
132                 } catch (Exception e) {
133                         logger.error(EELFLoggerDelegate.errorLogger, "init failed", e);
134                 }
135         }
136
137         @Override
138         @EPMetricsLog
139         @SuppressWarnings("unchecked")
140         public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(String orgUserId) {
141                 AppsListWithAdminRole appsListWithAdminRole = null;
142
143                 try {
144                         List<EPUser> userList = null;
145                         Map<String, String> userParams = new HashMap<>();
146                         userParams.put("org_user_id", orgUserId);
147                         try {
148                                 userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null);
149                         } catch (Exception e) {
150                                 logger.error(EELFLoggerDelegate.errorLogger, "getEPUserByOrgUserId failed", e);
151                         }
152
153                         HashMap<Long, Long> appsUserAdmin = new HashMap<Long, Long>();
154                         if (userList!= null && userList.size() > 0) {
155                                 EPUser user = userList.get(0);
156                                 List<EPUserApp> userAppList = null;
157                                 try {
158                                         userAppList = dataAccessService.getList(EPUserApp.class,
159                                                         " where userId = " + user.getId() + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID, null, null);
160                                 } catch (Exception e) {
161                                         logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 1 failed", e);
162                                         EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
163                                 }
164                                 for (EPUserApp userApp : userAppList) {
165                                         appsUserAdmin.put(userApp.getAppId(), userApp.getUserId());
166                                 }
167                         }
168
169                         appsListWithAdminRole = new AppsListWithAdminRole();
170                         appsListWithAdminRole.orgUserId = orgUserId;
171                         List<EPApp> appsList = null;
172                         try {
173 //                              appsList = dataAccessService.getList(EPApp.class,
174 //                                              null, null, null);
175                                 
176                                 appsList = dataAccessService.getList(EPApp.class, null);
177                         } catch (Exception e) {
178                                 logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 2 failed", e);
179                                 EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
180                         }
181                         for (EPApp app : appsList) {
182                                 AppNameIdIsAdmin appNameIdIsAdmin = new AppNameIdIsAdmin();
183                                 appNameIdIsAdmin.id = app.getId();
184                                 appNameIdIsAdmin.appName = app.getName();
185                                 appNameIdIsAdmin.isAdmin = new Boolean(appsUserAdmin.containsKey(app.getId()));
186                                 appNameIdIsAdmin.restrictedApp = app.isRestrictedApp();
187                                 appsListWithAdminRole.appsRoles.add(appNameIdIsAdmin);
188                         }
189                 } catch (Exception e) {
190                         logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 3 failed", e);
191                 }
192
193                 return appsListWithAdminRole;
194         }
195
196         private static final Object syncRests = new Object();
197
198         @Override
199         @EPMetricsLog
200         @SuppressWarnings("unchecked")
201         public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles) {
202                 boolean result = false;
203                 // No changes if no new roles list or no userId.
204                 if (!StringUtils.isEmpty(newAppsListWithAdminRoles.orgUserId) && newAppsListWithAdminRoles.appsRoles != null) {
205                         synchronized (syncRests) {
206                                 List<EPApp> apps = appsService.getAppsFullList();
207                                 HashMap<Long, EPApp> enabledApps = new HashMap<Long, EPApp>();
208                                 for (EPApp app : apps) {
209 //                                      if (app.getEnabled().booleanValue() || app.getId() == ECOMP_APP_ID) {
210                                                 enabledApps.put(app.getId(), app);
211 //                                      }
212                                 }
213                                 List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<AppNameIdIsAdmin>();
214                                 for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.appsRoles) {
215                                         // user Admin role may be added only for enabled apps
216                                         if (adminRole.isAdmin.booleanValue() && enabledApps.containsKey(adminRole.id)) {
217                                                 newAppsWhereUserIsAdmin.add(adminRole);
218                                         }
219                                 }
220                                 EPUser user = null;
221                                 boolean createNewUser = false;
222                                 String orgUserId = newAppsListWithAdminRoles.orgUserId.trim();
223                                 List<EPUser> localUserList = dataAccessService.getList(EPUser.class,
224                                                 " where org_user_id='" + orgUserId + "'", null, null);
225                                 List<EPUserApp> oldAppsWhereUserIsAdmin = new ArrayList<EPUserApp>();
226                                 if (localUserList.size() > 0) {
227                                         EPUser tmpUser = localUserList.get(0);
228                                         oldAppsWhereUserIsAdmin = dataAccessService.getList(EPUserApp.class,
229                                                         " where userId = " + tmpUser.getId() + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID, null,
230                                                         null);
231                                         if (oldAppsWhereUserIsAdmin.size() > 0 || newAppsWhereUserIsAdmin.size() > 0) {
232                                                 user = tmpUser;
233                                         }
234                                 } else if (newAppsWhereUserIsAdmin.size() > 0) {
235                                         // we create new user only if he has Admin Role for any App
236                                         createNewUser = true;
237                                 }
238                                 if (user != null || createNewUser) {
239                                         Session localSession = null;
240                                         Transaction transaction = null;
241                                         try {
242                                                 localSession = sessionFactory.openSession();
243                                                 transaction = localSession.beginTransaction();
244                                                 if (createNewUser) {
245                                                         user = this.searchService.searchUserByUserId(orgUserId);
246                                                         if (user != null) {
247                                                                 // insert the user with active true in order to
248                                                                 // pass login phase.
249                                                                 user.setActive(true);
250                                                                 localSession.save(EPUser.class.getName(), user);
251                                                         }
252                                                 }
253                                                 for (EPUserApp oldUserApp : oldAppsWhereUserIsAdmin) {
254                                                         // user Admin role may be deleted only for enabled
255                                                         // apps
256                                                         if (enabledApps.containsKey(oldUserApp.getAppId())) {
257                                                                 localSession.delete(oldUserApp);
258                                                         }
259                                                 }
260                                                 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
261                                                         EPApp app = (EPApp) localSession.get(EPApp.class, appNameIdIsAdmin.id);
262                                                         EPRole role = (EPRole) localSession.get(EPRole.class, new Long(ACCOUNT_ADMIN_ROLE_ID));
263                                                         EPUserApp newUserApp = new EPUserApp();
264                                                         newUserApp.setUserId(user.getId());
265                                                         newUserApp.setApp(app);
266                                                         newUserApp.setRole(role);
267                                                         localSession.save(EPUserApp.class.getName(), newUserApp);
268                                                 }
269                                                 transaction.commit();
270                                                 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
271                                                         // Add user admin role for list of centralized applications in external system
272                                                         addAdminRoleInExternalSystem(user, localSession, newAppsWhereUserIsAdmin);
273                                                         result = true;
274                                                 }
275                                         } catch (Exception e) {
276                                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
277                                                 logger.error(EELFLoggerDelegate.errorLogger,
278                                                                 "setAppsWithAdminRoleStateForUser: exception in point 2", e);
279                                                 try {
280                                                         if(transaction!=null)
281                                                                 transaction.rollback();
282                                                         else
283                                                                 logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: transaction is null cannot rollback");
284                                                 } catch (Exception ex) {
285                                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e);
286                                                         logger.error(EELFLoggerDelegate.errorLogger,
287                                                                         "setAppsWithAdminRoleStateForUser: exception in point 3", ex);
288                                                 }
289                                         } finally {
290                                                 try {
291                                                         localSession.close();
292                                                 } catch (Exception e) {
293                                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e);
294                                                         logger.error(EELFLoggerDelegate.errorLogger,
295                                                                         "setAppsWithAdminRoleStateForUser: exception in point 4", e);
296                                                 }
297                                         }
298                                 }
299                         }
300                 }
301
302                 return result;
303         }
304
305         @SuppressWarnings("unchecked")
306         private boolean addAdminRoleInExternalSystem(EPUser user, Session localSession,
307                         List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin) {
308                 boolean result = false;
309                 try {
310                         // Reset All admin role for centralized applications
311                         List<EPApp> appList = dataAccessService.executeNamedQuery("getCentralizedApps", null, null);
312                         HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
313                         for (EPApp app : appList) {
314                                 String name = "";
315                                 if (EPCommonSystemProperties
316                                                 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
317                                         name = user.getOrgUserId() + SystemProperties
318                                                         .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
319                                 }
320                                 String extRole = app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
321                                 HttpEntity<String> entity = new HttpEntity<>(headers);
322                                 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
323                                 try {
324                                         ResponseEntity<String> getResponse = template
325                                                         .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
326                                                                         + "roles/" + extRole, HttpMethod.GET, entity, String.class);
327
328                                         if (getResponse.getBody().equals("{}")) {
329                                                 String addDesc = "{\"name\":\"" + extRole + "\"}";
330                                                 HttpEntity<String> roleEntity = new HttpEntity<>(addDesc, headers);
331                                                 template.exchange(
332                                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
333                                                                                 + "role",
334                                                                 HttpMethod.POST, roleEntity, String.class);
335                                         } else {
336                                                 try {
337                                                         HttpEntity<String> deleteUserRole = new HttpEntity<>(headers);
338                                                         template.exchange(
339                                                                         SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
340                                                                                         + "userRole/" + name + "/" + extRole,
341                                                                         HttpMethod.DELETE, deleteUserRole, String.class);
342                                                 } catch (Exception e) {
343                                                         logger.error(EELFLoggerDelegate.errorLogger,
344                                                                         " Role not found for this user may be it gets deleted before", e);
345                                                 }
346                                         }
347                                 } catch (Exception e) {
348                                         if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
349                                                 logger.debug(EELFLoggerDelegate.debugLogger, "Application Not found for app {}",
350                                                                 app.getNameSpace(), e.getMessage());
351                                         } else {
352                                                 logger.error(EELFLoggerDelegate.errorLogger, "Application Not found for app {}",
353                                                                 app.getNameSpace(), e);
354                                         }
355                                 }
356                         }
357                         // Add admin role in external application
358                         // application
359                         for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
360                                 EPApp app = (EPApp) localSession.get(EPApp.class, appNameIdIsAdmin.id);
361                                 try {
362                                         if (app.getCentralAuth()) {
363                                                 String extRole = app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
364                                                 HttpEntity<String> entity = new HttpEntity<>(headers);
365                                                 String name = "";
366                                                 if (EPCommonSystemProperties
367                                                                 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
368                                                         name = user.getOrgUserId() + SystemProperties
369                                                                         .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
370                                                 }
371                                                 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
372                                                 ResponseEntity<String> getUserRolesResponse = template.exchange(
373                                                                 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
374                                                                                 + "userRoles/user/" + name,
375                                                                 HttpMethod.GET, entity, String.class);
376                                                 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
377                                                 if (!getUserRolesResponse.getBody().equals("{}")) {
378                                                         JSONObject jsonObj = new JSONObject(getUserRolesResponse.getBody());
379                                                         JSONArray extRoles = jsonObj.getJSONArray("userRole");
380                                                         final Map<String, JSONObject> extUserRoles = new HashMap<>();
381                                                         for (int i = 0; i < extRoles.length(); i++) {
382                                                                 String userRole = extRoles.getJSONObject(i).getString("role");
383                                                                 if (userRole.startsWith(app.getNameSpace() + ".")
384                                                                                 && !userRole.equals(app.getNameSpace() + ".admin")
385                                                                                 && !userRole.equals(app.getNameSpace() + ".owner")) {
386
387                                                                         extUserRoles.put(userRole, extRoles.getJSONObject(i));
388                                                                 }
389                                                         }
390                                                         if (!extUserRoles.containsKey(extRole)) {
391                                                                 // Assign with new apps user admin
392                                                                 try {
393                                                                         ExternalAccessUser extUser = new ExternalAccessUser(name, extRole);
394                                                                         // Assign user role for an application in external access system
395                                                                         ObjectMapper addUserRoleMapper = new ObjectMapper();
396                                                                         String userRole = addUserRoleMapper.writeValueAsString(extUser);
397                                                                         HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers);
398                                                                         template.exchange(
399                                                                                         SystemProperties.getProperty(
400                                                                                                         EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
401                                                                                         HttpMethod.POST, addUserRole, String.class);
402                                                                 } catch (Exception e) {
403                                                                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user admin role", e);
404                                                                 }
405
406                                                         }
407                                                 }
408                                         }
409                                         result = true;
410                                 } catch (Exception e) {
411                                         if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
412                                                 logger.debug(EELFLoggerDelegate.errorLogger,
413                                                                 "Application name space not found in External system for app {} due to bad rquest name space ",
414                                                                 app.getNameSpace(), e.getMessage());
415                                         } else {
416                                                 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin role for application {}",
417                                                                 app.getNameSpace(), e);
418                                                 result = false;
419                                         }
420                                 }
421                         }
422                 } catch (Exception e) {
423                         result = false;
424                         logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin roles operation", e);
425                 }
426                 return result;
427         }
428
429         @SuppressWarnings("unchecked")
430         @Override
431         public boolean isSuperAdmin(EPUser user) {
432                 if ((user != null) && (user.getOrgUserId() != null)) {
433                         String sql = "SELECT user.USER_ID, user.org_user_id, userrole.ROLE_ID, userrole.APP_ID FROM fn_user_role userrole "
434                                         + "INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID " + "WHERE user.org_user_id = '"
435                                         + user.getOrgUserId() + "' " + "AND userrole.ROLE_ID = '" + SYS_ADMIN_ROLE_ID + "' "
436                                         + "AND userrole.APP_ID = '" + ECOMP_APP_ID + "';";
437                         try {
438                                 List<UserRole> userRoleList = dataAccessService.executeSQLQuery(sql, UserIdRoleId.class, null);
439                                 if (userRoleList != null && userRoleList.size() > 0) {
440                                         return true;
441                                 }
442                         } catch (Exception e) {
443                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
444                                 logger.error(EELFLoggerDelegate.errorLogger,
445                                                 "Exception occurred while executing isSuperAdmin operation", e);
446                         }
447                 }
448                 return false;
449         }
450
451         public boolean isAccountAdmin(EPUser user) {
452                 try {
453         if (user == null) {
454             return false;
455         }
456
457                         EPUser currentUser = (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null);
458
459                         final Map<String, Long> userParams = new HashMap<>();
460                         userParams.put("userId", user.getId());
461                         logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user {}", user.getId());
462                         List<Integer> userAdminApps = new ArrayList<>();
463
464                         userAdminApps =dataAccessService.executeNamedQuery("getAdminAppsForTheUser", userParams, null);
465                         logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}", user.getOrgUserId(), userAdminApps.size());
466
467
468                         if (currentUser != null && currentUser.getId() != null) {
469                                 for (EPUserApp userApp : currentUser.getEPUserApps()) {
470
471
472                                         if (userApp.getRole().getId().equals(ACCOUNT_ADMIN_ROLE_ID)||(userAdminApps.size()>1)) {
473                                                 logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for userAdminApps() - for user {}, found Id {}", user.getOrgUserId(), userApp.getRole().getId());
474                                                 // Account Administrator sees only the applications
475                                                 // he/she is Administrator
476                                                 return true;
477                                         }
478                                 }
479                         }
480                 } catch (Exception e) {
481                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
482                         logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isAccountAdmin operation",
483                                         e);
484                 }
485                 return false;
486         }
487
488
489         public boolean isRoleAdmin(EPUser user) {
490                 try {
491                         logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has isRoleAdmin access");
492
493                                         final Map<String, Long> userParams = new HashMap<>();
494                                         userParams.put("userId", user.getId());
495                                         List getRoleFuncListOfUser = dataAccessService.executeNamedQuery("getRoleFunctionsOfUserforAlltheApplications", userParams, null);
496                                         logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has isRoleAdmin access :: getRoleFuncListOfUser" , getRoleFuncListOfUser);
497                                         Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfUser);
498                                         Set<String> getRoleFuncListOfPortalSet1=new HashSet<>();
499                                         Set<String> roleFunSet = new HashSet<>();
500                                         roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|")).collect(Collectors.toSet());
501                                         if (roleFunSet.size() > 0)
502                                                 for (String roleFunction : roleFunSet) {
503                                                         String type = externalAccessRolesService.getFunctionCodeType(roleFunction);
504                                                         getRoleFuncListOfPortalSet1.add(type);
505                                                 }
506                                 
507                                         boolean checkIfFunctionsExits = getRoleFuncListOfPortalSet1.stream()
508                                                         .anyMatch(roleFunction -> roleFunction.equalsIgnoreCase("Approver"));
509                                         logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has approver rolefunction" , checkIfFunctionsExits);
510
511                                         return checkIfFunctionsExits;
512                 
513                 } catch (Exception e) {
514                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
515                         logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isRoleAdmin operation",
516                                         e);
517                 }
518                 return false;
519         }
520
521         public boolean isUser(EPUser user) {
522                 try {
523                         EPUser currentUser = user != null
524                                         ? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null)
525                                         : null;
526                         if (currentUser != null && currentUser.getId() != null) {
527                                 for (EPUserApp userApp : currentUser.getEPUserApps()) {
528                                         if (!userApp.getApp().getId().equals(ECOMP_APP_ID)) {
529                                                 EPRole role = userApp.getRole();
530                                                 if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
531                                                         if (role.getActive()) {
532                                                                 return true;
533                                                         }
534                                                 }
535                                         }
536                                 }
537                         }
538                 } catch (Exception e) {
539                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
540                         logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation", e);
541                 }
542                 return false;
543         }
544
545         @Override
546         @EPMetricsLog
547         public List<EPRole> getRolesByApp(EPUser user, Long appId) {
548                 List<EPRole> list = new ArrayList<>();
549                 String sql = "SELECT * FROM FN_ROLE WHERE UPPER(ACTIVE_YN) = 'Y' AND APP_ID = " + appId;
550                 @SuppressWarnings("unchecked")
551                 List<EPRole> roles = dataAccessService.executeSQLQuery(sql, EPRole.class, null);
552                 for (EPRole role : roles) {
553                         list.add(role);
554                 }
555                 return list;
556         }
557
558         @Override
559         public boolean isAccountAdminOfApplication(EPUser user, EPApp app) {
560                 Boolean isApplicationAccountAdmin=false;
561                 try {
562                                         final Map<String, Long> userParams = new HashMap<>();
563                                         userParams.put("userId", user.getId());
564                                         logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user {}", user.getId());
565                                         List<Integer> userAdminApps = new ArrayList<>();
566                                         userAdminApps =dataAccessService.executeNamedQuery("getAdminAppsForTheUser", userParams, null);
567                                         if(userAdminApps.size()>=1){
568                                         isApplicationAccountAdmin=userAdminApps.contains((int) (long) app.getId());
569                                         logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user is true{} ,appId {}", user.getId(),app.getId());
570                                         }
571                         } catch (Exception e) {
572                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
573                         logger.error(EELFLoggerDelegate.errorLogger,
574                                         "Exception occurred while executing isAccountAdminOfApplication operation", e);
575                 }
576                 logger.debug(EELFLoggerDelegate.debugLogger, "In AdminRolesServiceImpl() - isAccountAdminOfApplication = {} and userId ={} ", isApplicationAccountAdmin, user.getOrgUserId());
577                 return isApplicationAccountAdmin;
578
579         }
580
581         @Override
582         public Set<String> getAllAppsFunctionsOfUser(String OrgUserId) throws RoleFunctionException {
583                 final Map<String, String> params = new HashMap<>();
584                 params.put("userId", OrgUserId);
585                 List getRoleFuncListOfPortal = dataAccessService.executeNamedQuery("getAllAppsFunctionsOfUser", params, null);
586                 Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfPortal);
587                 Set<String> roleFunSet = new HashSet<>();
588                 roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|")).collect(Collectors.toSet());
589                 if (roleFunSet.size() > 0)
590                         for (String roleFunction : roleFunSet) {
591                                 String roleFun = EcompPortalUtils.getFunctionCode(roleFunction);
592                                 getRoleFuncListOfPortalSet.remove(roleFunction);
593                                 getRoleFuncListOfPortalSet.add(roleFun);
594                         }
595
596                 Set<String> finalRoleFunctionSet = new HashSet<>();
597                 for (String roleFn : getRoleFuncListOfPortalSet) {
598                         finalRoleFunctionSet.add(EPUserUtils.decodeFunctionCode(roleFn));
599                 }
600                 
601 //              List<String> functionsOfUser = new ArrayList<>(getRoleFuncListOfPortal);
602                 return finalRoleFunctionSet;
603         }
604
605         
606         @Override
607         public boolean isAccountAdminOfAnyActiveorInactiveApplication(EPUser user, EPApp app) {
608                 Boolean isApplicationAccountAdmin=false;
609                 try {
610                                         final Map<String, Long> userParams = new HashMap<>();
611                                         userParams.put("userId", user.getId()); 
612                                         logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user {}", user.getId());
613                                         List<Integer> userAdminApps = new ArrayList<>();
614                                         userAdminApps =dataAccessService.executeNamedQuery("getAllAdminAppsofTheUser", userParams, null);
615                                         if(userAdminApps.size()>=1){
616                                         isApplicationAccountAdmin=userAdminApps.contains((int) (long) app.getId());
617                                         logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user is true{} ,appId {}", user.getId(),app.getId());
618                                         }                                       
619                         } catch (Exception e) {
620                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
621                         logger.error(EELFLoggerDelegate.errorLogger,
622                                         "Exception occurred while executing isAccountAdminOfApplication operation", e);
623                 }
624                 logger.debug(EELFLoggerDelegate.debugLogger, "In AdminRolesServiceImpl() - isAccountAdminOfApplication = {} and userId ={} ", isApplicationAccountAdmin, user.getOrgUserId());
625                 return isApplicationAccountAdmin;
626
627         }
628 }