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