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