90d6ab7840684790349e33bfb67f3c476dacb7e9
[portal.git] / portal-BE / src / main / java / org / onap / portal / service / WidgetService.java
1 /*
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ===================================================================
9  *
10  * Unless otherwise specified, all software contained herein is licensed
11  * under the Apache License, Version 2.0 (the "License");
12  * you may not use this software except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *             http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * Unless otherwise specified, all documentation contained herein is licensed
24  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25  * you may not use this documentation except in compliance with the License.
26  * You may obtain a copy of the License at
27  *
28  *             https://creativecommons.org/licenses/by/4.0/
29  *
30  * Unless required by applicable law or agreed to in writing, documentation
31  * distributed under the License is distributed on an "AS IS" BASIS,
32  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33  * See the License for the specific language governing permissions and
34  * limitations under the License.
35  *
36  * ============LICENSE_END============================================
37  *
38  *
39  */
40
41 package org.onap.portal.service;
42
43 import java.util.ArrayList;
44 import java.util.List;
45 import javax.persistence.EntityManager;
46 import javax.servlet.http.HttpServletResponse;
47 import javax.validation.constraints.NotNull;
48 import org.onap.portal.dao.fn.FnWidgetDao;
49 import org.onap.portal.domain.db.fn.FnUser;
50 import org.onap.portal.domain.db.fn.FnWidget;
51 import org.onap.portal.domain.dto.ecomp.EPUserApp;
52 import org.onap.portal.domain.dto.ecomp.Widget;
53 import org.onap.portal.domain.dto.transport.FieldsValidator;
54 import org.onap.portal.domain.dto.transport.OnboardingWidget;
55 import org.onap.portal.utils.EPCommonSystemProperties;
56 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
57 import org.springframework.beans.factory.annotation.Autowired;
58 import org.springframework.context.annotation.EnableAspectJAutoProxy;
59 import org.springframework.security.access.prepost.PreAuthorize;
60 import org.springframework.stereotype.Service;
61 import org.springframework.transaction.annotation.Transactional;
62
63 @Service
64 @EnableAspectJAutoProxy
65 @Transactional
66 public class WidgetService {
67
68        private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetService.class);
69        private final Long ACCOUNT_ADMIN_ROLE_ID = 999L;
70
71        private static String baseSqlToken =
72                " new org.onap.portal.domain.dto.transport.OnboardingWidget("
73                        + "widget.WIDGET_ID,widget.WDG_NAME,widget.APP_ID,"
74                        + "app.APP_NAME,widget.WDG_WIDTH,widget.WDG_HEIGHT,"
75                        + "widget.WDG_URL) widget.WIDGET_ID,widget.WDG_NAME,widget.APP_ID,app.APP_NAME,widget.WDG_WIDTH,widget.WDG_HEIGHT,widget.WDG_URL from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID";
76
77        private static final String urlField = "url";
78        private static final Long DUBLICATED_FIELD_VALUE_ECOMP_ERROR = new Long(
79                EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
80        private static final String nameField = "name";
81
82        private final AdminRolesService adminRolesService;
83        private final EntityManager entityManager;
84        private final FnWidgetDao fnWidgetDao;
85
86        @Autowired
87        public WidgetService(final AdminRolesService adminRolesService, final EntityManager entityManager,
88                final FnWidgetDao fnWidgetDao) {
89               this.adminRolesService = adminRolesService;
90               this.entityManager = entityManager;
91               this.fnWidgetDao = fnWidgetDao;
92        }
93
94        private static final Object syncRests = new Object();
95
96        public List<OnboardingWidget> getOnboardingWidgets(FnUser user, boolean managed) {
97               if (adminRolesService.isSuperAdmin(user)) {
98                      return entityManager.createQuery(sqlWidgetsForAllApps(), OnboardingWidget.class).getResultList();
99               } else if (managed) {
100                      if (adminRolesService.isAccountAdmin(user)) {
101                             return entityManager
102                                     .createQuery(sqlWidgetsForAllAppsWhereUserIsAdmin(), OnboardingWidget.class)
103                                     .setParameter("USERID", user.getId()).getResultList();
104                      }
105               } else if (adminRolesService.isAccountAdmin(user) || adminRolesService.isUser(user)) {
106                      return entityManager
107                              .createQuery(sqlWidgetsForAllAppsWhereUserHasAnyRole(), OnboardingWidget.class)
108                              .setParameter("USERID", user.getId()).getResultList();
109               }
110               return new ArrayList<>();
111        }
112
113        private String sqlWidgetsForAllApps() {
114               return "SELECT" + baseSqlToken;
115        }
116
117        private String sqlWidgetsForAllAppsWhereUserIsAdmin() {
118               return "SELECT" + baseSqlToken
119                       + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = :USERID AND FN_USER_ROLE.ROLE_ID = "
120                       + ACCOUNT_ADMIN_ROLE_ID;
121        }
122
123        private String sqlWidgetsForAllAppsWhereUserHasAnyRole() {
124               return "SELECT DISTINCT" + baseSqlToken
125                       + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = "
126                       + ":USERID";
127        }
128
129        @PreAuthorize("hasRole('System_Administrator')")
130        public FieldsValidator setOnboardingWidget(final FnUser user, final OnboardingWidget onboardingWidget) {
131               return this.updateOrSaveWidget(true, user.getId(), onboardingWidget);
132        }
133
134        private FieldsValidator updateOrSaveWidget(boolean superAdmin, Long userId, OnboardingWidget onboardingWidget) {
135               FieldsValidator fieldsValidator = new FieldsValidator();
136               if (!this.isUserAdminOfAppForWidget(superAdmin, userId, onboardingWidget.getAppId())) {
137                      fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_FORBIDDEN);
138                      return fieldsValidator;
139               }
140               synchronized (syncRests) {
141                      if (onboardingWidget.getId() == null) {
142                             this.validateOnboardingWidget(onboardingWidget, fieldsValidator);
143                      } else {
144                             FnWidget widget = fnWidgetDao.getOne(onboardingWidget.getId());
145                             if (widget == null || widget.getAppId() == null) {
146                                    fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_NOT_FOUND);
147                                    return fieldsValidator;
148                             }
149                             this.validateOnboardingWidget(onboardingWidget, fieldsValidator);
150                      }
151                      if (fieldsValidator.getHttpStatusCode() == HttpServletResponse.SC_OK) {
152                             this.applyOnboardingWidget(onboardingWidget, fieldsValidator);
153                      }
154               }
155               return fieldsValidator;
156        }
157
158        private boolean isUserAdminOfAppForWidget(boolean superAdmin, Long userId, Long appId) {
159               if (!superAdmin) {
160                      List<EPUserApp> userRoles = getAdminUserRoles(userId, appId);
161                      return (userRoles.size() > 0);
162               }
163               return true;
164        }
165
166        private List<EPUserApp> getAdminUserRoles(Long userId, Long appId) {
167               return entityManager.createQuery(
168                       "SELECT new org.onap.portal.domain.dto.ecomp.EPUserApp(fn.userId, fn.roleId, fn.appId) FROM FnUserRole fn"
169                               + "WHERE  fn.userId = :USERID "
170                               + "AND fn.roleId = :ROLEID "
171                               + "AND fn.appId = :APPID", EPUserApp.class)
172                       .setParameter("USERID", userId)
173                       .setParameter("ROLEID", ACCOUNT_ADMIN_ROLE_ID)
174                       .setParameter("APPID", appId)
175                       .getResultList();
176        }
177
178        private void applyOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) {
179               boolean result;
180               FnWidget widget;
181               if (onboardingWidget.getId() == null) {
182                      widget = new FnWidget();
183               } else {
184                      widget = fnWidgetDao.getOne(onboardingWidget.getId());
185               }
186               widget.setAppId(onboardingWidget.getAppId());
187               widget.setName(onboardingWidget.getName());
188               widget.setWidth(onboardingWidget.getWidth());
189               widget.setHeight(onboardingWidget.getHeight());
190               widget.setUrl(onboardingWidget.getUrl());
191               result = widget.equals(fnWidgetDao.saveAndFlush(widget));
192               if (!result) {
193                      fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
194               }
195        }
196
197        private void validateOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) {
198               List<FnWidget> widgets = getWidgets(onboardingWidget);
199               boolean dublicatedUrl = false;
200               boolean dublicatedName = false;
201               for (FnWidget widget : widgets) {
202                      if (onboardingWidget.getId() != null && onboardingWidget.getId().equals(widget.getWidgetId())) {
203                             // widget should not be compared with itself
204                             continue;
205                      }
206                      if (!dublicatedUrl && widget.getUrl().equals(onboardingWidget.getUrl())) {
207                             dublicatedUrl = true;
208                             if (dublicatedName) {
209                                    break;
210                             }
211                      }
212                      if (!dublicatedName && widget.getName().equalsIgnoreCase(onboardingWidget.getName()) && widget
213                              .getAppId().equals(onboardingWidget.getAppId())) {
214                             dublicatedName = true;
215                             if (dublicatedUrl) {
216                                    break;
217                             }
218                      }
219               }
220               if (dublicatedUrl || dublicatedName) {
221                      if (dublicatedUrl) {
222                             fieldsValidator.addProblematicFieldName(urlField);
223                      }
224                      if (dublicatedName) {
225                             fieldsValidator.addProblematicFieldName(nameField);
226                      }
227                      fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_CONFLICT);
228                      fieldsValidator.setErrorCode(DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
229               }
230        }
231
232        private List<FnWidget> getWidgets(final OnboardingWidget onboardingWidget) {
233               return fnWidgetDao.getForUrlNameAndAppId(onboardingWidget.getUrl(), onboardingWidget.getName(), onboardingWidget.getAppId()).orElse(new ArrayList<>());
234        }
235
236        public FieldsValidator deleteOnboardingWidget(FnUser user, Long onboardingWidgetId) {
237               FieldsValidator fieldsValidator = new FieldsValidator();
238               synchronized (syncRests) {
239                      FnWidget widget = fnWidgetDao.getOne(onboardingWidgetId);
240                      if (widget != null && widget.getAppId() != null) { // widget exists
241                             if (!this.isUserAdminOfAppForWidget(adminRolesService.isSuperAdmin(user), user.getId(),
242                                     widget.getAppId())) {
243                                    fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_FORBIDDEN);
244                             } else {
245                                    fnWidgetDao.deleteById(onboardingWidgetId);
246                                    fieldsValidator.setHttpStatusCode(
247                                            (long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
248                             }
249                      }
250               }
251               return fieldsValidator;
252        }
253
254        public FnWidget saveOne(final FnWidget widget){
255               return fnWidgetDao.saveAndFlush(widget);
256        }
257 }