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 if(transaction!=null)
232 transaction.rollback();
234 logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: transaction is null cannot rollback");
235 } catch (Exception ex) {
236 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e);
237 logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 3", ex);
241 localSession.close();
242 } catch (Exception e) {
243 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e);
244 logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 4", e);
254 @SuppressWarnings("unchecked")
255 private boolean addAdminRoleInExternalSystem(EPUser user, Session localSession, List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin) {
256 boolean result = false;
258 // Reset All admin role for centralized applications
259 List<EPApp> appList = dataAccessService.executeNamedQuery("getCentralizedApps", null, null);
260 HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
261 for (EPApp app : appList) {
263 if (EPCommonSystemProperties
264 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
265 name = user.getOrgUserId() + SystemProperties
266 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
268 String extRole = app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
269 HttpEntity<String> entity = new HttpEntity<>(headers);
270 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
272 ResponseEntity<String> getResponse = template
273 .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
274 + "roles/" + extRole, HttpMethod.GET, entity, String.class);
276 if (getResponse.getBody().equals("{}")) {
277 String addDesc = "{\"name\":\"" + extRole + "\"}";
278 HttpEntity<String> roleEntity = new HttpEntity<>(addDesc, headers);
280 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
282 HttpMethod.POST, roleEntity, String.class);
285 HttpEntity<String> deleteUserRole = new HttpEntity<>(headers);
287 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
288 + "userRole/" + name + "/" + extRole,
289 HttpMethod.DELETE, deleteUserRole, String.class);
290 } catch (Exception e) {
291 logger.error(EELFLoggerDelegate.errorLogger,
292 " Role not found for this user may be it gets deleted before", e);
295 } catch (Exception e) {
296 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
297 logger.debug(EELFLoggerDelegate.debugLogger, "Application Not found for app {}",
298 app.getNameSpace(), e.getMessage());
300 logger.error(EELFLoggerDelegate.errorLogger, "Application Not found for app {}",
301 app.getNameSpace(), e);
305 // Add admin role in external application
307 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
308 EPApp app = (EPApp) localSession.get(EPApp.class, appNameIdIsAdmin.id);
310 if (app.getCentralAuth()) {
311 String extRole = app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_");
312 HttpEntity<String> entity = new HttpEntity<>(headers);
314 if (EPCommonSystemProperties
315 .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
316 name = user.getOrgUserId() + SystemProperties
317 .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
319 logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system");
320 ResponseEntity<String> getUserRolesResponse = template.exchange(
321 SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
322 + "userRoles/user/" + name,
323 HttpMethod.GET, entity, String.class);
324 logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system");
325 if (!getUserRolesResponse.getBody().equals("{}")) {
326 JSONObject jsonObj = new JSONObject(getUserRolesResponse.getBody());
327 JSONArray extRoles = jsonObj.getJSONArray("userRole");
328 final Map<String, JSONObject> extUserRoles = new HashMap<>();
329 for (int i = 0; i < extRoles.length(); i++) {
330 String userRole = extRoles.getJSONObject(i).getString("role");
331 if (userRole.startsWith(app.getNameSpace() + ".")
332 && !userRole.equals(app.getNameSpace() + ".admin")
333 && !userRole.equals(app.getNameSpace() + ".owner")) {
335 extUserRoles.put(userRole, extRoles.getJSONObject(i));
338 if (!extUserRoles.containsKey(extRole)) {
339 // Assign with new apps user admin
341 ExternalAccessUser extUser = new ExternalAccessUser(name, extRole);
342 // Assign user role for an application in external access system
343 ObjectMapper addUserRoleMapper = new ObjectMapper();
344 String userRole = addUserRoleMapper.writeValueAsString(extUser);
345 HttpEntity<String> addUserRole = new HttpEntity<>(userRole, headers);
347 SystemProperties.getProperty(
348 EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
349 HttpMethod.POST, addUserRole, String.class);
350 } catch (Exception e) {
351 logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user admin role", e);
358 } catch (Exception e) {
359 if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
360 logger.debug(EELFLoggerDelegate.errorLogger,
361 "Application name space not found in External system for app {} due to bad rquest name space ", app.getNameSpace(),
364 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin role for application {}",
365 app.getNameSpace(), e);
370 } catch (Exception e) {
372 logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin roles operation", e);
377 @SuppressWarnings("unchecked")
379 public boolean isSuperAdmin(EPUser user) {
380 if ((user != null) /* && (user.getId() == null) */ && (user.getOrgUserId() != null)) {
381 String sql = "SELECT user.USER_ID, user.org_user_id, userrole.ROLE_ID, userrole.APP_ID FROM fn_user_role userrole "
382 + "INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID " + "WHERE user.org_user_id = '"
383 + user.getOrgUserId() + "' " + "AND userrole.ROLE_ID = '" + SYS_ADMIN_ROLE_ID + "' "
384 + "AND userrole.APP_ID = '" + ECOMP_APP_ID + "';";
386 List<UserRole> userRoleList = dataAccessService.executeSQLQuery(sql, UserIdRoleId.class, null);
387 if (userRoleList != null && userRoleList.size() > 0) {
390 } catch (Exception e) {
391 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
392 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isSuperAdmin operation", e);
397 // User currentUser = user != null ? (User)
398 // dataAccessService.getDomainObject(User.class, user.getId(), null) :
400 // if (currentUser != null && currentUser.getId() != null) {
401 // for (UserApp userApp : currentUser.getUserApps()) {
402 // if (userApp.getApp().getId().equals(ECOMP_APP_ID) &&
403 // userApp.getRole().getId().equals(SYS_ADMIN_ROLE_ID)) {
404 // // Super Administrator role is global, no need to keep iterating
413 public boolean isAccountAdmin(EPUser user) {
415 EPUser currentUser = user != null
416 ? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null) : null;
417 if (currentUser != null && currentUser.getId() != null) {
418 for (EPUserApp userApp : currentUser.getEPUserApps()) {
419 if (//!userApp.getApp().getId().equals(ECOMP_APP_ID)
421 userApp.getRole().getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
422 // Account Administrator sees only the applications
423 // he/she is Administrator
428 } catch (Exception e) {
429 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
430 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isAccountAdmin operation", e);
435 public boolean isUser(EPUser user) {
437 EPUser currentUser = user != null
438 ? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null) : null;
439 if (currentUser != null && currentUser.getId() != null) {
440 for (EPUserApp userApp : currentUser.getEPUserApps()) {
441 if (!userApp.getApp().getId().equals(ECOMP_APP_ID)) {
442 EPRole role = userApp.getRole();
443 if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
444 if (role.getActive()) {
451 } catch (Exception e) {
452 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
453 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation", e);
460 public List<EPRole> getRolesByApp(EPUser user, Long appId) {
461 List<EPRole> list = new ArrayList<>();
462 String sql = "SELECT * FROM FN_ROLE WHERE UPPER(ACTIVE_YN) = 'Y' AND APP_ID = " + appId;
463 @SuppressWarnings("unchecked")
464 List<EPRole> roles = dataAccessService.executeSQLQuery(sql, EPRole.class, null);
465 for (EPRole role: roles) {