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