Domain model change
[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 org.onap.portal.dao.fn.FnWidgetDao;
48 import org.onap.portal.domain.db.fn.FnUser;
49 import org.onap.portal.domain.db.fn.FnUserRole;
50 import org.onap.portal.domain.db.fn.FnWidget;
51 import org.onap.portal.domain.dto.transport.FieldsValidator;
52 import org.onap.portal.domain.dto.transport.OnboardingWidget;
53 import org.onap.portal.service.fn.FnUserRoleService;
54 import org.onap.portal.utils.EPCommonSystemProperties;
55 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
56 import org.springframework.beans.factory.annotation.Autowired;
57 import org.springframework.context.annotation.EnableAspectJAutoProxy;
58 import org.springframework.security.access.prepost.PreAuthorize;
59 import org.springframework.stereotype.Service;
60 import org.springframework.transaction.annotation.Transactional;
61
62 @Service
63 @EnableAspectJAutoProxy
64 @Transactional
65 public class WidgetService {
66
67        private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetService.class);
68        private final Long ACCOUNT_ADMIN_ROLE_ID = 999L;
69
70        private static final String baseSqlToken =
71                " new org.onap.portal.domain.dto.transport.OnboardingWidget("
72                        + "widget.WIDGET_ID,widget.WDG_NAME,widget.APP_ID,"
73                        + "app.APP_NAME,widget.WDG_WIDTH,widget.WDG_HEIGHT,"
74                        + "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";
75
76        private static final String urlField = "url";
77        private static final Long DUBLICATED_FIELD_VALUE_ECOMP_ERROR = new Long(
78                EPCommonSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
79        private static final String nameField = "name";
80
81        private final AdminRolesService adminRolesService;
82        private final EntityManager entityManager;
83        private final FnWidgetDao fnWidgetDao;
84        private final FnUserRoleService fnUserRoleService;
85
86        @Autowired
87        public WidgetService(final AdminRolesService adminRolesService, final EntityManager entityManager,
88                final FnWidgetDao fnWidgetDao, FnUserRoleService fnUserRoleService) {
89               this.adminRolesService = adminRolesService;
90               this.entityManager = entityManager;
91               this.fnWidgetDao = fnWidgetDao;
92               this.fnUserRoleService = fnUserRoleService;
93        }
94
95        private static final Object syncRests = new Object();
96
97        public List<OnboardingWidget> getOnboardingWidgets(FnUser user, boolean managed) {
98               if (adminRolesService.isSuperAdmin(user.getOrgUserId())) {
99                      return entityManager.createQuery(sqlWidgetsForAllApps(), OnboardingWidget.class).getResultList();
100               } else if (managed) {
101                      if (adminRolesService.isAccountAdmin(user)) {
102                             return entityManager
103                                     .createQuery(sqlWidgetsForAllAppsWhereUserIsAdmin(), OnboardingWidget.class)
104                                     .setParameter("USERID", user.getId()).getResultList();
105                      }
106               } else if (adminRolesService.isAccountAdmin(user) || adminRolesService.isUser(user)) {
107                      return entityManager
108                              .createQuery(sqlWidgetsForAllAppsWhereUserHasAnyRole(), OnboardingWidget.class)
109                              .setParameter("USERID", user.getId()).getResultList();
110               }
111               return new ArrayList<>();
112        }
113
114        private String sqlWidgetsForAllApps() {
115               return "SELECT" + baseSqlToken;
116        }
117
118        private String sqlWidgetsForAllAppsWhereUserIsAdmin() {
119               return "SELECT" + baseSqlToken
120                       + " 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 = "
121                       + ACCOUNT_ADMIN_ROLE_ID;
122        }
123
124        private String sqlWidgetsForAllAppsWhereUserHasAnyRole() {
125               return "SELECT DISTINCT" + baseSqlToken
126                       + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = "
127                       + ":USERID";
128        }
129
130        @PreAuthorize("hasRole('System_Administrator')")
131        public FieldsValidator setOnboardingWidget(final Long userId, final OnboardingWidget onboardingWidget) {
132               return this.updateOrSaveWidget(true, userId, onboardingWidget);
133        }
134
135        private FieldsValidator updateOrSaveWidget(boolean superAdmin, Long userId, OnboardingWidget onboardingWidget) {
136               FieldsValidator fieldsValidator = new FieldsValidator();
137               if (!this.isUserAdminOfAppForWidget(superAdmin, userId, onboardingWidget.getAppId())) {
138                      fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_FORBIDDEN);
139                      return fieldsValidator;
140               }
141               synchronized (syncRests) {
142                      if (onboardingWidget.getId() == null) {
143                             this.validateOnboardingWidget(onboardingWidget, fieldsValidator);
144                      } else {
145                             FnWidget widget = fnWidgetDao.getOne(onboardingWidget.getId());
146                             if (widget == null || widget.getAppId() == null) {
147                                    fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_NOT_FOUND);
148                                    return fieldsValidator;
149                             }
150                             this.validateOnboardingWidget(onboardingWidget, fieldsValidator);
151                      }
152                      if (fieldsValidator.getHttpStatusCode() == HttpServletResponse.SC_OK) {
153                             this.applyOnboardingWidget(onboardingWidget, fieldsValidator);
154                      }
155               }
156               return fieldsValidator;
157        }
158
159        private boolean isUserAdminOfAppForWidget(boolean superAdmin, Long userId, Long appId) {
160               if (!superAdmin) {
161                      List<FnUserRole> userRoles = getAdminUserRoles(userId, appId);
162                      return (userRoles.size() > 0);
163               }
164               return true;
165        }
166
167        private List<FnUserRole> getAdminUserRoles(Long userId, Long appId) {
168               return fnUserRoleService.getAdminUserRoles(userId, ACCOUNT_ADMIN_ROLE_ID, appId);
169        }
170
171        private void applyOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) {
172               boolean result;
173               FnWidget widget;
174               if (onboardingWidget.getId() == null) {
175                      widget = new FnWidget();
176               } else {
177                      widget = fnWidgetDao.getOne(onboardingWidget.getId());
178               }
179               widget.setAppId(onboardingWidget.getAppId());
180               widget.setName(onboardingWidget.getName());
181               widget.setWidth(onboardingWidget.getWidth());
182               widget.setHeight(onboardingWidget.getHeight());
183               widget.setUrl(onboardingWidget.getUrl());
184               result = widget.equals(fnWidgetDao.saveAndFlush(widget));
185               if (!result) {
186                      fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
187               }
188        }
189
190        private void validateOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) {
191               List<FnWidget> widgets = getWidgets(onboardingWidget);
192               boolean dublicatedUrl = false;
193               boolean dublicatedName = false;
194               for (FnWidget widget : widgets) {
195                      if (onboardingWidget.getId() != null && onboardingWidget.getId().equals(widget.getWidgetId())) {
196                             // widget should not be compared with itself
197                             continue;
198                      }
199                      if (!dublicatedUrl && widget.getUrl().equals(onboardingWidget.getUrl())) {
200                             dublicatedUrl = true;
201                             if (dublicatedName) {
202                                    break;
203                             }
204                      }
205                      if (!dublicatedName && widget.getName().equalsIgnoreCase(onboardingWidget.getName()) && widget
206                              .getAppId().equals(onboardingWidget.getAppId())) {
207                             dublicatedName = true;
208                             if (dublicatedUrl) {
209                                    break;
210                             }
211                      }
212               }
213               if (dublicatedUrl || dublicatedName) {
214                      if (dublicatedUrl) {
215                             fieldsValidator.addProblematicFieldName(urlField);
216                      }
217                      if (dublicatedName) {
218                             fieldsValidator.addProblematicFieldName(nameField);
219                      }
220                      fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_CONFLICT);
221                      fieldsValidator.setErrorCode(DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
222               }
223        }
224
225        private List<FnWidget> getWidgets(final OnboardingWidget onboardingWidget) {
226               return fnWidgetDao.getForUrlNameAndAppId(onboardingWidget.getUrl(), onboardingWidget.getName(), onboardingWidget.getAppId()).orElse(new ArrayList<>());
227        }
228
229        public FieldsValidator deleteOnboardingWidget(FnUser user, Long onboardingWidgetId) {
230               FieldsValidator fieldsValidator = new FieldsValidator();
231               synchronized (syncRests) {
232                      FnWidget widget = fnWidgetDao.getOne(onboardingWidgetId);
233                      if (widget != null && widget.getAppId() != null) { // widget exists
234                             if (!this.isUserAdminOfAppForWidget(adminRolesService.isSuperAdmin(user.getOrgUserId()), user.getId(),
235                                     widget.getAppId())) {
236                                    fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_FORBIDDEN);
237                             } else {
238                                    fnWidgetDao.deleteById(onboardingWidgetId);
239                                    fieldsValidator.setHttpStatusCode(
240                                            (long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
241                             }
242                      }
243               }
244               return fieldsValidator;
245        }
246
247        public FnWidget saveOne(final FnWidget widget){
248               return fnWidgetDao.saveAndFlush(widget);
249        }
250 }