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