summaryrefslogtreecommitdiffstats
path: root/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesServiceImpl.java
blob: 969ccc5f8831c8873cdd18a2a182f0fc2e5ef1b6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
/*-
 * ============LICENSE_START==========================================
 * ONAP Portal
 * ===================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ===================================================================
 * Modifications Copyright (c) 2019 Samsung
 * ===================================================================
 *
 * Unless otherwise specified, all software contained herein is licensed
 * under the Apache License, Version 2.0 (the "License");
 * you may not use this software except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Unless otherwise specified, all documentation contained herein is licensed
 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
 * you may not use this documentation except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             https://creativecommons.org/licenses/by/4.0/
 *
 * Unless required by applicable law or agreed to in writing, documentation
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * ============LICENSE_END============================================
 *
 * 
 */
package org.onap.portalapp.portal.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import org.apache.cxf.common.util.StringUtils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.json.JSONArray;
import org.json.JSONObject;
import org.onap.portalapp.portal.domain.EPApp;
import org.onap.portalapp.portal.domain.EPRole;
import org.onap.portalapp.portal.domain.EPUser;
import org.onap.portalapp.portal.domain.EPUserApp;
import org.onap.portalapp.portal.domain.UserIdRoleId;
import org.onap.portalapp.portal.domain.UserRole;
import org.onap.portalapp.portal.exceptions.RoleFunctionException;
import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
import org.onap.portalapp.portal.logging.logic.EPLogUtil;
import org.onap.portalapp.portal.transport.AppNameIdIsAdmin;
import org.onap.portalapp.portal.transport.AppsListWithAdminRole;
import org.onap.portalapp.portal.transport.ExternalAccessUser;
import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
import org.onap.portalapp.portal.utils.EcompPortalUtils;
import org.onap.portalapp.portal.utils.PortalConstants;
import org.onap.portalapp.util.EPUserUtils;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.service.DataAccessService;
import org.onap.portalsdk.core.util.SystemProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service("adminRolesService")
@Transactional
@org.springframework.context.annotation.Configuration
@EnableAspectJAutoProxy

public class AdminRolesServiceImpl implements AdminRolesService {

	private Long SYS_ADMIN_ROLE_ID = 1L;
	private Long ACCOUNT_ADMIN_ROLE_ID = 999L;
	private Long ECOMP_APP_ID = 1L;
	public static final String TYPE_APPROVER = "approver";
	private static final String ADMIN_ACCOUNT= "Is account admin for user {}";

