c19730e065d36c7f878840daca2baff2ac39a94a
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / service / WidgetServiceImpl.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.List;
24
25 import javax.annotation.PostConstruct;
26 import javax.servlet.http.HttpServletResponse;
27
28 import org.hibernate.Session;
29 import org.hibernate.SessionFactory;
30 import org.hibernate.Transaction;
31 import org.springframework.beans.factory.annotation.Autowired;
32 import org.springframework.context.annotation.EnableAspectJAutoProxy;
33 import org.springframework.stereotype.Service;
34 import org.springframework.transaction.annotation.Transactional;
35
36 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
37 import org.openecomp.portalsdk.core.service.DataAccessService;
38 import org.openecomp.portalsdk.core.util.SystemProperties;
39 import org.openecomp.portalapp.portal.domain.EPUser;
40 import org.openecomp.portalapp.portal.domain.EPUserApp;
41 import org.openecomp.portalapp.portal.domain.Widget;
42 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
43 import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
44 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
45 import org.openecomp.portalapp.portal.transport.FieldsValidator;
46 import org.openecomp.portalapp.portal.transport.OnboardingWidget;
47 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
48 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
49
50 @Service("widgetService")
51 @Transactional
52 @org.springframework.context.annotation.Configuration
53 @EnableAspectJAutoProxy
54 @EPMetricsLog
55 public class WidgetServiceImpl implements WidgetService {
56
57         private static final String baseSqlToken = " widget.WIDGET_ID, widget.WDG_NAME, widget.APP_ID, app.APP_NAME, widget.WDG_WIDTH, widget.WDG_HEIGHT, widget.WDG_URL"
58                         + " from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID";
59
60         private String validAppsFilter = "";
61
62         private Long LONG_ECOMP_APP_ID = 1L;
63         private Long ACCOUNT_ADMIN_ROLE_ID = 999L;
64         private static final Long DUBLICATED_FIELD_VALUE_ECOMP_ERROR = new Long(EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
65
66         private static final String urlField = "url";
67
68         private static final String nameField = "name";
69         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetServiceImpl.class);
70
71         @Autowired
72         AdminRolesService adminRolesService;
73         @Autowired
74         private SessionFactory sessionFactory;
75         @Autowired
76         private DataAccessService dataAccessService;
77
78         @PostConstruct
79         private void init() {
80                 try {
81                         validAppsFilter = " AND app.ENABLED = 'Y' AND app.APP_ID != " + SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID);
82                         ACCOUNT_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ACCOUNT_ADMIN_ROLE_ID));
83                         LONG_ECOMP_APP_ID = Long.valueOf(SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID));
84                 } catch(Exception e) {
85                         logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
86                 }
87         }
88         
89         private String sqlWidgetsForAllApps() {
90                 return "SELECT" + baseSqlToken + validAppsFilter;
91         }
92
93         private String sqlWidgetsForAllAppsWhereUserIsAdmin(Long userId) {
94                 return "SELECT" + baseSqlToken + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = " + userId
95                                 + " AND FN_USER_ROLE.ROLE_ID = " + ACCOUNT_ADMIN_ROLE_ID + validAppsFilter;
96         }
97
98         private String sqlWidgetsForAllAppsWhereUserHasAnyRole(Long userId) {
99                 return "SELECT DISTINCT" + baseSqlToken + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = "
100                                 + userId + validAppsFilter;
101         }
102
103         @SuppressWarnings("unchecked")
104         @Override
105         public List<OnboardingWidget> getOnboardingWidgets(EPUser user, boolean managed) {
106                 List<OnboardingWidget> onboardingWidgets = new ArrayList<OnboardingWidget>();
107                 String sql = null;
108                 if (adminRolesService.isSuperAdmin(user)) {
109                         sql = this.sqlWidgetsForAllApps();
110                 } else if (managed) {
111                         if (adminRolesService.isAccountAdmin(user)) {
112                                 sql = this.sqlWidgetsForAllAppsWhereUserIsAdmin(user.getId());
113                         }
114                 } else if (adminRolesService.isAccountAdmin(user) || adminRolesService.isUser(user)) {
115                         sql = this.sqlWidgetsForAllAppsWhereUserHasAnyRole(user.getId());
116                 }
117                 if (sql != null) {
118                         onboardingWidgets = dataAccessService.executeSQLQuery(sql, OnboardingWidget.class, null);
119                 }
120                 return onboardingWidgets;
121         }
122
123         private static final Object syncRests = new Object();
124
125         private boolean isUserAdminOfAppForWidget(boolean superAdmin, Long userId, Long appId) {
126                 if (!superAdmin) {
127                         @SuppressWarnings("unchecked")
128                         List<EPUserApp> userRoles = dataAccessService.getList(EPUserApp.class,
129                                         " where userId = " + userId + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID + " and app.id = " + appId, null, null);
130                         return (userRoles.size() > 0);
131                 }
132                 return true;
133         }
134
135         private void validateOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) {
136                 @SuppressWarnings("unchecked")
137                 List<Widget> widgets = dataAccessService.getList(Widget.class,
138                                 " where url = '" + onboardingWidget.url + "'" + " or name = '" + onboardingWidget.name + "'", null, null);
139                 boolean dublicatedUrl = false;
140                 boolean dublicatedName = false;
141                 for (Widget widget : widgets) {
142                         if (onboardingWidget.id != null && onboardingWidget.id.equals(widget.getId())) {
143                                 // widget should not be compared with itself
144                                 continue;
145                         }
146                         if (!dublicatedUrl && widget.getUrl().equals(onboardingWidget.url)) {
147                                 dublicatedUrl = true;
148                                 if (dublicatedName) {
149                                         break;
150                                 }
151                         }
152                         if (!dublicatedName && widget.getName().equalsIgnoreCase(onboardingWidget.name) && widget.getAppId().equals(onboardingWidget.appId)) {
153                                 dublicatedName = true;
154                                 if (dublicatedUrl) {
155                                         break;
156                                 }
157                         }
158                 }
159                 if (dublicatedUrl || dublicatedName) {
160                         if (dublicatedUrl) {
161                                 fieldsValidator.addProblematicFieldName(urlField);
162                         }
163                         if (dublicatedName) {
164                                 fieldsValidator.addProblematicFieldName(nameField);
165                         }
166                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
167                         fieldsValidator.errorCode = DUBLICATED_FIELD_VALUE_ECOMP_ERROR;
168                 }
169         }
170
171         private void applyOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) {
172                 boolean result = false;
173                 Session localSession = null;
174                 Transaction transaction = null;
175                 try {
176                         localSession = sessionFactory.openSession();
177                         transaction = localSession.beginTransaction();
178                         Widget widget;
179                         if (onboardingWidget.id == null) {
180                                 widget = new Widget();
181                         } else {
182                                 widget = (Widget) localSession.get(Widget.class, onboardingWidget.id);
183                         }
184                         widget.setAppId(onboardingWidget.appId);
185                         widget.setName(onboardingWidget.name);
186                         widget.setWidth(onboardingWidget.width);
187                         widget.setHeight(onboardingWidget.height);
188                         widget.setUrl(onboardingWidget.url);
189                         localSession.saveOrUpdate(widget);
190                         transaction.commit();
191                         result = true;
192                 } catch (Exception e) {
193                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
194                         EcompPortalUtils.rollbackTransaction(transaction, "applyOnboardingWidget rollback, exception = " + e);
195                 } finally {
196                         EcompPortalUtils.closeLocalSession(localSession, "applyOnboardingWidget");
197                 }
198                 if (!result) {
199                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
200                 }
201         }
202
203         private FieldsValidator updateOrSaveWidget(boolean superAdmin, Long userId, OnboardingWidget onboardingWidget) {
204                 FieldsValidator fieldsValidator = new FieldsValidator();
205                 if (!this.isUserAdminOfAppForWidget(superAdmin, userId, onboardingWidget.appId)) {
206                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
207                         return fieldsValidator;
208                 }
209                 synchronized (syncRests) {
210                         // onboardingWidget.id is null for POST and not null for PUT
211                         if (onboardingWidget.id == null) {
212                                 this.validateOnboardingWidget(onboardingWidget, fieldsValidator);
213                         } else {
214                                 Widget widget = (Widget) dataAccessService.getDomainObject(Widget.class, onboardingWidget.id, null);
215                                 if (widget == null || widget.getId() == null) {
216                                         // Widget not found
217                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
218                                         return fieldsValidator;
219                                 }
220                                 this.validateOnboardingWidget(onboardingWidget, fieldsValidator);
221                         }
222                         if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
223                                 this.applyOnboardingWidget(onboardingWidget, fieldsValidator);
224                         }
225                 }
226                 return fieldsValidator;
227         }
228
229         @Override
230         public FieldsValidator setOnboardingWidget(EPUser user, OnboardingWidget onboardingWidget) {
231                 if (onboardingWidget.name.length() == 0 || onboardingWidget.url.length() == 0 || onboardingWidget.appId == null
232                                 || onboardingWidget.appId.equals(LONG_ECOMP_APP_ID) || onboardingWidget.width.intValue() <= 0 || onboardingWidget.height.intValue() <= 0) {
233                         if (onboardingWidget.appId.equals(LONG_ECOMP_APP_ID)) {
234                                 // logger.error("Alarm!!! Security breach attempt on user " + user.getFullName() + ", userId = " + user.getUserId());
235                         }
236                         FieldsValidator fieldsValidator = new FieldsValidator();
237                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
238                         return fieldsValidator;
239                 }
240                 return this.updateOrSaveWidget(adminRolesService.isSuperAdmin(user), user.getId(), onboardingWidget);
241         }
242
243         @Override
244         public FieldsValidator deleteOnboardingWidget(EPUser user, Long onboardingWidgetId) {
245                 FieldsValidator fieldsValidator = new FieldsValidator();
246                 synchronized (syncRests) {
247                         Widget widget = (Widget) dataAccessService.getDomainObject(Widget.class, onboardingWidgetId, null);
248                         if (widget != null && widget.getId() != null) { // widget exists
249                                 if (!this.isUserAdminOfAppForWidget(adminRolesService.isSuperAdmin(user), user.getId(), widget.getAppId())) {
250                                         fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
251                                 } else {
252                                         boolean result = false;
253                                         Session localSession = null;
254                                         Transaction transaction = null;
255                                         try {
256                                                 localSession = sessionFactory.openSession();
257                                                 transaction = localSession.beginTransaction();
258                                                 localSession.delete(localSession.get(Widget.class, onboardingWidgetId));
259                                                 transaction.commit();
260                                                 result = true;
261                                         } catch (Exception e) {
262                                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e);
263                                                 EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingWidget rollback, exception = " + e);
264                                         } finally {
265                                                 EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingWidget");
266                                         }
267                                         if (!result) {
268                                                 fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
269                                         }
270                                 }
271                         }
272                 }
273                 return fieldsValidator;
274         }
275
276 }