Merge "removed code smells"
[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.PutMapping;
90 import org.springframework.web.bind.annotation.DeleteMapping;
91 import org.springframework.web.bind.annotation.RequestMethod;
92 import org.springframework.web.bind.annotation.ResponseBody;
93 import org.springframework.web.bind.annotation.RestController;
94
95 import io.swagger.annotations.ApiOperation;
96
97 @RestController
98 @RequestMapping(PortalConstants.REST_AUX_API)
99 @Configuration
100 @EnableAspectJAutoProxy
101 @EPAuditLog
102 public class ExternalAppsRestfulController extends EPRestrictedRESTfulBaseController {
103
104         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppsRestfulController.class);
105         private final DataValidator DATA_VALIDATOR = new DataValidator();
106
107         @Autowired
108         private FunctionalMenuService functionalMenuService;
109
110         @Autowired
111         private EPLoginService epLoginService;
112
113         @Autowired
114         private AdminRolesService adminRolesService;
115
116         @Autowired
117         private UserNotificationService userNotificationService;
118
119         @Autowired
120         private EPRoleService epRoleService;
121
122         @ApiOperation(value = "Creates a Portal user notification for roles identified in the content from an external application.", response = PortalAPIResponse.class)
123         @PostMapping(value = { "/publishNotification" }, produces = "application/json")
124         @ResponseBody
125         public PortalAPIResponse publishNotification(HttpServletRequest request,
126                         @RequestBody EpNotificationItem notificationItem) throws Exception {
127
128                 if(!DATA_VALIDATOR.isValid(notificationItem)){
129                         PortalAPIResponse response = new PortalAPIResponse(false, "failed");
130                         return response;
131                 }
132                 String appKey = request.getHeader("uebkey");
133                 EPApp app = findEpApp(appKey);
134                 List<Long> postRoleIds = new ArrayList<Long>();
135                 if (app != null) {
136         for (Long roleId : notificationItem.getRoleIds()) {
137             EPRole role = epRoleService.getRole(app.getId(), roleId);
138             if (role != null)
139                 postRoleIds.add(role.getId());
140                 }
141         }
142
143                 // --- recreate the user notification object with the POrtal Role Ids
144                 EpNotificationItem postItem = new EpNotificationItem();
145                 postItem.setRoleIds(postRoleIds);
146                 postItem.setIsForAllRoles("N");
147                 postItem.setIsForOnlineUsers("N");
148                 postItem.setActiveYn("Y");
149                 postItem.setPriority(notificationItem.getPriority());
150                 postItem.setMsgHeader(notificationItem.getMsgHeader());
151                 postItem.setMsgDescription(notificationItem.getMsgDescription());
152                 postItem.setStartTime(notificationItem.getStartTime());
153                 postItem.setEndTime(notificationItem.getEndTime());
154                 postItem.setCreatedDate(Calendar.getInstance().getTime());
155                 // default creator to 1 for now
156                 postItem.setCreatorId(PortalConstants.DEFAULT_NOTIFICATION_CREATOR);
157                 // ----
158
159                 try {
160                         userNotificationService.saveNotification(postItem);
161                 } catch (Exception e) {
162                         return new PortalAPIResponse(false, e.getMessage());
163                 }
164
165                 PortalAPIResponse response = new PortalAPIResponse(true, "success");
166                 return response;
167         }
168
169         private EPApp findEpApp(String uebKey) {
170                 List<?> list = null;
171                 Map<String, String> params = new HashMap<>();
172                 params.put("appKey", uebKey);
173                 try {
174                         list = this.getDataAccessService().executeNamedQuery("getMyAppDetailsByUebKey", params, null);
175                 } catch (Exception e) {
176                         logger.error(EELFLoggerDelegate.errorLogger, "getMyAppDetailsByUebKey failed", e);
177                 }
178                         
179                 return (list == null || list.isEmpty()) ? null : (EPApp) list.get(0);
180         }
181
182         @ApiOperation(value = "Gets favorite items within the functional menu for the current user.", response = FavoritesFunctionalMenuItemJson.class, responseContainer="List")
183         @GetMapping(value = { "/getFavorites" }, produces = "application/json")
184         public List<FavoritesFunctionalMenuItemJson> getFavoritesForUser(HttpServletRequest request,
185                         HttpServletResponse response) throws Exception {
186                 String loginId = "";
187                 String userAgent = "";
188                 List<FavoritesFunctionalMenuItemJson> favorites = null;
189
190                 loginId = request.getHeader(EPCommonSystemProperties.MDC_LOGIN_ID);
191                 userAgent = MDC.get(EPCommonSystemProperties.PARTNER_NAME);
192
193                 EPUser epUser = epLoginService.findUserWithoutPwd(loginId);
194                 logger.info(EELFLoggerDelegate.errorLogger,
195                                 "getFavorites request was received from " + userAgent + " for the user " + loginId + ".");
196                 if (epUser == null || epUser.getId() == null) {
197                         logger.error(EELFLoggerDelegate.errorLogger,
198                                         "No User record found for the LoginId '" + loginId + "' in the database.");
199                         throw new Exception("Received null for Login-Id.");
200                 } else {
201                         favorites = functionalMenuService.getFavoriteItems(epUser.getId());
202                         FieldsValidator fieldsValidator = new FieldsValidator();
203                         response.setStatus(fieldsValidator.httpStatusCode.intValue());
204
205                         EcompPortalUtils.logAndSerializeObject(logger, "/getFavorites", "result = ", favorites);
206                 }
207
208                 return favorites;
209         }
210
211         @ApiOperation(value = "Gets functional menu items appropriate for the current user.", response = FunctionalMenuItem.class, responseContainer="List")
212         @GetMapping(value = {
213                         "/functionalMenuItemsForUser" }, produces = "application/json")
214         public List<FunctionalMenuItem> getFunctionalMenuItemsForUser(HttpServletRequest request,
215                         HttpServletResponse response) throws Exception {
216                 String loginId = "";
217                 String userAgent = "";
218                 List<FunctionalMenuItem> fnMenuItems = null;
219
220                 loginId = request.getHeader("LoginId");
221                 userAgent = MDC.get(EPCommonSystemProperties.PARTNER_NAME);
222
223                 EPUser epUser = epLoginService.findUserWithoutPwd(loginId);
224                 logger.info(EELFLoggerDelegate.errorLogger, "getFunctionalMenuItemsForUser request was received from "
225                                 + userAgent + " for the user " + loginId + ".");
226                 if (epUser == null || epUser.getId() == null) {
227                         logger.error(EELFLoggerDelegate.errorLogger,
228                                         "No User record found for the LoginId '" + loginId + "' in the database.");
229                         throw new Exception("Received null for Login-Id.");
230                 } else if (adminRolesService.isSuperAdmin(epUser)) {
231                         logger.debug(EELFLoggerDelegate.debugLogger,
232                                         "FunctionalMenuHandler: SuperUser, about to call getFunctionalMenuItems()");
233                         fnMenuItems = functionalMenuService.getFunctionalMenuItems();
234                 } else {
235                         logger.debug(EELFLoggerDelegate.debugLogger,
236                                         "getMenuItemsForAuthUser: about to call getFunctionalMenuItemsForUser()");
237                         fnMenuItems = functionalMenuService.getFunctionalMenuItemsForUser(epUser.getOrgUserId());
238                 }
239
240                 FieldsValidator fieldsValidator = new FieldsValidator();
241                 response.setStatus(fieldsValidator.httpStatusCode.intValue());
242
243                 EcompPortalUtils.logAndSerializeObject(logger, "/functionalMenuItemsForUser", "result = ", fnMenuItems);
244
245                 return fnMenuItems;
246         }
247
248         @ExceptionHandler(Exception.class)
249         protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException {
250                 logger.warn(EELFLoggerDelegate.errorLogger, "Handling bad request", e);
251                 response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());
252         }
253         
254         @EPAuditLog
255         @PostMapping(value = { "/validateCookie" })
256         public boolean validateCookie(@RequestBody EPServiceCookie epServiceCookie, HttpServletRequest request) throws Exception {
257                 Map<String,String> epServiceCookieValueMap = epServiceCookie.getValue();
258                 if(epServiceCookieValueMap!=null) {
259                         String multifactorauthfrontendurl = SystemProperties.getProperty("frontend_url");
260                         String encryptedJSessionId = epServiceCookieValueMap.get(multifactorauthfrontendurl);
261                         if(encryptedJSessionId != null) {
262                                 String jSessionId = CipherUtil.decryptPKC(encryptedJSessionId);
263                                 if(jSessionId != null) {
264                                         if(jSessionId.equals(request.getSession().getId())) {
265                                                 if(MusicUtil.isMusicEnable()) { 
266                                                         MusicSession musicSession = new MusicSession();
267                                                         String sessionId = musicSession.getAttribute(encryptedJSessionId);
268                                                         logger.info(EELFLoggerDelegate.errorLogger, "Music sessionid : "+sessionId);
269                                                         return (sessionId != null); 
270                                                 } else {
271                                                         return true;
272                                                 }
273                                         }
274                                 }
275                         }
276                 }
277                 return false;
278         }
279 }