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