Reflected XSS vulnerability in saveNotification form fix.
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / controller / ExternalAppsRestfulController.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 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 package org.onap.portalapp.portal.controller;
41
42 import java.io.IOException;
43 import java.util.ArrayList;
44 import java.util.Calendar;
45 import java.util.HashMap;
46 import java.util.List;
47 import java.util.Map;
48
49 import javax.servlet.http.HttpServletRequest;
50 import javax.servlet.http.HttpServletResponse;
51
52 import org.onap.portalapp.controller.EPRestrictedRESTfulBaseController;
53 import org.onap.portalapp.portal.domain.EPApp;
54 import org.onap.portalapp.portal.domain.EPRole;
55 import org.onap.portalapp.portal.domain.EPUser;
56 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
57 import org.onap.portalapp.portal.service.AdminRolesService;
58 import org.onap.portalapp.portal.service.EPLoginService;
59 import org.onap.portalapp.portal.service.EPRoleService;
60 import org.onap.portalapp.portal.service.FunctionalMenuService;
61 import org.onap.portalapp.portal.service.UserNotificationService;
62 import org.onap.portalapp.portal.transport.EpNotificationItem;
63 import org.onap.portalapp.portal.transport.FavoritesFunctionalMenuItemJson;
64 import org.onap.portalapp.portal.transport.FieldsValidator;
65 import org.onap.portalapp.portal.transport.FunctionalMenuItem;
66 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
67 import org.onap.portalapp.portal.utils.EcompPortalUtils;
68 import org.onap.portalapp.portal.utils.PortalConstants;
69 import org.onap.portalapp.validation.DataValidator;
70 import org.onap.portalapp.validation.SecureString;
71 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
72 import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse;
73 import org.slf4j.MDC;
74 import org.springframework.beans.factory.annotation.Autowired;
75 import org.springframework.context.annotation.Configuration;
76 import org.springframework.context.annotation.EnableAspectJAutoProxy;
77 import org.springframework.http.HttpStatus;
78 import org.springframework.web.bind.annotation.ExceptionHandler;
79 import org.springframework.web.bind.annotation.RequestBody;
80 import org.springframework.web.bind.annotation.RequestMapping;
81 import org.springframework.web.bind.annotation.RequestMethod;
82 import org.springframework.web.bind.annotation.ResponseBody;
83 import org.springframework.web.bind.annotation.RestController;
84
85 import io.swagger.annotations.ApiOperation;
86
87 @RestController
88 @RequestMapping(PortalConstants.REST_AUX_API)
89 @Configuration
90 @EnableAspectJAutoProxy
91 @EPAuditLog
92 public class ExternalAppsRestfulController extends EPRestrictedRESTfulBaseController {
93
94         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppsRestfulController.class);
95         private final DataValidator DATA_VALIDATOR = new DataValidator();
96
97         @Autowired
98         private FunctionalMenuService functionalMenuService;
99
100         @Autowired
101         private EPLoginService epLoginService;
102
103         @Autowired
104         private AdminRolesService adminRolesService;
105
106         @Autowired
107         private UserNotificationService userNotificationService;
108
109         @Autowired
110         private EPRoleService epRoleService;
111
112         @ApiOperation(value = "Creates a Portal user notification for roles identified in the content from an external application.", response = PortalAPIResponse.class)
113         @RequestMapping(value = { "/publishNotification" }, method = RequestMethod.POST, produces = "application/json")
114         @ResponseBody
115         public PortalAPIResponse publishNotification(HttpServletRequest request,
116                         @RequestBody EpNotificationItem notificationItem) throws Exception {
117
118                 if(!DATA_VALIDATOR.isValid(notificationItem)){
119                         PortalAPIResponse response = new PortalAPIResponse(false, "failed");
120                         return response;
121                 }
122                 String appKey = request.getHeader("uebkey");
123                 EPApp app = findEpApp(appKey);
124                 List<Long> postRoleIds = new ArrayList<Long>();
125                 if (app != null) {
126         for (Long roleId : notificationItem.getRoleIds()) {
127             EPRole role = epRoleService.getRole(app.getId(), roleId);
128             if (role != null)
129                 postRoleIds.add(role.getId());
130                 }
131         }
132
133                 // --- recreate the user notification object with the POrtal Role Ids
134                 EpNotificationItem postItem = new EpNotificationItem();
135                 postItem.setRoleIds(postRoleIds);
136                 postItem.setIsForAllRoles("N");
137                 postItem.setIsForOnlineUsers("N");
138                 postItem.setActiveYn("Y");
139                 postItem.setPriority(notificationItem.getPriority());
140                 postItem.setMsgHeader(notificationItem.getMsgHeader());
141                 postItem.setMsgDescription(notificationItem.getMsgDescription());
142                 postItem.setStartTime(notificationItem.getStartTime());
143                 postItem.setEndTime(notificationItem.getEndTime());
144                 postItem.setCreatedDate(Calendar.getInstance().getTime());
145                 // default creator to 1 for now
146                 postItem.setCreatorId(PortalConstants.DEFAULT_NOTIFICATION_CREATOR);
147                 // ----
148
149                 try {
150                         userNotificationService.saveNotification(postItem);
151                 } catch (Exception e) {
152                         return new PortalAPIResponse(false, e.getMessage());
153                 }
154
155                 PortalAPIResponse response = new PortalAPIResponse(true, "success");
156                 return response;
157         }
158
159         private EPApp findEpApp(String uebKey) {
160                 List<?> list = null;
161                 Map<String, String> params = new HashMap<>();
162                 params.put("appKey", uebKey);
163                 try {
164                         list = this.getDataAccessService().executeNamedQuery("getMyAppDetailsByUebKey", params, null);
165                 } catch (Exception e) {
166                         logger.error(EELFLoggerDelegate.errorLogger, "getMyAppDetailsByUebKey failed", e);
167                 }
168                         
169                 return (list == null || list.isEmpty()) ? null : (EPApp) list.get(0);
170         }
171
172         @ApiOperation(value = "Gets favorite items within the functional menu for the current user.", response = FavoritesFunctionalMenuItemJson.class, responseContainer="List")
173         @RequestMapping(value = { "/getFavorites" }, method = RequestMethod.GET, produces = "application/json")
174         public List<FavoritesFunctionalMenuItemJson> getFavoritesForUser(HttpServletRequest request,
175                         HttpServletResponse response) throws Exception {
176                 String loginId = "";
177                 String userAgent = "";
178                 List<FavoritesFunctionalMenuItemJson> favorites = null;
179
180                 loginId = request.getHeader(EPCommonSystemProperties.MDC_LOGIN_ID);
181                 userAgent = MDC.get(EPCommonSystemProperties.PARTNER_NAME);
182
183                 EPUser epUser = epLoginService.findUserWithoutPwd(loginId);
184                 logger.info(EELFLoggerDelegate.errorLogger,
185                                 "getFavorites request was received from " + userAgent + " for the user " + loginId + ".");
186                 if (epUser == null || epUser.getId() == null) {
187                         logger.error(EELFLoggerDelegate.errorLogger,
188                                         "No User record found for the LoginId '" + loginId + "' in the database.");
189                         throw new Exception("Received null for Login-Id.");
190                 } else {
191                         favorites = functionalMenuService.getFavoriteItems(epUser.getId());
192                         FieldsValidator fieldsValidator = new FieldsValidator();
193                         response.setStatus(fieldsValidator.httpStatusCode.intValue());
194
195                         EcompPortalUtils.logAndSerializeObject(logger, "/getFavorites", "result = ", favorites);
196                 }
197
198                 return favorites;
199         }
200
201         @ApiOperation(value = "Gets functional menu items appropriate for the current user.", response = FunctionalMenuItem.class, responseContainer="List")
202         @RequestMapping(value = {
203                         "/functionalMenuItemsForUser" }, method = RequestMethod.GET, produces = "application/json")
204         public List<FunctionalMenuItem> getFunctionalMenuItemsForUser(HttpServletRequest request,
205                         HttpServletResponse response) throws Exception {
206                 String loginId = "";
207                 String userAgent = "";
208                 List<FunctionalMenuItem> fnMenuItems = null;
209
210                 loginId = request.getHeader("LoginId");
211                 userAgent = MDC.get(EPCommonSystemProperties.PARTNER_NAME);
212
213                 EPUser epUser = epLoginService.findUserWithoutPwd(loginId);
214                 logger.info(EELFLoggerDelegate.errorLogger, "getFunctionalMenuItemsForUser request was received from "
215                                 + userAgent + " for the user " + loginId + ".");
216                 if (epUser == null || epUser.getId() == null) {
217                         logger.error(EELFLoggerDelegate.errorLogger,
218                                         "No User record found for the LoginId '" + loginId + "' in the database.");
219                         throw new Exception("Received null for Login-Id.");
220                 } else if (adminRolesService.isSuperAdmin(epUser)) {
221                         logger.debug(EELFLoggerDelegate.debugLogger,
222                                         "FunctionalMenuHandler: SuperUser, about to call getFunctionalMenuItems()");
223                         fnMenuItems = functionalMenuService.getFunctionalMenuItems();
224                 } else {
225                         logger.debug(EELFLoggerDelegate.debugLogger,
226                                         "getMenuItemsForAuthUser: about to call getFunctionalMenuItemsForUser()");
227                         fnMenuItems = functionalMenuService.getFunctionalMenuItemsForUser(epUser.getOrgUserId());
228                 }
229
230                 FieldsValidator fieldsValidator = new FieldsValidator();
231                 response.setStatus(fieldsValidator.httpStatusCode.intValue());
232
233                 EcompPortalUtils.logAndSerializeObject(logger, "/functionalMenuItemsForUser", "result = ", fnMenuItems);
234
235                 return fnMenuItems;
236         }
237
238         @ExceptionHandler(Exception.class)
239         protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException {
240                 logger.warn(EELFLoggerDelegate.errorLogger, "Handling bad request", e);
241                 response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());
242         }
243 }