	private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesServiceImpl.class);

	@Autowired
	private SessionFactory sessionFactory;
	@Autowired
	private DataAccessService dataAccessService;
	@Autowired
	private SearchService searchService;
	@Autowired
	private EPAppService appsService;
	@Autowired
	private ExternalAccessRolesService externalAccessRolesService;

	private RestTemplate template = new RestTemplate();

	@PostConstruct
	private void init() {
		try {
			SYS_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.SYS_ADMIN_ROLE_ID));
			ACCOUNT_ADMIN_ROLE_ID = Long
					.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID));
			ECOMP_APP_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID));
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "init failed", e);
		}
	}

	@Override
	@EPMetricsLog
	@SuppressWarnings("unchecked")
	public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(String orgUserId) {
		AppsListWithAdminRole appsListWithAdminRole = null;

		try {
			List<EPUser> userList = null;
			Map<String, String> userParams = new HashMap<>();
			userParams.put("org_user_id", orgUserId);
			try {
				userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null);
			} catch (Exception e) {
				logger.error(EELFLoggerDelegate.errorLogger, "getEPUserByOrgUserId failed", e);
			}

			HashMap<Long, Long> appsUserAdmin = new HashMap<Long, Long>();
			if (userList!= null && userList.size() > 0) {
				EPUser user = userList.get(0);
				List<EPUserApp> userAppList = null;
				try {
					userAppList = dataAccessService.getList(EPUserApp.class,
							" where userId = " + user.getId() + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID, null, null);
				} catch (Exception e) {
					logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 1 failed", e);
					EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
				}
				for (EPUserApp userApp : userAppList) {
					appsUserAdmin.put(userApp.getAppId(), userApp.getUserId());
				}
			}

			appsListWithAdminRole = new AppsListWithAdminRole();
			appsListWithAdminRole.orgUserId = orgUserId;
			List<EPApp> appsList = null;
			try {
//				appsList = dataAccessService.getList(EPApp.class,
//						null, null, null);
				
				appsList = dataAccessService.getList(EPApp.class, null);
			} catch (Exception e) {
				logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 2 failed", e);
				EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
			}
			for (EPApp app : appsList) {
				AppNameIdIsAdmin appNameIdIsAdmin = new AppNameIdIsAdmin();
				appNameIdIsAdmin.id = app.getId();
				appNameIdIsAdmin.appName = app.getName();
				appNameIdIsAdmin.isAdmin = new Boolean(appsUserAdmin.containsKey(app.getId()));
				appNameIdIsAdmin.restrictedApp = app.isRestrictedApp();
				appsListWithAdminRole.appsRoles.add(appNameIdIsAdmin);
			}
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 3 failed", e);
		}

		return appsListWithAdminRole;
	}

	private static final Object syncRests = new Object();

	@Override
	@EPMetricsLog
	@SuppressWarnings("unchecked")
	public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles) {
		boolean result = false;
		// No changes if no new roles list or no userId.
		if (!StringUtils.isEmpty(newAppsListWithAdminRoles.orgUserId) && newAppsListWithAdminRoles.appsRoles != null) {
			synchronized (syncRests) {
				List<EPApp> apps = appsService.getAppsFullList();
				HashMap<Long, EPApp> enabledApps = new HashMap<Long, EPApp>();
				for (EPApp app : apps) {
//					if (app.getEnabled().booleanValue() || app.getId() == ECOMP_APP_ID) {
						enabledApps.put(app.getId(), app);
//					}
				}
				List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<AppNameIdIsAdmin>();
				for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.appsRoles) {
					// user Admin role may be added only for enabled apps
					if (adminRole.isAdmin.booleanValue() && enabledApps.containsKey(adminRole.id)) {
						newAppsWhereUserIsAdmin.add(adminRole);
					}
				}
				EPUser user = null;
				boolean createNewUser = false;
				String orgUserId = newAppsListWithAdminRoles.orgUserId.trim();
				List<EPUser> localUserList = dataAccessService.getList(EPUser.class,
						" where org_user_id='" + orgUserId + "'", null, null);
				List<EPUserApp> oldAppsWhereUserIsAdmin = new ArrayList<EPUserApp>();
				if (localUserList.size() > 0) {
					EPUser tmpUser = localUserList.get(0);
					oldAppsWhereUserIsAdmin = dataAccessService.getList(EPUserApp.class,
							" where userId = " + tmpUser.getId() + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID, null,
							null);
					if (oldAppsWhereUserIsAdmin.size() > 0 || newAppsWhereUserIsAdmin.size() > 0) {
						user = tmpUser;
					}
				} else if (newAppsWhereUserIsAdmin.size() > 0) {
					// we create new user only if he has Admin Role for any App
					createNewUser = true;
				}
				if (user != null || createNewUser) {
					Session localSession = null;
					Transaction transaction = null;
					try {
						localSession = sessionFactory.openSession();
						transaction = localSession.beginTransaction();
						if (createNewUser) {
							user = this.searchService.searchUserByUserId(orgUserId);
							if (user != null) {
								// insert the user with active true in order to
								// pass login phase.
								user.setActive(true);
								localSession.save(EPUser.class.getName(), user);
							}
						}
						for (EPUserApp oldUserApp : oldAppsWhereUserIsAdmin) {
							// user Admin role may be deleted only for enabled
							// apps
							if (enabledApps.containsKey(oldUserApp.getAppId())) {
								localSession.delete(oldUserApp);
							}
						}
						for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
							EPApp app = (EPApp) localSession.get(EPApp.class, appNameIdIsAdmin.id);
							EPRole role = (EPRole) localSession.get(EPRole.class, new Long(ACCOUNT_ADMIN_ROLE_ID));
							EPUserApp newUserApp = new EPUserApp();
							newUserApp.setUserId(user.getId());
							newUserApp.setApp(app);
							newUserApp.setRole(role);
							localSession.save(EPUserApp.class.getName(), newUserApp);
						}
						transaction.commit();
						if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
							// Add user admin role for list of centralized applications in external system
							addAdminRoleInExternalSystem(user, localSession, newAppsWhereUserIsAdmin);
							result = true;
						}
					} catch (Exception e) {
						EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
						logger.error(EELFLoggerDelegate.errorLogger,
								"setAppsWithAdminRoleStateForUser: exception in point 2", e);
						try {
							if(transaction!=null)
								transaction.rollback();
							else
								logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: transaction is null cannot rollback");
						} catch (Exception ex) {
							EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e);
							logger.error(EELFLoggerDelegate.errorLogger,
									"setAppsWithAdminRoleStateForUser: exception in point 3", ex);
						}
					} finally {
						try {
							localSession.close();
						} catch (Exception e) {
							EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e);
							logger.error(EELFLoggerDelegate.errorLogger,
									"setAppsWithAdminRoleStateForUser: exception in point 4", e);
						}
					}
				}
			}
		}

		return result;
	}

	@SuppressWarnings("unchecked")
	private boolean addAdminRoleInExternalSystem(EPUser user, Session localSession,
			List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin) {
		boolean result = false;
		try {
			// Reset All admin role for centralized applications
			List<EPApp> appList = dataAccessService.executeNamedQuery("getCentralizedApps", null, null);
			HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
			for (EPApp app : appList) {
				String name = "";
				if (EPCommonSystemProperties
						.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
					name = user.getOrgUserId() + SystemProperties
							.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
				}
				String extRole = app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
				HttpEntity<String> entity = new HttpEntity<>(headers);
				logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
				try {
					ResponseEntity<String> getResponse = template
							.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
									+ "roles/" + extRole, HttpMethod.GET, entity, String.class);

					if (getResponse.getBody().equals("{}")) {
						String addDesc = "{\"name\":\"" + extRole + "\"}";
						HttpEntity<String> roleEntity = new HttpEntity<>(addDesc, headers);
						template.exchange(
								SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
										+ "role",
								HttpMethod.POST, roleEntity, String.class);
					} else {
						try {
							HttpEntity<String> deleteUserRole = new HttpEntity<>(headers);
							template.exchange(
									SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
											+ "userRole/" + name + "/" + extRole,
									HttpMethod.DELETE, deleteUserRole, String.class);
						} catch (Exception e) {
							logger.error(EELFLoggerDelegate.errorLogger,
									" Role not found for this user may be it gets deleted before", e);
						}
					}
				} catch (Exception e) {
					if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
						logger.debug(EELFLoggerDelegate.debugLogger, "Application Not found for app {}",
								app.getNameSpace(), e.getMessage());
					} else {
						logger.error(EELFLoggerDelegate.errorLogger, "Application Not found for app {}",
								app.getNameSpace(), e);
					}
				}
			}
			// Add admin role in external application
			// application
			for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
				EPApp app = (EPApp) localSession.get(EPApp.class, appNameIdIsAdmin.id);
				try {
					if (app.getRolesInAAF()) {
						String extRole = app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
						HttpEntity<String> entity = new HttpEntity<>(headers);
						String name = "";
						if (EPCommonSystemProperties
								.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
							name = user.getOrgUserId() + SystemProperties
									.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
						}
						logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
						ResponseEntity<String> getUserRolesResponse = template.exchange(
								SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
										+ "userRoles/user/" + name,
								HttpMethod.GET, entity, String.class);
						logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
						if (!getUserRolesResponse.getBody().equals("{}")) {
							JSONObject jsonObj = new JSONObject(getUserRolesResponse.getBody());
							JSONArray extRoles = jsonObj.getJSONArray("userRole");
							final Map<String, JSONObject> extUserRoles = new HashMap<>();
							for (int i = 0; i < extRoles.length(); i++) {
								String userRole = extRoles.getJSONObject(i).getString("role");
								if (userRole.startsWith(app.getNameSpace() + ".")
										&& !userRole.equals(app.getNameSpace() + ".admin")
										&& !userRole.equals(app.getNameSpace() + ".owner")) {

									extUserRoles.put(userRole, extRoles.getJSONObject(i));
								}
							}
							if (!extUserRoles.containsKey(extRole)) {
								// Assign with new apps user admin
								try {
									ExternalAccessUser extUser = new ExternalAccessUser(name, extRole);
									// Assign user role for an application in external access system
									ObjectMapper addUserRoleMapper = new ObjectMapper();
									String userRole = addUserRoleMapper.writeValueAsString(extUser);
									HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers);
									template.exchange(
											SystemProperties.getProperty(
													EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
											HttpMethod.POST, addUserRole, String.class);
								} catch (Exception e) {
									logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user admin role", e);
								}

							}
						}
					}
					result = true;
				} catch (Exception e) {
					if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
						logger.debug(EELFLoggerDelegate.errorLogger,
								"Application name space not found in External system for app {} due to bad rquest name space ",
								app.getNameSpace(), e.getMessage());
					} else {
						logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin role for application {}",
								app.getNameSpace(), e);
						result = false;
					}
				}
			}
		} catch (Exception e) {
			result = false;
			logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin roles operation", e);
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean isSuperAdmin(EPUser user) {
		if ((user != null) && (user.getOrgUserId() != null)) {
			String sql = "SELECT user.USER_ID, user.org_user_id, userrole.ROLE_ID, userrole.APP_ID FROM fn_user_role userrole "
					+ "INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID " + "WHERE user.org_user_id = '"
					+ user.getOrgUserId() + "' " + "AND userrole.ROLE_ID = '" + SYS_ADMIN_ROLE_ID + "' "
					+ "AND userrole.APP_ID = '" + ECOMP_APP_ID + "';";
			try {
				List<UserRole> userRoleList = dataAccessService.executeSQLQuery(sql, UserIdRoleId.class, null);
				if (userRoleList != null && userRoleList.size() > 0) {
					return true;
				}
			} catch (Exception e) {
				EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
				logger.error(EELFLoggerDelegate.errorLogger,
						"Exception occurred while executing isSuperAdmin operation", e);
			}
		}
		return false;
	}

	public boolean isAccountAdmin(EPUser user) {
		try {
        if (user == null) {
            return false;
        }

			EPUser currentUser = (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null);

			final Map<String, Long> userParams = new HashMap<>();
			userParams.put("userId", user.getId());
			logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, user.getId());
			List<Integer> userAdminApps = new ArrayList<>();

			userAdminApps =dataAccessService.executeNamedQuery("getAdminAppsForTheUser", userParams, null);
			logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}", user.getOrgUserId(), userAdminApps.size());


			if (currentUser != null && currentUser.getId() != null) {
				for (EPUserApp userApp : currentUser.getEPUserApps()) {


					if (userApp.getRole().getId().equals(ACCOUNT_ADMIN_ROLE_ID)||(userAdminApps.size()>1)) {
						logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for userAdminApps() - for user {}, found Id {}", user.getOrgUserId(), userApp.getRole().getId());
						// Account Administrator sees only the applications
						// he/she is Administrator
						return true;
					}
				}
			}
		} catch (Exception e) {
			EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
			logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isAccountAdmin operation",
					e);
		}
		return false;
	}


	public boolean isRoleAdmin(EPUser user) {
		try {
			logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has isRoleAdmin access");

					final Map<String, Long> userParams = new HashMap<>();
					userParams.put("userId", user.getId());
					List getRoleFuncListOfUser = dataAccessService.executeNamedQuery("getRoleFunctionsOfUserforAlltheApplications", userParams, null);
					logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has isRoleAdmin access :: getRoleFuncListOfUser" , getRoleFuncListOfUser);
					Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfUser);
					Set<String> getRoleFuncListOfPortalSet1=new HashSet<>();
					Set<String> roleFunSet = new HashSet<>();
					roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|")).collect(Collectors.toSet());
					if (!roleFunSet.isEmpty())
						for (String roleFunction : roleFunSet) {
							String type = externalAccessRolesService.getFunctionCodeType(roleFunction);
							getRoleFuncListOfPortalSet1.add(type);
						}
				
					boolean checkIfFunctionsExits = getRoleFuncListOfPortalSet1.stream()
							.anyMatch(roleFunction -> roleFunction.equalsIgnoreCase("Approver"));
					logger.debug(EELFLoggerDelegate.debugLogger, "Checking if user has approver rolefunction" , checkIfFunctionsExits);

					return checkIfFunctionsExits;
		
		} catch (Exception e) {
			EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
			logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isRoleAdmin operation",
					e);
		}
		return false;
	}

	public boolean isUser(EPUser user) {
		try {
			EPUser currentUser = user != null
					? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null)
					: null;
			if (currentUser != null && currentUser.getId() != null) {
				for (EPUserApp userApp : currentUser.getEPUserApps()) {
					if (!userApp.getApp().getId().equals(ECOMP_APP_ID)) {
						EPRole role = userApp.getRole();
						if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
							if (role.getActive()) {
								return true;
							}
						}
					}
				}
			}
		} catch (Exception e) {
			EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
			logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation", e);
		}
		return false;
	}

	@Override
	@EPMetricsLog
	public List<EPRole> getRolesByApp(EPUser user, Long appId) {
		List<EPRole> list = new ArrayList<>();
		String sql = "SELECT * FROM FN_ROLE WHERE UPPER(ACTIVE_YN) = 'Y' AND APP_ID = " + appId;
		@SuppressWarnings("unchecked")
		List<EPRole> roles = dataAccessService.executeSQLQuery(sql, EPRole.class, null);
		for (EPRole role : roles) {
			list.add(role);
		}
		return list;
	}

	@Override
	public boolean isAccountAdminOfApplication(EPUser user, EPApp app) {
		Boolean isApplicationAccountAdmin=false;
		try {
					final Map<String, Long> userParams = new HashMap<>();
					userParams.put("userId", user.getId());
					logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, user.getId());
					List<Integer> userAdminApps = new ArrayList<>();
					userAdminApps =dataAccessService.executeNamedQuery("getAdminAppsForTheUser", userParams, null);
					if(!userAdminApps.isEmpty()){
					isApplicationAccountAdmin=userAdminApps.contains((int) (long) app.getId());
					logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user is true{} ,appId {}", user.getId(),app.getId());
					}
			} catch (Exception e) {
			EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
			logger.error(EELFLoggerDelegate.errorLogger,
					"Exception occurred while executing isAccountAdminOfApplication operation", e);
		}
		logger.debug(EELFLoggerDelegate.debugLogger, "In AdminRolesServiceImpl() - isAccountAdminOfApplication = {} and userId ={} ", isApplicationAccountAdmin, user.getOrgUserId());
		return isApplicationAccountAdmin;

	}

	@Override
	public Set<String> getAllAppsFunctionsOfUser(String OrgUserId) throws RoleFunctionException {
		final Map<String, String> params = new HashMap<>();
		params.put("userId", OrgUserId);
		List getRoleFuncListOfPortal = dataAccessService.executeNamedQuery("getAllAppsFunctionsOfUser", params, null);
		Set<String> getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfPortal);
		Set<String> roleFunSet = new HashSet<>();
		roleFunSet = getRoleFuncListOfPortalSet.stream().filter(x -> x.contains("|")).collect(Collectors.toSet());
		if (!roleFunSet.isEmpty())
			for (String roleFunction : roleFunSet) {
				String roleFun = EcompPortalUtils.getFunctionCode(roleFunction);
				getRoleFuncListOfPortalSet.remove(roleFunction);
				getRoleFuncListOfPortalSet.add(roleFun);
			}

		Set<String> finalRoleFunctionSet = new HashSet<>();
		for (String roleFn : getRoleFuncListOfPortalSet) {
			finalRoleFunctionSet.add(EPUserUtils.decodeFunctionCode(roleFn));
		}
		
		return finalRoleFunctionSet;
	}

	
	@Override
	public boolean isAccountAdminOfAnyActiveorInactiveApplication(EPUser user, EPApp app) {
		Boolean isApplicationAccountAdmin=false;
		try {
					final Map<String, Long> userParams = new HashMap<>();
					userParams.put("userId", user.getId());	
					logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, user.getId());
					List<Integer> userAdminApps = new ArrayList<>();
					userAdminApps =dataAccessService.executeNamedQuery("getAllAdminAppsofTheUser", userParams, null);
					if(!userAdminApps.isEmpty()){
					isApplicationAccountAdmin=userAdminApps.contains((int) (long) app.getId());
					logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for user is true{} ,appId {}", user.getId(),app.getId());
					}					
			} catch (Exception e) {
			EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
			logger.error(EELFLoggerDelegate.errorLogger,
					"Exception occurred while executing isAccountAdminOfApplication operation", e);
		}
		logger.debug(EELFLoggerDelegate.debugLogger, "In AdminRolesServiceImpl() - isAccountAdminOfApplication = {} and userId ={} ", isApplicationAccountAdmin, user.getOrgUserId());
		return isApplicationAccountAdmin;

	}
}