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