20daa4fc746a03cd6f59cc1a2d5de6444a131e81
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / service / AdminRolesServiceImpl.java
1 /*-
2  * ================================================================================
3  * ECOMP Portal
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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  * ================================================================================
19  */
20 package org.openecomp.portalapp.portal.service;
21
22 import java.util.ArrayList;
23 import java.util.HashMap;
24 import java.util.List;
25
26 import javax.annotation.PostConstruct;
27
28 import org.apache.cxf.common.util.StringUtils;
29 import org.hibernate.Session;
30 import org.hibernate.SessionFactory;
31 import org.hibernate.Transaction;
32 import org.springframework.beans.factory.annotation.Autowired;
33 import org.springframework.context.annotation.EnableAspectJAutoProxy;
34 import org.springframework.stereotype.Service;
35 import org.springframework.transaction.annotation.Transactional;
36
37 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
38 import org.openecomp.portalsdk.core.service.DataAccessService;
39 import org.openecomp.portalsdk.core.util.SystemProperties;
40 import org.openecomp.portalapp.portal.domain.EPApp;
41 import org.openecomp.portalapp.portal.domain.EPRole;
42 import org.openecomp.portalapp.portal.domain.EPUser;
43 import org.openecomp.portalapp.portal.domain.EPUserApp;
44 import org.openecomp.portalapp.portal.domain.UserIdRoleId;
45 import org.openecomp.portalapp.portal.domain.UserRole;
46 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
47 import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
48 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
49 import org.openecomp.portalapp.portal.transport.AppNameIdIsAdmin;
50 import org.openecomp.portalapp.portal.transport.AppsListWithAdminRole;
51 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
52 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
53
54 @Service("adminRolesService")
55 @Transactional
56 @org.springframework.context.annotation.Configuration
57 @EnableAspectJAutoProxy
58
59 public class AdminRolesServiceImpl implements AdminRolesService {
60
61         private Long SYS_ADMIN_ROLE_ID = 1L;
62         private Long ACCOUNT_ADMIN_ROLE_ID = 999L;
63         private Long ECOMP_APP_ID = 1L;
64
65         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesServiceImpl.class);
66
67         @Autowired
68         private SessionFactory sessionFactory;
69         @Autowired
70         private DataAccessService dataAccessService;
71         @Autowired
72         SearchService searchService;
73         @Autowired
74         EPAppService appsService;
75
76         @PostConstruct
77         private void init() {
78                 try {
79                         SYS_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.SYS_ADMIN_ROLE_ID));
80                         ACCOUNT_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID));
81                         ECOMP_APP_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID));
82                 } catch(Exception e) {
83                         logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
84                 }
85         }
86         
87         @Override
88         @EPMetricsLog
89         @SuppressWarnings("unchecked")
90         public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(String orgUserId) {
91                 AppsListWithAdminRole appsListWithAdminRole = null;
92
93                 try {
94                         List<EPUser> userList = dataAccessService.getList(EPUser.class, " where orgUserId = '" + orgUserId + "'", null,
95                                         null);
96                         HashMap<Long, Long> appsUserAdmin = new HashMap<Long, Long>();
97                         if (userList.size() > 0) {
98                                 EPUser user = userList.get(0);
99                                 List<EPUserApp> userAppList = null;
100                                 try {
101                                         userAppList = dataAccessService.getList(EPUserApp.class,
102                                                         " where userId = " + user.getId() + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID, null, null);
103                                 } catch (Exception e) {
104                                         logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
105                                         EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
106                                 }
107                                 for (EPUserApp userApp : userAppList) {
108                                         appsUserAdmin.put(userApp.getAppId(), userApp.getUserId());
109                                 }
110                         }
111
112                         appsListWithAdminRole = new AppsListWithAdminRole();
113                         appsListWithAdminRole.orgUserId = orgUserId;
114                         List<EPApp> appsList = null;
115                         try {
116                                 appsList = dataAccessService.getList(EPApp.class, "  where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", null, null);
117                         } catch (Exception e) {
118                                 logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
119                                 EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
120                         }
121                         for (EPApp app : appsList) {
122                                 AppNameIdIsAdmin appNameIdIsAdmin = new AppNameIdIsAdmin();
123                                 appNameIdIsAdmin.id = app.getId();
124                                 appNameIdIsAdmin.appName = app.getName();       
125                                 appNameIdIsAdmin.isAdmin = new Boolean(appsUserAdmin.containsKey(app.getId()));
126                                 appNameIdIsAdmin.restrictedApp = app.isRestrictedApp();
127                                 appsListWithAdminRole.appsRoles.add(appNameIdIsAdmin);
128                         }
129                 } catch (Exception e) {
130                         logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing AdminRolesServiceImpl.getAppsWithAdminRoleStateForUser operation, Details:"
131                                                         + EcompPortalUtils.getStackTrace(e));
132                 }
133
134                 return appsListWithAdminRole;
135         }
136
137         private static final Object syncRests = new Object();
138
139         @Override
140         @EPMetricsLog
141         @SuppressWarnings("unchecked")
142         public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles) {
143                 boolean result = false;
144                 // No changes if no new roles list or no userId.
145                 if (!StringUtils.isEmpty(newAppsListWithAdminRoles.orgUserId) && newAppsListWithAdminRoles.appsRoles != null) {
146                         synchronized (syncRests) {
147                                 List<EPApp> apps = appsService.getAppsFullList();
148                                 HashMap<Long, EPApp> enabledApps = new HashMap<Long, EPApp>();
149                                 for (EPApp app : apps) {
150                                         if (app.getEnabled().booleanValue() || app.getId() == ECOMP_APP_ID) {
151                                                 enabledApps.put(app.getId(), app);
152                                         }
153                                 }
154                                 List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<AppNameIdIsAdmin>();
155                                 for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.appsRoles) {
156                                         // user Admin role may be added only for enabled apps
157                                         if (adminRole.isAdmin.booleanValue() && enabledApps.containsKey(adminRole.id)) {
158                                                 newAppsWhereUserIsAdmin.add(adminRole);
159                                         }
160                                 }
161                                 EPUser user = null;
162                                 boolean createNewUser = false;
163                                 String orgUserId = newAppsListWithAdminRoles.orgUserId.trim();
164                                 List<EPUser> localUserList = dataAccessService.getList(EPUser.class, " where org_user_id='" + orgUserId + "'",
165                                                 null, null);
166                                 List<EPUserApp> oldAppsWhereUserIsAdmin = new ArrayList<EPUserApp>();
167                                 if (localUserList.size() > 0) {
168                                         EPUser tmpUser = localUserList.get(0);
169                                         oldAppsWhereUserIsAdmin = dataAccessService.getList(EPUserApp.class,
170                                                         " where userId = " + tmpUser.getId() + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID, null,
171                                                         null);
172                                         if (oldAppsWhereUserIsAdmin.size() > 0 || newAppsWhereUserIsAdmin.size() > 0) {
173                                                 user = tmpUser;
174                                         }
175                                 } else if (newAppsWhereUserIsAdmin.size() > 0) {
176                                         // we create new user only if he has Admin Role for any App
177                                         createNewUser = true;
178                                 }
179                                 if (user != null || createNewUser) {
180                                         Session localSession = null;
181                                         Transaction transaction = null;
182                                         try {
183                                                 localSession = sessionFactory.openSession();
184                                                 transaction = localSession.beginTransaction();
185                                                 if (createNewUser) {
186                                                         user = this.searchService.searchUserByUserId(orgUserId);
187                                                         if (user != null) {
188                                                                 // insert the user with active true in order to
189                                                                 // pass login phase.
190                                                                 user.setActive(true);
191                                                                 localSession.save(EPUser.class.getName(), user);
192                                                         }
193                                                 }
194                                                 for (EPUserApp oldUserApp : oldAppsWhereUserIsAdmin) {
195                                                         // user Admin role may be deleted only for enabled
196                                                         // apps
197                                                         if (enabledApps.containsKey(oldUserApp.getAppId())) {
198                                                                 localSession.delete(oldUserApp);
199                                                         }
200                                                 }
201                                                 for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
202                                                         EPApp app = (EPApp) localSession.get(EPApp.class, appNameIdIsAdmin.id);
203                                                         EPRole role = (EPRole) localSession.get(EPRole.class, new Long(ACCOUNT_ADMIN_ROLE_ID));
204                                                         EPUserApp newUserApp = new EPUserApp();
205                                                         newUserApp.setUserId(user.getId());
206                                                         newUserApp.setApp(app);
207                                                         newUserApp.setRole(role);
208                                                         localSession.save(EPUserApp.class.getName(), newUserApp);
209                                                 }
210                                                 transaction.commit();
211                                                 result = true;
212                                         } catch (Exception e) {
213                                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
214                                                 logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 2", e);
215                                                 try {
216                                                         transaction.rollback();
217                                                 } catch (Exception ex) {
218                                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e);
219                                                         logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 3", ex);
220                                                 }
221                                         } finally {
222                                                 try {
223                                                         localSession.close();
224                                                 } catch (Exception e) {
225                                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoCloseSessionError, e);
226                                                         logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 4", e);
227                                                 }
228                                         }
229                                 }
230                         }
231                 }
232
233                 return result;
234         }
235
236         @SuppressWarnings("unchecked")
237         @Override
238         public boolean isSuperAdmin(EPUser user) {
239                 if ((user != null) /* && (user.getId() == null) */ && (user.getOrgUserId() != null)) {
240                         String sql = "SELECT user.USER_ID, user.org_user_id, userrole.ROLE_ID, userrole.APP_ID FROM fn_user_role userrole "
241                                         + "INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID " + "WHERE user.org_user_id = '"
242                                         + user.getOrgUserId() + "' " + "AND userrole.ROLE_ID = '" + SYS_ADMIN_ROLE_ID + "' "
243                                         + "AND userrole.APP_ID = '" + ECOMP_APP_ID + "';";
244                         try {
245                                 List<UserRole> userRoleList = dataAccessService.executeSQLQuery(sql, UserIdRoleId.class, null);
246                                 if (userRoleList != null && userRoleList.size() > 0) {
247                                         return true;
248                                 }
249                         } catch (Exception e) {
250                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
251                                 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isSuperAdmin operation", e);
252                         }
253                 }
254                 // else
255                 // {
256                 // User currentUser = user != null ? (User)
257                 // dataAccessService.getDomainObject(User.class, user.getId(), null) :
258                 // null;
259                 // if (currentUser != null && currentUser.getId() != null) {
260                 // for (UserApp userApp : currentUser.getUserApps()) {
261                 // if (userApp.getApp().getId().equals(ECOMP_APP_ID) &&
262                 // userApp.getRole().getId().equals(SYS_ADMIN_ROLE_ID)) {
263                 // // Super Administrator role is global, no need to keep iterating
264                 // return true;
265                 // }
266                 // }
267                 // }
268                 // }
269                 return false;
270         }
271
272         public boolean isAccountAdmin(EPUser user) {
273                 try {
274                         EPUser currentUser = user != null
275                                         ? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null) : null;
276                         if (currentUser != null && currentUser.getId() != null) {
277                                 for (EPUserApp userApp : currentUser.getEPUserApps()) {
278                                         if (//!userApp.getApp().getId().equals(ECOMP_APP_ID)
279                                                         // && 
280                                                         userApp.getRole().getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
281                                                 // Account Administrator sees only the applications
282                                                 // he/she is Administrator
283                                                 return true;
284                                         }
285                                 }
286                         }
287                 } catch (Exception e) {
288                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
289                         logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isAccountAdmin operation", e);
290                 }
291                 return false;
292         }
293
294         public boolean isUser(EPUser user) {
295                 try {
296                         EPUser currentUser = user != null
297                                         ? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null) : null;
298                         if (currentUser != null && currentUser.getId() != null) {
299                                 for (EPUserApp userApp : currentUser.getEPUserApps()) {
300                                         if (!userApp.getApp().getId().equals(ECOMP_APP_ID)) {
301                                                 EPRole role = userApp.getRole();
302                                                 if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
303                                                         if (role.getActive()) {
304                                                                 return true;
305                                                         }
306                                                 }
307                                         }
308                                 }
309                         }
310                 } catch (Exception e) {
311                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
312                         logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation", e);
313                 }
314                 return false;
315         }
316
317         @Override
318         @EPMetricsLog
319         public List<EPRole> getRolesByApp(EPUser user, Long appId) {
320                 List<EPRole> list = new ArrayList<>();
321                 String sql = "SELECT * FROM FN_ROLE WHERE APP_ID = " + appId;
322                 @SuppressWarnings("unchecked")
323                 List<EPRole> roles = dataAccessService.executeSQLQuery(sql, EPRole.class, null);
324                 for (EPRole role: roles) {
325                         list.add(role);
326                 }
327                 return list;
328         }
329 }