Fix sql injection vulnerability
[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  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38 package org.onap.portalapp.portal.controller;
39
40 import java.io.IOException;
41 import java.util.ArrayList;
42 import java.util.Calendar;
43 import java.util.HashMap;
44 import java.util.List;
45 import java.util.Map;
46
47 import javax.servlet.http.HttpServletRequest;
48 import javax.servlet.http.HttpServletResponse;
49
50 import org.onap.portalapp.controller.EPRestrictedRESTfulBaseController;
51 import org.onap.portalapp.portal.domain.EPApp;
52 import org.onap.portalapp.portal.domain.EPRole;
53 import org.onap.portalapp.portal.domain.EPUser;
54 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
55 import org.onap.portalapp.portal.service.AdminRolesService;
56 import org.onap.portalapp.portal.service.EPLoginService;
57 import org.onap.portalapp.portal.service.EPRoleService;
58 import org.onap.portalapp.portal.service.FunctionalMenuService;
59 import org.onap.portalapp.portal.service.UserNotificationService;
60 import org.onap.portalapp.portal.transport.EpNotificationItem;
61 import org.onap.portalapp.portal.transport.FavoritesFunctionalMenuItemJson;
62 import org.onap.portalapp.portal.transport.FieldsValidator;
63 import org.onap.portalapp.portal.transport.FunctionalMenuItem;
64 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
65 import org.onap.portalapp.portal.utils.EcompPortalUtils;
66 import org.onap.portalapp.portal.utils.PortalConstants;
67 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
68 import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse;
69 import org.slf4j.MDC;
70 import org.springframework.beans.factory.annotation.Autowired;
71 import org.springframework.context.annotation.Configuration;
72 import org.springframework.context.annotation.EnableAspectJAutoProxy;
73 import org.springframework.http.HttpStatus;
74 import org.springframework.web.bind.annotation.ExceptionHandler;
75 import org.springframework.web.bind.annotation.RequestBody;
76 import org.springframework.web.bind.annotation.RequestMapping;
77 import org.springframework.web.bind.annotation.RequestMethod;
78 import org.springframework.web.bind.annotation.ResponseBody;
79 import org.springframework.web.bind.annotation.RestController;
80
81 import io.swagger.annotations.ApiOperation;
82
83 @RestController
84 @RequestMapping(PortalConstants.REST_AUX_API)
85 @Configuration
86 @EnableAspectJAutoProxy
87 @EPAuditLog
88 public class ExternalAppsRestfulController extends EPRestrictedRESTfulBaseController {
89
90         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppsRestfulController.class);
91
92         @Autowired
93         private FunctionalMenuService functionalMenuService;
94
95         @Autowired
96         private EPLoginService epLoginService;
97
98         @Autowired
99         private AdminRolesService adminRolesService;
100
101         @Autowired
102         private UserNotificationService userNotificationService;
103
104         @Autowired
105         private EPRoleService epRoleService;
106
107         @ApiOperation(value = "Creates a Portal user notification for roles identified in the content from an external application.", response = PortalAPIResponse.class)
108         @RequestMapping(value = { "/publishNotification" }, method = RequestMethod.POST, produces = "application/json")
109         @ResponseBody
110         public PortalAPIResponse publishNotification(HttpServletRequest request,
111                         @RequestBody EpNotificationItem notificationItem) throws Exception {
112                 String appKey = request.getHeader("uebkey");
113                 EPApp app = findEpApp(appKey);
114                 List<Long> postRoleIds = new ArrayList<Long>();
115                 for (Long roleId : notificationItem.getRoleIds()) {
116                         EPRole role = epRoleService.getRole(app.getId(), roleId);
117                         if (role != null)
118                                 postRoleIds.add(role.getId());
119                 }
120
121                 // --- recreate the user notification object with the POrtal Role Ids
122                 EpNotificationItem postItem = new EpNotificationItem();
123                 postItem.setRoleIds(postRoleIds);
124                 postItem.setIsForAllRoles("N");
125                 postItem.setIsForOnlineUsers("N");
126                 postItem.setActiveYn("Y");
127                 postItem.setPriority(notificationItem.getPriority());
128                 postItem.setMsgHeader(notificationItem.getMsgHeader());
129                 postItem.setMsgDescription(notificationItem.getMsgDescription());
130                 postItem.setStartTime(notificationItem.getStartTime());
131                 postItem.setEndTime(notificationItem.getEndTime());
132                 postItem.setCreatedDate(Calendar.getInstance().getTime());
133                 // default creator to 1 for now
134                 postItem.setCreatorId(PortalConstants.DEFAULT_NOTIFICATION_CREATOR);
135                 // ----
136
137                 try {
138                         userNotificationService.saveNotification(postItem);
139                 } catch (Exception e) {
140                         return new PortalAPIResponse(false, e.getMessage());
141                 }
142
143                 PortalAPIResponse response = new PortalAPIResponse(true, "success");
144                 return response;
145         }
146
147         private EPApp findEpApp(String uebKey) {
148                 List<?> list = null;
149                 Map<String, String> params = new HashMap<>();
150                 params.put("appKey", uebKey);
151                 try {
152                         list = this.getDataAccessService().executeNamedQuery("getMyAppDetailsByUebKey", params, null);
153                 } catch (Exception e) {
154                         logger.error(EELFLoggerDelegate.errorLogger, "getMyAppDetailsByUebKey failed", e);                      
155                 }
156                         
157                 return (list == null || list.size() == 0) ? null : (EPApp) list.get(0);
158         }
159
160         @ApiOperation(value = "Gets favorite items within the functional menu for the current user.", response = FavoritesFunctionalMenuItemJson.class, responseContainer="List")
161         @RequestMapping(value = { "/getFavorites" }, method = RequestMethod.GET, produces = "application/json")
162         public List<FavoritesFunctionalMenuItemJson> getFavoritesForUser(HttpServletRequest request,
163                         HttpServletResponse response) throws Exception {
164                 String loginId = "";
165                 String userAgent = "";
166                 List<FavoritesFunctionalMenuItemJson> favorites = null;
167
168                 loginId = request.getHeader(EPCommonSystemProperties.MDC_LOGIN_ID);
169                 userAgent = MDC.get(EPCommonSystemProperties.PARTNER_NAME);
170
171                 EPUser epUser = epLoginService.findUserWithoutPwd(loginId);
172                 logger.info(EELFLoggerDelegate.errorLogger,
173                                 "getFavorites request was received from " + userAgent + " for the user " + loginId + ".");
174                 if (epUser == null || epUser.getId() == null) {
175                         logger.error(EELFLoggerDelegate.errorLogger,
176                                         "No User record found for the LoginId '" + loginId + "' in the database.");
177                         throw new Exception("Received null for Login-Id.");
178                 } else {
179                         favorites = functionalMenuService.getFavoriteItems(epUser.getId());
180                         FieldsValidator fieldsValidator = new FieldsValidator();
181                         response.setStatus(fieldsValidator.httpStatusCode.intValue());
182
183                         EcompPortalUtils.logAndSerializeObject(logger, "/getFavorites", "result = ", favorites);
184                 }
185
186                 return favorites;
187         }
188
189         @ApiOperation(value = "Gets functional menu items appropriate for the current user.", response = FunctionalMenuItem.class, responseContainer="List")
190         @RequestMapping(value = {
191                         "/functionalMenuItemsForUser" }, method = RequestMethod.GET, produces = "application/json")
192         public List<FunctionalMenuItem> getFunctionalMenuItemsForUser(HttpServletRequest request,
193                         HttpServletResponse response) throws Exception {
194                 String loginId = "";
195                 String userAgent = "";
196                 List<FunctionalMenuItem> fnMenuItems = null;
197
198                 loginId = request.getHeader("LoginId");
199                 userAgent = MDC.get(EPCommonSystemProperties.PARTNER_NAME);
200
201                 EPUser epUser = epLoginService.findUserWithoutPwd(loginId);
202                 logger.info(EELFLoggerDelegate.errorLogger, "getFunctionalMenuItemsForUser request was received from "
203                                 + userAgent + " for the user " + loginId + ".");
204                 if (epUser == null || epUser.getId() == null) {
205                         logger.error(EELFLoggerDelegate.errorLogger,
206                                         "No User record found for the LoginId '" + loginId + "' in the database.");
207                         throw new Exception("Received null for Login-Id.");
208                 } else if (adminRolesService.isSuperAdmin(epUser)) {
209                         logger.debug(EELFLoggerDelegate.debugLogger,
210                                         "FunctionalMenuHandler: SuperUser, about to call getFunctionalMenuItems()");
211                         fnMenuItems = functionalMenuService.getFunctionalMenuItems();
212                 } else {
213                         logger.debug(EELFLoggerDelegate.debugLogger,
214                                         "getMenuItemsForAuthUser: about to call getFunctionalMenuItemsForUser()");
215                         fnMenuItems = functionalMenuService.getFunctionalMenuItemsForUser(epUser.getOrgUserId());
216                 }
217
218                 FieldsValidator fieldsValidator = new FieldsValidator();
219                 response.setStatus(fieldsValidator.httpStatusCode.intValue());
220
221                 EcompPortalUtils.logAndSerializeObject(logger, "/functionalMenuItemsForUser", "result = ", fnMenuItems);
222
223                 return fnMenuItems;
224         }
225
226         @ExceptionHandler(Exception.class)
227         protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException {
228                 logger.warn(EELFLoggerDelegate.errorLogger, "Handling bad request", e);
229                 response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());
230         }
231 }