2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright © 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============================================
36 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
38 package org.openecomp.portalapp.portal.service;
40 import java.util.ArrayList;
41 import java.util.HashMap;
42 import java.util.List;
45 import javax.annotation.PostConstruct;
47 import org.apache.cxf.common.util.StringUtils;
48 import org.hibernate.Session;
49 import org.hibernate.SessionFactory;
50 import org.hibernate.Transaction;
51 import org.json.JSONArray;
52 import org.json.JSONObject;
53 import org.openecomp.portalapp.portal.domain.EPApp;
54 import org.openecomp.portalapp.portal.domain.EPRole;
55 import org.openecomp.portalapp.portal.domain.EPUser;
56 import org.openecomp.portalapp.portal.domain.EPUserApp;
57 import org.openecomp.portalapp.portal.domain.UserIdRoleId;
58 import org.openecomp.portalapp.portal.domain.UserRole;
59 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
60 import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
61 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
62 import org.openecomp.portalapp.portal.transport.AppNameIdIsAdmin;
63 import org.openecomp.portalapp.portal.transport.AppsListWithAdminRole;
64 import org.openecomp.portalapp.portal.transport.ExternalAccessUser;
65 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
66 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
67 import org.openecomp.portalapp.portal.utils.PortalConstants;
68 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
69 import org.openecomp.portalsdk.core.service.DataAccessService;
70 import org.openecomp.portalsdk.core.util.SystemProperties;
71 import org.springframework.beans.factory.annotation.Autowired;
72 import org.springframework.context.annotation.EnableAspectJAutoProxy;
73 import org.springframework.http.HttpEntity;
74 import org.springframework.http.HttpHeaders;
75 import org.springframework.http.HttpMethod;
76 import org.springframework.http.ResponseEntity;
77 import org.springframework.stereotype.Service;
78 import org.springframework.transaction.annotation.Transactional;
79 import org.springframework.web.client.RestTemplate;
81 import com.fasterxml.jackson.databind.ObjectMapper;
83 @Service("adminRolesService")
85 @org.springframework.context.annotation.Configuration
86 @EnableAspectJAutoProxy
88 public class AdminRolesServiceImpl implements AdminRolesService {
90 private Long SYS_ADMIN_ROLE_ID = 1L;
91 private Long ACCOUNT_ADMIN_ROLE_ID = 999L;
92 private Long ECOMP_APP_ID = 1L;
94 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesServiceImpl.class);
97 private SessionFactory sessionFactory;
99 private DataAccessService dataAccessService;
101 private SearchService searchService;
103 private EPAppService appsService;
105 private RestTemplate template = new RestTemplate();
108 private void init() {
110 SYS_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.SYS_ADMIN_ROLE_ID));
111 ACCOUNT_ADMIN_ROLE_ID = Long
112 .valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID));
113 ECOMP_APP_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID));
114 } catch (Exception e) {
115 logger.error(EELFLoggerDelegate.errorLogger, "init failed", e);
121 @SuppressWarnings("unchecked")
122 public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(String orgUserId) {
123 AppsListWithAdminRole appsListWithAdminRole = null;
126 List<EPUser> userList = dataAccessService.getList(EPUser.class, " where orgUserId = '" + orgUserId + "'",
128 HashMap<Long, Long> appsUserAdmin = new HashMap<Long, Long>();
129 if (userList.size() > 0) {
130 EPUser user = userList.get(0);
131 List<EPUserApp> userAppList = null;
133 userAppList = dataAccessService.getList(EPUserApp.class,
134 " where userId = " + user.getId() + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID, null, null);
135 } catch (Exception e) {
136 logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 1 failed", e);
137 EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
139 for (EPUserApp userApp : userAppList) {
140 appsUserAdmin.put(userApp.getAppId(), userApp.getUserId());
144 appsListWithAdminRole = new AppsListWithAdminRole();
145 appsListWithAdminRole.orgUserId = orgUserId;
146 List<EPApp> appsList = null;
148 appsList = dataAccessService.getList(EPApp.class,
149 " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", null, null);
150 } catch (Exception e) {
151 logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 2 failed", e);
152 EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
154 for (EPApp app : appsList) {
155 AppNameIdIsAdmin appNameIdIsAdmin = new AppNameIdIsAdmin();
156 appNameIdIsAdmin.id = app.getId();
157 appNameIdIsAdmin.appName = app.getName();
158 appNameIdIsAdmin.isAdmin = new Boolean(appsUserAdmin.containsKey(app.getId()));
159 appNameIdIsAdmin.restrictedApp = app.isRestrictedApp();
160 appsListWithAdminRole.appsRoles.add(appNameIdIsAdmin);
162 } catch (Exception e) {
163 logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 3 failed", e);
166 return appsListWithAdminRole;
169 private static final Object syncRests = new Object();
173 @SuppressWarnings("unchecked")
174 public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles) {
175 boolean result = false;
176 // No changes if no new roles list or no userId.
177 if (!StringUtils.isEmpty(newAppsListWithAdminRoles.orgUserId) && newAppsListWithAdminRoles.appsRoles != null) {
178 synchronized (syncRests) {
179 List<EPApp> apps = appsService.getAppsFullList();
180 HashMap<Long, EPApp> enabledApps = new HashMap<Long, EPApp>();
181 for (EPApp app : apps) {
182 if (app.getEnabled().booleanValue() || app.getId() == ECOMP_APP_ID) {
183 enabledApps.put(app.getId(), app);
186 List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<AppNameIdIsAdmin>();
187 for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.appsRoles) {
188 // user Admin role may be added only for enabled apps
189 if (adminRole.isAdmin.booleanValue() && enabledApps.containsKey(adminRole.id)) {
190 newAppsWhereUserIsAdmin.add(adminRole);
194 boolean createNewUser = false;
195 String orgUserId = newAppsListWithAdminRoles.orgUserId.trim();
196 List<EPUser> localUserList = dataAccessService.getList(EPUser.class,
197 " where org_user_id='" + orgUserId + "'", null, null);
198 List<EPUserApp> oldAppsWhereUserIsAdmin = new ArrayList<EPUserApp>();
199 if (localUserList.size() > 0) {
200 EPUser tmpUser = localUserList.get(0);
201 oldAppsWhereUserIsAdmin = dataAccessService.getList(EPUserApp.class,
202 " where userId = " + tmpUser.getId() + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID, null,
204 if (oldAppsWhereUserIsAdmin.size() > 0 || newAppsWhereUserIsAdmin.size() > 0) {
207 } else if (newAppsWhereUserIsAdmin.size() > 0) {
208 // we create new user only if he has Admin Role for any App
209 createNewUser = true;
211 if (user != null || createNewUser) {
212 Session localSession = null;
213 Transaction transaction = null;
215 localSession = sessionFactory.openSession();
216 transaction = localSession.beginTransaction();
218 user = this.searchService.searchUserByUserId(orgUserId);
220 // insert the user with active true in order to
222 user.setActive(true);
223 localSession.save(EPUser.class.getName(), user);
226 for (EPUserApp oldUserApp : oldAppsWhereUserIsAdmin) {
227 // user Admin role may be deleted only for enabled
229 if (enabledApps.containsKey(oldUserApp.getAppId())) {
230 localSession.delete(oldUserApp);
233 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
234 EPApp app = (EPApp) localSession.get(EPApp.class, appNameIdIsAdmin.id);
235 EPRole role = (EPRole) localSession.get(EPRole.class, new Long(ACCOUNT_ADMIN_ROLE_ID));
236 EPUserApp newUserApp = new EPUserApp();
237 newUserApp.setUserId(user.getId());
238 newUserApp.setApp(app);
239 newUserApp.setRole(role);
240 localSession.save(EPUserApp.class.getName(), newUserApp);
242 transaction.commit();
244 // Add user admin role for list of centralized applications in external system
245 result = addAdminRoleInExternalSystem(user, localSession, newAppsWhereUserIsAdmin);
246 } catch (Exception e) {
247 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
248 logger.error(EELFLoggerDelegate.errorLogger,
249 "setAppsWithAdminRoleStateForUser: exception in point 2", e);
251 if(transaction!=null)
252 transaction.rollback();
254 logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: transaction is null cannot rollback");
255 } catch (Exception ex) {
256 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e);
257 logger.error(EELFLoggerDelegate.errorLogger,
258 "setAppsWithAdminRoleStateForUser: exception in point 3", ex);
262 localSession.close();
263 } catch (Exception e) {
264 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e);
265 logger.error(EELFLoggerDelegate.errorLogger,
266 "setAppsWithAdminRoleStateForUser: exception in point 4", e);
276 @SuppressWarnings("unchecked")
277 private boolean addAdminRoleInExternalSystem(EPUser user, Session localSession,
278 List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin) {
279 boolean result = false;
281 // Reset All admin role for centralized applications
282 List<EPApp> appList = dataAccessService.executeNamedQuery("getCentralizedApps", null, null);
283 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
284 for (EPApp app : appList) {
286 if (EPCommonSystemProperties
287 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
288 name = user.getOrgUserId() + SystemProperties
289 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
291 String extRole = app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
292 HttpEntity<String> entity = new HttpEntity<>(headers);
293 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
295 ResponseEntity<String> getResponse = template
296 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
297 + "roles/" + extRole, HttpMethod.GET, entity, String.class);
299 if (getResponse.getBody().equals("{}")) {
300 String addDesc = "{\"name\":\"" + extRole + "\"}";
301 HttpEntity<String> roleEntity = new HttpEntity<>(addDesc, headers);
303 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
305 HttpMethod.POST, roleEntity, String.class);
308 HttpEntity<String> deleteUserRole = new HttpEntity<>(headers);
310 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
311 + "userRole/" + name + "/" + extRole,
312 HttpMethod.DELETE, deleteUserRole, String.class);
313 } catch (Exception e) {
314 logger.error(EELFLoggerDelegate.errorLogger,
315 " Role not found for this user may be it gets deleted before", e);
318 } catch (Exception e) {
319 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
320 logger.debug(EELFLoggerDelegate.debugLogger, "Application Not found for app {}",
321 app.getNameSpace(), e.getMessage());
323 logger.error(EELFLoggerDelegate.errorLogger, "Application Not found for app {}",
324 app.getNameSpace(), e);
328 // Add admin role in external application
330 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
331 EPApp app = (EPApp) localSession.get(EPApp.class, appNameIdIsAdmin.id);
333 if (app.getCentralAuth()) {
334 String extRole = app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
335 HttpEntity<String> entity = new HttpEntity<>(headers);
337 if (EPCommonSystemProperties
338 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
339 name = user.getOrgUserId() + SystemProperties
340 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
342 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
343 ResponseEntity<String> getUserRolesResponse = template.exchange(
344 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
345 + "userRoles/user/" + name,
346 HttpMethod.GET, entity, String.class);
347 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
348 if (!getUserRolesResponse.getBody().equals("{}")) {
349 JSONObject jsonObj = new JSONObject(getUserRolesResponse.getBody());
350 JSONArray extRoles = jsonObj.getJSONArray("userRole");
351 final Map<String, JSONObject> extUserRoles = new HashMap<>();
352 for (int i = 0; i < extRoles.length(); i++) {
353 String userRole = extRoles.getJSONObject(i).getString("role");
354 if (userRole.startsWith(app.getNameSpace() + ".")
355 && !userRole.equals(app.getNameSpace() + ".admin")
356 && !userRole.equals(app.getNameSpace() + ".owner")) {
358 extUserRoles.put(userRole, extRoles.getJSONObject(i));
361 if (!extUserRoles.containsKey(extRole)) {
362 // Assign with new apps user admin
364 ExternalAccessUser extUser = new ExternalAccessUser(name, extRole);
365 // Assign user role for an application in external access system
366 ObjectMapper addUserRoleMapper = new ObjectMapper();
367 String userRole = addUserRoleMapper.writeValueAsString(extUser);
368 HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers);
370 SystemProperties.getProperty(
371 EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
372 HttpMethod.POST, addUserRole, String.class);
373 } catch (Exception e) {
374 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user admin role", e);
381 } catch (Exception e) {
382 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
383 logger.debug(EELFLoggerDelegate.errorLogger,
384 "Application name space not found in External system for app {} due to bad rquest name space ",
385 app.getNameSpace(), e.getMessage());
387 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin role for application {}",
388 app.getNameSpace(), e);
393 } catch (Exception e) {
395 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin roles operation", e);
400 @SuppressWarnings("unchecked")
402 public boolean isSuperAdmin(EPUser user) {
403 if ((user != null) /* && (user.getId() == null) */ && (user.getOrgUserId() != null)) {
404 String sql = "SELECT user.USER_ID, user.org_user_id, userrole.ROLE_ID, userrole.APP_ID FROM fn_user_role userrole "
405 + "INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID " + "WHERE user.org_user_id = '"
406 + user.getOrgUserId() + "' " + "AND userrole.ROLE_ID = '" + SYS_ADMIN_ROLE_ID + "' "
407 + "AND userrole.APP_ID = '" + ECOMP_APP_ID + "';";
409 List<UserRole> userRoleList = dataAccessService.executeSQLQuery(sql, UserIdRoleId.class, null);
410 if (userRoleList != null && userRoleList.size() > 0) {
413 } catch (Exception e) {
414 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
415 logger.error(EELFLoggerDelegate.errorLogger,
416 "Exception occurred while executing isSuperAdmin operation", e);
421 // User currentUser = user != null ? (User)
422 // dataAccessService.getDomainObject(User.class, user.getId(), null) :
424 // if (currentUser != null && currentUser.getId() != null) {
425 // for (UserApp userApp : currentUser.getUserApps()) {
426 // if (userApp.getApp().getId().equals(ECOMP_APP_ID) &&
427 // userApp.getRole().getId().equals(SYS_ADMIN_ROLE_ID)) {
428 // // Super Administrator role is global, no need to keep iterating
437 public boolean isAccountAdmin(EPUser user) {
439 EPUser currentUser = user != null
440 ? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null)
442 if (currentUser != null && currentUser.getId() != null) {
443 for (EPUserApp userApp : currentUser.getEPUserApps()) {
444 if (// !userApp.getApp().getId().equals(ECOMP_APP_ID)
446 userApp.getRole().getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
447 // Account Administrator sees only the applications
448 // he/she is Administrator
453 } catch (Exception e) {
454 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
455 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isAccountAdmin operation",
461 public boolean isUser(EPUser user) {
463 EPUser currentUser = user != null
464 ? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null)
466 if (currentUser != null && currentUser.getId() != null) {
467 for (EPUserApp userApp : currentUser.getEPUserApps()) {
468 if (!userApp.getApp().getId().equals(ECOMP_APP_ID)) {
469 EPRole role = userApp.getRole();
470 if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
471 if (role.getActive()) {
478 } catch (Exception e) {
479 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
480 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation", e);
487 public List<EPRole> getRolesByApp(EPUser user, Long appId) {
488 List<EPRole> list = new ArrayList<>();
489 String sql = "SELECT * FROM FN_ROLE WHERE UPPER(ACTIVE_YN) = 'Y' AND APP_ID = " + appId;
490 @SuppressWarnings("unchecked")
491 List<EPRole> roles = dataAccessService.executeSQLQuery(sql, EPRole.class, null);
492 for (EPRole role : roles) {