2 * ================================================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ================================================================================
20 package org.openecomp.portalapp.portal.service;
22 import java.util.ArrayList;
23 import java.util.HashMap;
24 import java.util.List;
27 import javax.annotation.PostConstruct;
29 import org.apache.cxf.common.util.StringUtils;
30 import org.hibernate.Session;
31 import org.hibernate.SessionFactory;
32 import org.hibernate.Transaction;
33 import org.json.JSONArray;
34 import org.json.JSONObject;
35 import org.openecomp.portalapp.portal.domain.EPApp;
36 import org.openecomp.portalapp.portal.domain.EPRole;
37 import org.openecomp.portalapp.portal.domain.EPUser;
38 import org.openecomp.portalapp.portal.domain.EPUserApp;
39 import org.openecomp.portalapp.portal.domain.UserIdRoleId;
40 import org.openecomp.portalapp.portal.domain.UserRole;
41 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
42 import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
43 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
44 import org.openecomp.portalapp.portal.transport.AppNameIdIsAdmin;
45 import org.openecomp.portalapp.portal.transport.AppsListWithAdminRole;
46 import org.openecomp.portalapp.portal.transport.ExternalAccessUser;
47 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
48 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
49 import org.openecomp.portalapp.portal.utils.PortalConstants;
50 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
51 import org.openecomp.portalsdk.core.service.DataAccessService;
52 import org.openecomp.portalsdk.core.util.SystemProperties;
53 import org.springframework.beans.factory.annotation.Autowired;
54 import org.springframework.context.annotation.EnableAspectJAutoProxy;
55 import org.springframework.http.HttpEntity;
56 import org.springframework.http.HttpHeaders;
57 import org.springframework.http.HttpMethod;
58 import org.springframework.http.ResponseEntity;
59 import org.springframework.stereotype.Service;
60 import org.springframework.transaction.annotation.Transactional;
61 import org.springframework.web.client.RestTemplate;
63 import com.fasterxml.jackson.databind.ObjectMapper;
65 @Service("adminRolesService")
67 @org.springframework.context.annotation.Configuration
68 @EnableAspectJAutoProxy
70 public class AdminRolesServiceImpl implements AdminRolesService {
72 private Long SYS_ADMIN_ROLE_ID = 1L;
73 private Long ACCOUNT_ADMIN_ROLE_ID = 999L;
74 private Long ECOMP_APP_ID = 1L;
76 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesServiceImpl.class);
79 private SessionFactory sessionFactory;
81 private DataAccessService dataAccessService;
83 SearchService searchService;
85 EPAppService appsService;
87 RestTemplate template = new RestTemplate();
92 SYS_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.SYS_ADMIN_ROLE_ID));
93 ACCOUNT_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID));
94 ECOMP_APP_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID));
95 } catch(Exception e) {
96 logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
102 @SuppressWarnings("unchecked")
103 public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(String orgUserId) {
104 AppsListWithAdminRole appsListWithAdminRole = null;
107 List<EPUser> userList = dataAccessService.getList(EPUser.class, " where orgUserId = '" + orgUserId + "'", null,
109 HashMap<Long, Long> appsUserAdmin = new HashMap<Long, Long>();
110 if (userList.size() > 0) {
111 EPUser user = userList.get(0);
112 List<EPUserApp> userAppList = null;
114 userAppList = dataAccessService.getList(EPUserApp.class,
115 " where userId = " + user.getId() + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID, null, null);
116 } catch (Exception e) {
117 logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
118 EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
120 for (EPUserApp userApp : userAppList) {
121 appsUserAdmin.put(userApp.getAppId(), userApp.getUserId());
125 appsListWithAdminRole = new AppsListWithAdminRole();
126 appsListWithAdminRole.orgUserId = orgUserId;
127 List<EPApp> appsList = null;
129 appsList = dataAccessService.getList(EPApp.class, " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", null, null);
130 } catch (Exception e) {
131 logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
132 EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
134 for (EPApp app : appsList) {
135 AppNameIdIsAdmin appNameIdIsAdmin = new AppNameIdIsAdmin();
136 appNameIdIsAdmin.id = app.getId();
137 appNameIdIsAdmin.appName = app.getName();
138 appNameIdIsAdmin.isAdmin = new Boolean(appsUserAdmin.containsKey(app.getId()));
139 appNameIdIsAdmin.restrictedApp = app.isRestrictedApp();
140 appsListWithAdminRole.appsRoles.add(appNameIdIsAdmin);
142 } catch (Exception e) {
143 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing AdminRolesServiceImpl.getAppsWithAdminRoleStateForUser operation, Details:"
144 + EcompPortalUtils.getStackTrace(e));
147 return appsListWithAdminRole;
150 private static final Object syncRests = new Object();
154 @SuppressWarnings("unchecked")
155 public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles) {
156 boolean result = false;
157 // No changes if no new roles list or no userId.
158 if (!StringUtils.isEmpty(newAppsListWithAdminRoles.orgUserId) && newAppsListWithAdminRoles.appsRoles != null) {
159 synchronized (syncRests) {
160 List<EPApp> apps = appsService.getAppsFullList();
161 HashMap<Long, EPApp> enabledApps = new HashMap<Long, EPApp>();
162 for (EPApp app : apps) {
163 if (app.getEnabled().booleanValue() || app.getId() == ECOMP_APP_ID) {
164 enabledApps.put(app.getId(), app);
167 List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<AppNameIdIsAdmin>();
168 for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.appsRoles) {
169 // user Admin role may be added only for enabled apps
170 if (adminRole.isAdmin.booleanValue() && enabledApps.containsKey(adminRole.id)) {
171 newAppsWhereUserIsAdmin.add(adminRole);
175 boolean createNewUser = false;
176 String orgUserId = newAppsListWithAdminRoles.orgUserId.trim();
177 List<EPUser> localUserList = dataAccessService.getList(EPUser.class, " where org_user_id='" + orgUserId + "'",
179 List<EPUserApp> oldAppsWhereUserIsAdmin = new ArrayList<EPUserApp>();
180 if (localUserList.size() > 0) {
181 EPUser tmpUser = localUserList.get(0);
182 oldAppsWhereUserIsAdmin = dataAccessService.getList(EPUserApp.class,
183 " where userId = " + tmpUser.getId() + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID, null,
185 if (oldAppsWhereUserIsAdmin.size() > 0 || newAppsWhereUserIsAdmin.size() > 0) {
188 } else if (newAppsWhereUserIsAdmin.size() > 0) {
189 // we create new user only if he has Admin Role for any App
190 createNewUser = true;
192 if (user != null || createNewUser) {
193 Session localSession = null;
194 Transaction transaction = null;
196 localSession = sessionFactory.openSession();
197 transaction = localSession.beginTransaction();
199 user = this.searchService.searchUserByUserId(orgUserId);
201 // insert the user with active true in order to
203 user.setActive(true);
204 localSession.save(EPUser.class.getName(), user);
207 for (EPUserApp oldUserApp : oldAppsWhereUserIsAdmin) {
208 // user Admin role may be deleted only for enabled
210 if (enabledApps.containsKey(oldUserApp.getAppId())) {
211 localSession.delete(oldUserApp);
214 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
215 EPApp app = (EPApp) localSession.get(EPApp.class, appNameIdIsAdmin.id);
216 EPRole role = (EPRole) localSession.get(EPRole.class, new Long(ACCOUNT_ADMIN_ROLE_ID));
217 EPUserApp newUserApp = new EPUserApp();
218 newUserApp.setUserId(user.getId());
219 newUserApp.setApp(app);
220 newUserApp.setRole(role);
221 localSession.save(EPUserApp.class.getName(), newUserApp);
223 transaction.commit();
225 // Add user admin role for list of centralized applications in external system
226 result = addAdminRoleInExternalSystem(user, localSession, newAppsWhereUserIsAdmin);
227 } catch (Exception e) {
228 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
229 logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 2", e);
231 transaction.rollback();
232 } catch (Exception ex) {
233 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e);
234 logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 3", ex);
238 localSession.close();
239 } catch (Exception e) {
240 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e);
241 logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 4", e);
251 @SuppressWarnings("unchecked")
252 private boolean addAdminRoleInExternalSystem(EPUser user, Session localSession, List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin) {
253 boolean result = false;
255 // Reset All admin role for centralized applications
256 List<EPApp> appList = dataAccessService.executeNamedQuery("getCentralizedApps", null, null);
257 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
258 for (EPApp app : appList) {
260 if (EPCommonSystemProperties
261 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
262 name = user.getOrgUserId() + SystemProperties
263 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
265 String extRole = app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
266 HttpEntity<String> entity = new HttpEntity<>(headers);
267 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
269 ResponseEntity<String> getResponse = template
270 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
271 + "roles/" + extRole, HttpMethod.GET, entity, String.class);
273 if (getResponse.getBody().equals("{}")) {
274 String addDesc = "{\"name\":\"" + extRole + "\"}";
275 HttpEntity<String> roleEntity = new HttpEntity<>(addDesc, headers);
277 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
279 HttpMethod.POST, roleEntity, String.class);
282 HttpEntity<String> deleteUserRole = new HttpEntity<>(headers);
284 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
285 + "userRole/" + name + "/" + extRole,
286 HttpMethod.DELETE, deleteUserRole, String.class);
287 } catch (Exception e) {
288 logger.error(EELFLoggerDelegate.errorLogger,
289 " Role not found for this user may be it gets deleted before", e);
292 } catch (Exception e) {
293 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
294 logger.debug(EELFLoggerDelegate.debugLogger, "Application Not found for app {}",
295 app.getNameSpace(), e.getMessage());
297 logger.error(EELFLoggerDelegate.errorLogger, "Application Not found for app {}",
298 app.getNameSpace(), e);
302 // Add admin role in external application
304 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
305 EPApp app = (EPApp) localSession.get(EPApp.class, appNameIdIsAdmin.id);
307 if (app.getCentralAuth()) {
308 String extRole = app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
309 HttpEntity<String> entity = new HttpEntity<>(headers);
311 if (EPCommonSystemProperties
312 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
313 name = user.getOrgUserId() + SystemProperties
314 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
316 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
317 ResponseEntity<String> getUserRolesResponse = template.exchange(
318 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
319 + "userRoles/user/" + name,
320 HttpMethod.GET, entity, String.class);
321 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
322 if (!getUserRolesResponse.getBody().equals("{}")) {
323 JSONObject jsonObj = new JSONObject(getUserRolesResponse.getBody());
324 JSONArray extRoles = jsonObj.getJSONArray("userRole");
325 final Map<String, JSONObject> extUserRoles = new HashMap<>();
326 for (int i = 0; i < extRoles.length(); i++) {
327 String userRole = extRoles.getJSONObject(i).getString("role");
328 if (userRole.startsWith(app.getNameSpace() + ".")
329 && !userRole.equals(app.getNameSpace() + ".admin")
330 && !userRole.equals(app.getNameSpace() + ".owner")) {
332 extUserRoles.put(userRole, extRoles.getJSONObject(i));
335 if (!extUserRoles.containsKey(extRole)) {
336 // Assign with new apps user admin
338 ExternalAccessUser extUser = new ExternalAccessUser(name, extRole);
339 // Assign user role for an application in external access system
340 ObjectMapper addUserRoleMapper = new ObjectMapper();
341 String userRole = addUserRoleMapper.writeValueAsString(extUser);
342 HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers);
344 SystemProperties.getProperty(
345 EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
346 HttpMethod.POST, addUserRole, String.class);
347 } catch (Exception e) {
348 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user admin role", e);
355 } catch (Exception e) {
356 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
357 logger.debug(EELFLoggerDelegate.errorLogger,
358 "Application name space not found in External system for app {} due to bad rquest name space ", app.getNameSpace(),
361 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin role for application {}",
362 app.getNameSpace(), e);
367 } catch (Exception e) {
369 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin roles operation", e);
374 @SuppressWarnings("unchecked")
376 public boolean isSuperAdmin(EPUser user) {
377 if ((user != null) /* && (user.getId() == null) */ && (user.getOrgUserId() != null)) {
378 String sql = "SELECT user.USER_ID, user.org_user_id, userrole.ROLE_ID, userrole.APP_ID FROM fn_user_role userrole "
379 + "INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID " + "WHERE user.org_user_id = '"
380 + user.getOrgUserId() + "' " + "AND userrole.ROLE_ID = '" + SYS_ADMIN_ROLE_ID + "' "
381 + "AND userrole.APP_ID = '" + ECOMP_APP_ID + "';";
383 List<UserRole> userRoleList = dataAccessService.executeSQLQuery(sql, UserIdRoleId.class, null);
384 if (userRoleList != null && userRoleList.size() > 0) {
387 } catch (Exception e) {
388 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
389 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isSuperAdmin operation", e);
394 // User currentUser = user != null ? (User)
395 // dataAccessService.getDomainObject(User.class, user.getId(), null) :
397 // if (currentUser != null && currentUser.getId() != null) {
398 // for (UserApp userApp : currentUser.getUserApps()) {
399 // if (userApp.getApp().getId().equals(ECOMP_APP_ID) &&
400 // userApp.getRole().getId().equals(SYS_ADMIN_ROLE_ID)) {
401 // // Super Administrator role is global, no need to keep iterating
410 public boolean isAccountAdmin(EPUser user) {
412 EPUser currentUser = user != null
413 ? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null) : null;
414 if (currentUser != null && currentUser.getId() != null) {
415 for (EPUserApp userApp : currentUser.getEPUserApps()) {
416 if (//!userApp.getApp().getId().equals(ECOMP_APP_ID)
418 userApp.getRole().getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
419 // Account Administrator sees only the applications
420 // he/she is Administrator
425 } catch (Exception e) {
426 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
427 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isAccountAdmin operation", e);
432 public boolean isUser(EPUser user) {
434 EPUser currentUser = user != null
435 ? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null) : null;
436 if (currentUser != null && currentUser.getId() != null) {
437 for (EPUserApp userApp : currentUser.getEPUserApps()) {
438 if (!userApp.getApp().getId().equals(ECOMP_APP_ID)) {
439 EPRole role = userApp.getRole();
440 if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
441 if (role.getActive()) {
448 } catch (Exception e) {
449 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
450 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation", e);
457 public List<EPRole> getRolesByApp(EPUser user, Long appId) {
458 List<EPRole> list = new ArrayList<>();
459 String sql = "SELECT * FROM FN_ROLE WHERE UPPER(ACTIVE_YN) = 'Y' AND APP_ID = " + appId;
460 @SuppressWarnings("unchecked")
461 List<EPRole> roles = dataAccessService.executeSQLQuery(sql, EPRole.class, null);
462 for (EPRole role: roles) {