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