XSS Vulnerability fix in DashboardController
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / controller / DashboardController.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.text.ParseException;
41 import java.text.SimpleDateFormat;
42 import java.util.ArrayList;
43 import java.util.Date;
44 import java.util.HashMap;
45 import java.util.HashSet;
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.EPRestrictedBaseController;
53 import org.onap.portalapp.portal.domain.EPUser;
54 import org.onap.portalapp.portal.domain.EcompAuditLog;
55 import org.onap.portalapp.portal.ecomp.model.PortalRestResponse;
56 import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
57 import org.onap.portalapp.portal.ecomp.model.SearchResultItem;
58 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
59 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
60 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
61 import org.onap.portalapp.portal.service.AdminRolesService;
62 import org.onap.portalapp.portal.service.DashboardSearchService;
63 import org.onap.portalapp.portal.transport.CommonWidget;
64 import org.onap.portalapp.portal.transport.CommonWidgetMeta;
65 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
66 import org.onap.portalapp.portal.utils.EcompPortalUtils;
67 import org.onap.portalapp.portal.utils.PortalConstants;
68 import org.onap.portalapp.util.EPUserUtils;
69 import org.onap.portalapp.validation.DataValidator;
70 import org.onap.portalapp.validation.SecureString;
71 import org.onap.portalsdk.core.domain.AuditLog;
72 import org.onap.portalsdk.core.domain.support.CollaborateList;
73 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
74 import org.onap.portalsdk.core.service.AuditService;
75 import org.onap.portalsdk.core.util.SystemProperties;
76 import org.slf4j.MDC;
77 import org.springframework.beans.factory.annotation.Autowired;
78 import org.springframework.context.annotation.Configuration;
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.RequestParam;
83 import org.springframework.web.bind.annotation.RestController;
84
85 /**
86  * Controller supplies data to Angular services on the dashboard page.
87  */
88 @Configuration
89 @RestController
90 @RequestMapping("/portalApi/dashboard")
91 public class DashboardController extends EPRestrictedBaseController {
92         private static final DataValidator DATA_VALIDATOR = new DataValidator();
93         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
94
95         private DashboardSearchService searchService;
96         private AuditService auditService;
97         private AdminRolesService adminRolesService;
98
99         @Autowired
100         public DashboardController(DashboardSearchService searchService,
101                 AuditService auditService, AdminRolesService adminRolesService) {
102                 this.searchService = searchService;
103                 this.auditService = auditService;
104                 this.adminRolesService = adminRolesService;
105         }
106
107         public enum WidgetCategory {
108                 EVENTS, NEWS, IMPORTANTRESOURCES
109         }
110
111         /**
112          * Validates the resource type parameter.
113          * 
114          * @param resourceType
115          * @return True if known in the enum WidgetCategory, else false.
116          */
117         private boolean isValidResourceType(String resourceType) {
118                 if (resourceType == null)
119                         return false;
120                 for (WidgetCategory wc : WidgetCategory.values())
121                         if (wc.name().equals(resourceType))
122                                 return true;
123                 return false;
124         }
125
126         /**
127          * Gets all widgets of the specified resource type. 
128          * In iteration 41 (when widget will utilized service onboarding), this method can be removed, instead we will use CommonWidgetController.java (basic auth based)
129          * 
130          * @param request
131          * @param resourceType
132          *            Request parameter.
133          * @return Rest response wrapped around a CommonWidgetMeta object.
134          */
135         @RequestMapping(value = "/widgetData", method = RequestMethod.GET, produces = "application/json")
136         public PortalRestResponse<CommonWidgetMeta> getWidgetData(HttpServletRequest request,
137                         @RequestParam String resourceType) {
138                 if (!isValidResourceType(resourceType)) {
139                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
140                                 "Unexpected resource type " + resourceType, null);
141                 }else if (!DATA_VALIDATOR.isValid(new SecureString(resourceType))){
142                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
143                                 "Unsafe resource type " + resourceType, null);
144                 }
145                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
146                         searchService.getWidgetData(resourceType));
147         }
148         
149         
150         /**
151          * Saves a batch of events, news or resources.
152          * 
153          * @param commonWidgetMeta
154          *            read from POST body.
155          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
156          */
157         @RequestMapping(value = "/widgetDataBulk", method = RequestMethod.POST, produces = "application/json")
158         public PortalRestResponse<String> saveWidgetDataBulk(@RequestBody CommonWidgetMeta commonWidgetMeta) {
159                 logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetDataBulk: argument is {}", commonWidgetMeta);
160                 if (!DATA_VALIDATOR.isValid(commonWidgetMeta)){
161                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
162                                 "Unsafe resource type " + commonWidgetMeta, "ERROR");
163                 }else if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals("")) {
164                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR",
165                                 "Category cannot be null or empty");
166                 }else if (!isValidResourceType(commonWidgetMeta.getCategory())) {
167                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
168                                 "Unexpected resource type " + commonWidgetMeta.getCategory(), null);
169                 }
170                 for (CommonWidget cw : commonWidgetMeta.getItems()) {
171                         String err = validateCommonWidget(cw);
172                         if (err != null)
173                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
174                 }
175                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
176                         searchService.saveWidgetDataBulk(commonWidgetMeta));
177         }
178
179         /**
180          * Saves one: event, news or resource
181          * 
182          * @param commonWidget
183          *            read from POST body
184          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
185          */
186         @RequestMapping(value = "/widgetData", method = RequestMethod.POST, produces = "application/json")
187         public PortalRestResponse<String> saveWidgetData(@RequestBody CommonWidget commonWidget, HttpServletRequest request, HttpServletResponse response) {
188                 logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget);
189                 EPUser user = EPUserUtils.getUserSession(request);
190                 if (adminRolesService.isSuperAdmin(user)) {
191                         if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().isEmpty()) {
192                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR",
193                                         "Category cannot be null or empty");
194                         }else if (!DATA_VALIDATOR.isValid(commonWidget)){
195                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
196                                         "Unsafe resource type " + commonWidget, "ERROR");
197                         }
198                         String err = validateCommonWidget(commonWidget);
199                         if (err != null)
200                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null);
201                         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
202                                 searchService.saveWidgetData(commonWidget));
203                 } else {
204                         EcompPortalUtils.setBadPermissions(user, response, "saveWidgetData");
205                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed", null);
206                 }
207         }
208
209         /**
210          * Used by the validate function
211          */
212         private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
213
214         /**
215          * Validates the content of a common widget.
216          * 
217          * @param cw
218          * @return null on success; an error message if validation fails.
219          * @throws Exception
220          */
221         private String validateCommonWidget(CommonWidget cw) {
222                 if (!isValidResourceType(cw.getCategory()))
223                         return "Invalid category: " + cw.getCategory();
224                 if (cw.getTitle() == null || cw.getTitle().trim().length() == 0)
225                         return "Title is missing";
226                 if (cw.getHref() == null || cw.getHref().trim().length() == 0)
227                         return "HREF is missing";
228                 if (!cw.getHref().toLowerCase().startsWith("http"))
229                         return "HREF does not start with http";
230                 if (cw.getSortOrder() == null)
231                         return "Sort order is null";
232                 if (cw.getEventDate() == null || cw.getEventDate().trim().length() == 0)
233                         return "Date is missing";
234                 try {
235                         yearMonthDayFormat.setLenient(false);
236                         Date date = yearMonthDayFormat.parse(cw.getEventDate());
237                         if (date == null)
238                                 return "Failed to parse date " + cw.getEventDate();
239                 } catch (ParseException ex) {
240                         return "Invalid date format " +ex.toString();
241                 }
242                 return null;
243         }
244
245         /**
246          * Deletes one: event, news or resource
247          * 
248          * @param commonWidget
249          *            read from POST body
250          * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
251          */
252         @RequestMapping(value = "/deleteData", method = RequestMethod.POST, produces = "application/json")
253         public PortalRestResponse<String> deleteWidgetData(@RequestBody CommonWidget commonWidget) {
254                 logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget);
255                 if (!DATA_VALIDATOR.isValid(commonWidget)){
256                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
257                                 "Unsafe resource type " + commonWidget, "ERROR");
258                 }
259                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
260                         searchService.deleteWidgetData(commonWidget));
261         }
262
263         /**
264          * Searches all portal for the input string.
265          * 
266          * @param request
267          * @param searchString
268          * @return Rest response wrapped around a Map of String to List of Search
269          *         Result Item.
270          */
271         @EPAuditLog
272         @RequestMapping(value = "/search", method = RequestMethod.GET, produces = "application/json")
273         public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
274                         @RequestParam String searchString) {
275                 if (!DATA_VALIDATOR.isValid(new SecureString(searchString))){
276                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is not safe",
277                                 new HashMap<>());
278                 }
279                 if (searchString != null)
280                         searchString = searchString.trim();
281                 EPUser user = EPUserUtils.getUserSession(request);
282                 try {
283                         if (user == null) {
284                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
285                                                 "searchPortal: User object is null? - check logs",
286                                         new HashMap<>());
287                         } else if (searchString == null || searchString.length() == 0) {
288                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null",
289                                         new HashMap<>());
290                         } else {
291                                 logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
292                                                 user.getLoginId(), searchString);
293                                 Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
294                                                 searchString);
295                                 /*Audit log the search*/
296                                 AuditLog auditLog = new AuditLog();
297                                 auditLog.setUserId(user.getId());
298                                 auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_SEARCH);
299                                 auditLog.setComments(EcompPortalUtils.truncateString(searchString, PortalConstants.AUDIT_LOG_COMMENT_SIZE));
300                                 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());  
301                                 MDC.put(EPCommonSystemProperties.PARTNER_NAME, EPCommonSystemProperties.ECOMP_PORTAL_FE);
302                                 MDC.put(com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE);
303                                 auditService.logActivity(auditLog, null);
304                                 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,EPEELFLoggerAdvice.getCurrentDateTimeUTC());
305                                 
306                                 MDC.put(EPCommonSystemProperties.STATUS_CODE, "COMPLETE");
307                                 EcompPortalUtils.calculateDateTimeDifferenceForLog(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
308                                 logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("DashboardController.PortalRestResponse", 
309                                                 EcompAuditLog.CD_ACTIVITY_SEARCH, user.getOrgUserId(), null, searchString));    
310                                 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
311                                 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
312                                 MDC.remove(SystemProperties.MDC_TIMER);
313                                 MDC.remove(EPCommonSystemProperties.STATUS_CODE);
314                                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
315                         }
316                 } catch (Exception e) {
317                         logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e);
318                         MDC.put(EPCommonSystemProperties.STATUS_CODE, "ERROR");
319                         MDC.remove(EPCommonSystemProperties.STATUS_CODE);
320                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
321                                 new HashMap<>());
322                 }
323         }
324
325         /**
326          * Gets all active users.
327          * 
328          * TODO: should only the superuser be allowed to use this API?
329          * 
330          * @param request
331          * @return Rest response wrapped around a list of String
332          */
333         @RequestMapping(value = "/activeUsers", method = RequestMethod.GET, produces = "application/json")
334         public List<String> getActiveUsers(HttpServletRequest request) {
335                 List<String> activeUsers;
336                 List<String> onlineUsers = new ArrayList<>();
337                 try {
338                         EPUser user = EPUserUtils.getUserSession(request);
339                         String userId = user.getOrgUserId();
340
341                         activeUsers = searchService.getRelatedUsers(userId);
342                         HashSet<String> usersSet = (HashSet<String>) CollaborateList.getInstance().getAllUserName();
343                         for (String users : activeUsers) {
344                                 if (usersSet.contains(users)) {
345                                         onlineUsers.add(users);
346                                 }
347                         }
348
349                 } catch (Exception e) {
350                         logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
351                 }
352                 return onlineUsers;
353         }
354         
355         /**
356          * Gets the refresh interval and duration of a cycle of continuous refreshing for the online users side panel, both in milliseconds.
357          * 
358          * @param request
359          * @return Rest response wrapped around a number that is the number of milliseconds.
360          */
361         @RequestMapping(value = "/onlineUserUpdateRate", method = RequestMethod.GET, produces = "application/json")
362         public PortalRestResponse<Map<String, String>> getOnlineUserUpdateRate(HttpServletRequest request) {
363                 try {
364                         String updateRate = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_RATE);     
365                         String updateDuration = SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_DURATION);                             
366                         Integer rateInMiliSec = Integer.valueOf(updateRate)*1000;
367                         Integer durationInMiliSec = Integer.valueOf(updateDuration)*1000;
368                         Map<String, String> results = new HashMap<>();
369                         results.put("onlineUserUpdateRate", String.valueOf(rateInMiliSec));
370                         results.put("onlineUserUpdateDuration", String.valueOf(durationInMiliSec));                     
371                         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
372                 } catch (Exception e) {
373                         logger.error(EELFLoggerDelegate.errorLogger, "getOnlineUserUpdateRate failed", e);
374                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
375                 }               
376         }
377
378         /**
379          * Gets the window width threshold for collapsing right menu from system.properties.
380          * 
381          * @param request
382          * @return Rest response wrapped around a number that is the window width threshold to collapse right menu.
383          */
384         @RequestMapping(value = "/windowWidthThresholdRightMenu", method = RequestMethod.GET, produces = "application/json")
385         public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForRightMenu(HttpServletRequest request) {
386                 try {
387                         String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_RIGHT_MENU);    
388                         Integer windowWidth = Integer.valueOf(windowWidthString);
389                         Map<String, String> results = new HashMap<>();
390                         results.put("windowWidth", String.valueOf(windowWidth));
391                         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
392                 } catch (Exception e) {
393                         logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForRightMenu failed", e);
394                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
395                 }               
396         }
397
398
399         /**
400          * Gets the window width threshold for collapsing left menu from system.properties.
401          * 
402          * @param request
403          * @return Rest response wrapped around a number that is the window width threshold to collapse the left menu.
404          */
405         @RequestMapping(value = "/windowWidthThresholdLeftMenu", method = RequestMethod.GET, produces = "application/json")
406         public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForLeftMenu(HttpServletRequest request) {
407                 try {
408                         String windowWidthString = SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_LEFT_MENU);     
409                         Integer windowWidth = Integer.valueOf(windowWidthString);
410                         Map<String, String> results = new HashMap<>();
411                         results.put("windowWidth", String.valueOf(windowWidth));
412                         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
413                 } catch (Exception e) {
414                         logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForLeftMenu failed", e);
415                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
416                 }               
417         }
418         
419         /**
420          * Gets only those users that are 'related' to the currently logged-in user.
421          * 
422          * @param request
423          * @return Rest response wrapped around a List of String
424          */
425         @RequestMapping(value = "/relatedUsers", method = RequestMethod.GET, produces = "application/json")
426         public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
427                 EPUser user = EPUserUtils.getUserSession(request);
428                 try {
429                         if (user == null) {
430                                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
431                                                 new ArrayList<>());
432                         } else {
433                                 logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
434                                 return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
435                                                 searchService.getRelatedUsers(user.getLoginId()));
436                         }
437                 } catch (Exception e) {
438                         logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
439                         return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
440                                         new ArrayList<>());
441                 }
442         }
443
444 }