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