2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
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
26 * https://creativecommons.org/licenses/by/4.0/
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.
34 * ============LICENSE_END============================================
38 package org.onap.portalapp.portal.service;
40 import java.util.ArrayList;
41 import java.util.HashMap;
42 import java.util.List;
44 import java.util.SortedSet;
46 import javax.annotation.PostConstruct;
48 import org.apache.cxf.common.util.StringUtils;
49 import org.hibernate.Session;
50 import org.hibernate.SessionFactory;
51 import org.hibernate.Transaction;
52 import org.json.JSONArray;
53 import org.json.JSONObject;
54 import org.onap.portalapp.portal.domain.EPApp;
55 import org.onap.portalapp.portal.domain.EPRole;
56 import org.onap.portalapp.portal.domain.EPUser;
57 import org.onap.portalapp.portal.domain.EPUserApp;
58 import org.onap.portalapp.portal.domain.UserIdRoleId;
59 import org.onap.portalapp.portal.domain.UserRole;
60 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
61 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
62 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
63 import org.onap.portalapp.portal.transport.AppNameIdIsAdmin;
64 import org.onap.portalapp.portal.transport.AppsListWithAdminRole;
65 import org.onap.portalapp.portal.transport.ExternalAccessUser;
66 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
67 import org.onap.portalapp.portal.utils.EcompPortalUtils;
68 import org.onap.portalapp.portal.utils.PortalConstants;
69 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
70 import org.onap.portalsdk.core.service.DataAccessService;
71 import org.onap.portalsdk.core.util.SystemProperties;
72 import org.springframework.beans.factory.annotation.Autowired;
73 import org.springframework.context.annotation.EnableAspectJAutoProxy;
74 import org.springframework.http.HttpEntity;
75 import org.springframework.http.HttpHeaders;
76 import org.springframework.http.HttpMethod;
77 import org.springframework.http.ResponseEntity;
78 import org.springframework.stereotype.Service;
79 import org.springframework.transaction.annotation.Transactional;
80 import org.springframework.web.client.RestTemplate;
82 import com.fasterxml.jackson.databind.ObjectMapper;
84 @Service("adminRolesService")
86 @org.springframework.context.annotation.Configuration
87 @EnableAspectJAutoProxy
89 public class AdminRolesServiceImpl implements AdminRolesService {
91 private Long SYS_ADMIN_ROLE_ID = 1L;
92 private Long ACCOUNT_ADMIN_ROLE_ID = 999L;
93 private Long ECOMP_APP_ID = 1L;
95 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesServiceImpl.class);
98 private SessionFactory sessionFactory;
100 private DataAccessService dataAccessService;
102 private SearchService searchService;
104 private EPAppService appsService;
106 private RestTemplate template = new RestTemplate();
109 private void init() {
111 SYS_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.SYS_ADMIN_ROLE_ID));
112 ACCOUNT_ADMIN_ROLE_ID = Long
113 .valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID));
114 ECOMP_APP_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID));
115 } catch (Exception e) {
116 logger.error(EELFLoggerDelegate.errorLogger, "init failed", e);
122 @SuppressWarnings("unchecked")
123 public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(String orgUserId) {
124 AppsListWithAdminRole appsListWithAdminRole = null;
127 List<EPUser> userList = null;
128 Map<String, String> userParams = new HashMap<>();
129 userParams.put("org_user_id", orgUserId);
131 userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null);
132 } catch (Exception e) {
133 logger.error(EELFLoggerDelegate.errorLogger, "getEPUserByOrgUserId failed", e);
136 HashMap<Long, Long> appsUserAdmin = new HashMap<Long, Long>();
137 if (userList!= null && userList.size() > 0) {
138 EPUser user = userList.get(0);
139 List<EPUserApp> userAppList = null;
141 userAppList = dataAccessService.getList(EPUserApp.class,
142 " where userId = " + user.getId() + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID, null, null);
143 } catch (Exception e) {
144 logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 1 failed", e);
145 EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
147 for (EPUserApp userApp : userAppList) {
148 appsUserAdmin.put(userApp.getAppId(), userApp.getUserId());
152 appsListWithAdminRole = new AppsListWithAdminRole();
153 appsListWithAdminRole.orgUserId = orgUserId;
154 List<EPApp> appsList = null;
156 appsList = dataAccessService.getList(EPApp.class,
157 " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", null, null);
158 } catch (Exception e) {
159 logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 2 failed", e);
160 EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
162 for (EPApp app : appsList) {
163 AppNameIdIsAdmin appNameIdIsAdmin = new AppNameIdIsAdmin();
164 appNameIdIsAdmin.id = app.getId();
165 appNameIdIsAdmin.appName = app.getName();
166 appNameIdIsAdmin.isAdmin = new Boolean(appsUserAdmin.containsKey(app.getId()));
167 appNameIdIsAdmin.restrictedApp = app.isRestrictedApp();
168 appsListWithAdminRole.appsRoles.add(appNameIdIsAdmin);
170 } catch (Exception e) {
171 logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 3 failed", e);
174 return appsListWithAdminRole;
177 private static final Object syncRests = new Object();
181 @SuppressWarnings("unchecked")
182 public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles) {
183 boolean result = false;
184 // No changes if no new roles list or no userId.
185 if (!StringUtils.isEmpty(newAppsListWithAdminRoles.orgUserId) && newAppsListWithAdminRoles.appsRoles != null) {
186 synchronized (syncRests) {
187 List<EPApp> apps = appsService.getAppsFullList();
188 HashMap<Long, EPApp> enabledApps = new HashMap<Long, EPApp>();
189 for (EPApp app : apps) {
190 if (app.getEnabled().booleanValue() || app.getId() == ECOMP_APP_ID) {
191 enabledApps.put(app.getId(), app);
194 List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<AppNameIdIsAdmin>();
195 for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.appsRoles) {
196 // user Admin role may be added only for enabled apps
197 if (adminRole.isAdmin.booleanValue() && enabledApps.containsKey(adminRole.id)) {
198 newAppsWhereUserIsAdmin.add(adminRole);
202 boolean createNewUser = false;
203 String orgUserId = newAppsListWithAdminRoles.orgUserId.trim();
204 List<EPUser> localUserList = dataAccessService.getList(EPUser.class,
205 " where org_user_id='" + orgUserId + "'", null, null);
206 List<EPUserApp> oldAppsWhereUserIsAdmin = new ArrayList<EPUserApp>();
207 if (localUserList.size() > 0) {
208 EPUser tmpUser = localUserList.get(0);
209 oldAppsWhereUserIsAdmin = dataAccessService.getList(EPUserApp.class,
210 " where userId = " + tmpUser.getId() + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID, null,
212 if (oldAppsWhereUserIsAdmin.size() > 0 || newAppsWhereUserIsAdmin.size() > 0) {
215 } else if (newAppsWhereUserIsAdmin.size() > 0) {
216 // we create new user only if he has Admin Role for any App
217 createNewUser = true;
219 if (user != null || createNewUser) {
220 Session localSession = null;
221 Transaction transaction = null;
223 localSession = sessionFactory.openSession();
224 transaction = localSession.beginTransaction();
226 user = this.searchService.searchUserByUserId(orgUserId);
228 // insert the user with active true in order to
230 user.setActive(true);
231 localSession.save(EPUser.class.getName(), user);
234 for (EPUserApp oldUserApp : oldAppsWhereUserIsAdmin) {
235 // user Admin role may be deleted only for enabled
237 if (enabledApps.containsKey(oldUserApp.getAppId())) {
238 localSession.delete(oldUserApp);
241 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
242 EPApp app = (EPApp) localSession.get(EPApp.class, appNameIdIsAdmin.id);
243 EPRole role = (EPRole) localSession.get(EPRole.class, new Long(ACCOUNT_ADMIN_ROLE_ID));
244 EPUserApp newUserApp = new EPUserApp();
245 newUserApp.setUserId(user.getId());
246 newUserApp.setApp(app);
247 newUserApp.setRole(role);
248 localSession.save(EPUserApp.class.getName(), newUserApp);
250 transaction.commit();
251 if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
252 // Add user admin role for list of centralized applications in external system
253 addAdminRoleInExternalSystem(user, localSession, newAppsWhereUserIsAdmin);
256 } catch (Exception e) {
257 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
258 logger.error(EELFLoggerDelegate.errorLogger,
259 "setAppsWithAdminRoleStateForUser: exception in point 2", e);
261 if(transaction!=null)
262 transaction.rollback();
264 logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: transaction is null cannot rollback");
265 } catch (Exception ex) {
266 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e);
267 logger.error(EELFLoggerDelegate.errorLogger,
268 "setAppsWithAdminRoleStateForUser: exception in point 3", ex);
272 localSession.close();
273 } catch (Exception e) {
274 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e);
275 logger.error(EELFLoggerDelegate.errorLogger,
276 "setAppsWithAdminRoleStateForUser: exception in point 4", e);
286 @SuppressWarnings("unchecked")
287 private boolean addAdminRoleInExternalSystem(EPUser user, Session localSession,
288 List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin) {
289 boolean result = false;
291 // Reset All admin role for centralized applications
292 List<EPApp> appList = dataAccessService.executeNamedQuery("getCentralizedApps", null, null);
293 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
294 for (EPApp app : appList) {
296 if (EPCommonSystemProperties
297 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
298 name = user.getOrgUserId() + SystemProperties
299 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
301 String extRole = app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
302 HttpEntity<String> entity = new HttpEntity<>(headers);
303 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
305 ResponseEntity<String> getResponse = template
306 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
307 + "roles/" + extRole, HttpMethod.GET, entity, String.class);
309 if (getResponse.getBody().equals("{}")) {
310 String addDesc = "{\"name\":\"" + extRole + "\"}";
311 HttpEntity<String> roleEntity = new HttpEntity<>(addDesc, headers);
313 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
315 HttpMethod.POST, roleEntity, String.class);
318 HttpEntity<String> deleteUserRole = new HttpEntity<>(headers);
320 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
321 + "userRole/" + name + "/" + extRole,
322 HttpMethod.DELETE, deleteUserRole, String.class);
323 } catch (Exception e) {
324 logger.error(EELFLoggerDelegate.errorLogger,
325 " Role not found for this user may be it gets deleted before", e);
328 } catch (Exception e) {
329 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
330 logger.debug(EELFLoggerDelegate.debugLogger, "Application Not found for app {}",
331 app.getNameSpace(), e.getMessage());
333 logger.error(EELFLoggerDelegate.errorLogger, "Application Not found for app {}",
334 app.getNameSpace(), e);
338 // Add admin role in external application
340 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
341 EPApp app = (EPApp) localSession.get(EPApp.class, appNameIdIsAdmin.id);
343 if (app.getCentralAuth()) {
344 String extRole = app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
345 HttpEntity<String> entity = new HttpEntity<>(headers);
347 if (EPCommonSystemProperties
348 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
349 name = user.getOrgUserId() + SystemProperties
350 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
352 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
353 ResponseEntity<String> getUserRolesResponse = template.exchange(
354 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
355 + "userRoles/user/" + name,
356 HttpMethod.GET, entity, String.class);
357 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
358 if (!getUserRolesResponse.getBody().equals("{}")) {
359 JSONObject jsonObj = new JSONObject(getUserRolesResponse.getBody());
360 JSONArray extRoles = jsonObj.getJSONArray("userRole");
361 final Map<String, JSONObject> extUserRoles = new HashMap<>();
362 for (int i = 0; i < extRoles.length(); i++) {
363 String userRole = extRoles.getJSONObject(i).getString("role");
364 if (userRole.startsWith(app.getNameSpace() + ".")
365 && !userRole.equals(app.getNameSpace() + ".admin")
366 && !userRole.equals(app.getNameSpace() + ".owner")) {
368 extUserRoles.put(userRole, extRoles.getJSONObject(i));
371 if (!extUserRoles.containsKey(extRole)) {
372 // Assign with new apps user admin
374 ExternalAccessUser extUser = new ExternalAccessUser(name, extRole);
375 // Assign user role for an application in external access system
376 ObjectMapper addUserRoleMapper = new ObjectMapper();
377 String userRole = addUserRoleMapper.writeValueAsString(extUser);
378 HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers);
380 SystemProperties.getProperty(
381 EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
382 HttpMethod.POST, addUserRole, String.class);
383 } catch (Exception e) {
384 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user admin role", e);
391 } catch (Exception e) {
392 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
393 logger.debug(EELFLoggerDelegate.errorLogger,
394 "Application name space not found in External system for app {} due to bad rquest name space ",
395 app.getNameSpace(), e.getMessage());
397 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin role for application {}",
398 app.getNameSpace(), e);
403 } catch (Exception e) {
405 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin roles operation", e);
410 @SuppressWarnings("unchecked")
412 public boolean isSuperAdmin(EPUser user) {
413 if ((user != null) && (user.getOrgUserId() != null)) {
414 String sql = "SELECT user.USER_ID, user.org_user_id, userrole.ROLE_ID, userrole.APP_ID FROM fn_user_role userrole "
415 + "INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID " + "WHERE user.org_user_id = '"
416 + user.getOrgUserId() + "' " + "AND userrole.ROLE_ID = '" + SYS_ADMIN_ROLE_ID + "' "
417 + "AND userrole.APP_ID = '" + ECOMP_APP_ID + "';";
419 List<UserRole> userRoleList = dataAccessService.executeSQLQuery(sql, UserIdRoleId.class, null);
420 if (userRoleList != null && userRoleList.size() > 0) {
423 } catch (Exception e) {
424 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
425 logger.error(EELFLoggerDelegate.errorLogger,
426 "Exception occurred while executing isSuperAdmin operation", e);
432 public boolean isAccountAdmin(EPUser user) {
434 EPUser currentUser = user != null
435 ? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null)
437 if (currentUser != null && currentUser.getId() != null) {
438 for (EPUserApp userApp : currentUser.getEPUserApps()) {
439 if (userApp.getRole().getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
440 // Account Administrator sees only the applications
441 // he/she is Administrator
446 } catch (Exception e) {
447 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
448 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isAccountAdmin operation",
454 public boolean isUser(EPUser user) {
456 EPUser currentUser = user != null
457 ? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null)
459 if (currentUser != null && currentUser.getId() != null) {
460 for (EPUserApp userApp : currentUser.getEPUserApps()) {
461 if (!userApp.getApp().getId().equals(ECOMP_APP_ID)) {
462 EPRole role = userApp.getRole();
463 if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
464 if (role.getActive()) {
471 } catch (Exception e) {
472 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
473 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation", e);
480 public List<EPRole> getRolesByApp(EPUser user, Long appId) {
481 List<EPRole> list = new ArrayList<>();
482 String sql = "SELECT * FROM FN_ROLE WHERE UPPER(ACTIVE_YN) = 'Y' AND APP_ID = " + appId;
483 @SuppressWarnings("unchecked")
484 List<EPRole> roles = dataAccessService.executeSQLQuery(sql, EPRole.class, null);
485 for (EPRole role : roles) {
492 public boolean isAccountAdminOfApplication(EPUser user, EPApp app) {
494 EPUser currentUser = user != null
495 ? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null) : null;
496 if (currentUser != null && currentUser.getId() != null) {
497 SortedSet<EPUserApp> userApps = currentUser.getEPUserApps();
498 EPUserApp userApp = userApps.stream()
499 .filter(x -> x.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)
500 && x.getApp().getId().equals(app.getId()))
501 .findAny().orElse(null);
502 if (userApp != null) {
506 } catch (Exception e) {
507 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
508 logger.error(EELFLoggerDelegate.errorLogger,
509 "Exception occurred while executing isAccountAdminOfApplication operation", e);