Sync Integ to Master
[sdc.git] / catalog-fe / src / main / java / org / openecomp / sdc / fe / servlets / PortalServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.fe.servlets;
22
23 import java.io.IOException;
24 import java.util.Enumeration;
25 import java.util.List;
26
27 import javax.servlet.RequestDispatcher;
28 import javax.servlet.ServletException;
29 import javax.servlet.http.Cookie;
30 import javax.servlet.http.HttpServlet;
31 import javax.servlet.http.HttpServletRequest;
32 import javax.servlet.http.HttpServletResponse;
33 import javax.ws.rs.GET;
34 import javax.ws.rs.Path;
35 import javax.ws.rs.core.Context;
36
37 import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
38 import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
39 import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
40 import org.openecomp.sdc.common.config.EcompErrorName;
41 import org.openecomp.sdc.common.impl.MutableHttpServletRequest;
42 import org.openecomp.sdc.fe.Constants;
43 import org.openecomp.sdc.fe.config.Configuration;
44 import org.openecomp.sdc.fe.config.ConfigurationManager;
45 import org.openecomp.sdc.fe.config.FeEcompErrorManager;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 /**
50  * Root resource (exposed at "/" path)
51  */
52 @Path("/")
53 public class PortalServlet extends HttpServlet {
54
55         private static Logger log = LoggerFactory.getLogger(PortalServlet.class.getName());
56         private static final long serialVersionUID = 1L;
57         public static final String MISSING_HEADERS_MSG = "Missing Headers In Request";
58         public static final String AUTHORIZATION_ERROR_MSG = "Autherization error";
59         public static final String NEW_LINE = System.getProperty("line.separator");
60
61         /**
62          * Entry point from ECOMP portal
63          */
64         @GET
65         @Path("/portal")
66         public void doGet(@Context final HttpServletRequest request, @Context final HttpServletResponse response) {
67                 try {
68                         addRequestHeadersUsingWebseal(request, response);
69                 } catch (Exception e) {
70                         FeEcompErrorManager.getInstance().logFePortalServletError("Portal Servlet");
71                         log.error("Error during getting portal page", e);
72                 }
73         }
74         
75         /**
76          * Building new HTTP request and setting headers for the request The request
77          * will dispatch to index.html
78          * 
79          * @param request
80          * @param response
81          * @throws ServletException
82          * @throws IOException
83          */
84         private void addRequestHeadersUsingWebseal(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
85                 
86                 response.setContentType("text/html");
87
88                 // Create new request object to dispatch
89                 MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request);
90
91                 // Get configuration object (reads data from configuration.yaml)
92                 Configuration configuration = getConfiguration(request);
93
94                 // Check if we got header from webseal
95                 String userId = request.getHeader(Constants.WEBSEAL_USER_ID_HEADER);
96                 if (null == userId) {
97                         // Authentication via ecomp portal
98                         try {
99                                 String userIdFromCookie = getUserIdFromCookie(request);
100                                 if (("").equals(userIdFromCookie)) {
101                                         // This is probably a webseal request, so missing header in request should be printed.
102                                         response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG);
103                                 }
104                                 userId = userIdFromCookie;
105                         } catch (Exception e) {
106                                 response.sendError(HttpServletResponse.SC_USE_PROXY, AUTHORIZATION_ERROR_MSG);
107                         }
108                 }
109                 
110                 // Replace webseal header with open source header
111                 mutableRequest.putHeader(Constants.USER_ID, userId);    
112                 
113                 // Getting identification headers from configuration.yaml
114                 // (identificationHeaderFields) and setting them to new request
115                 // mutableRequest
116                 List<List<String>> identificationHeaderFields = configuration.getIdentificationHeaderFields();
117                 for (List<String> possibleHeadersToRecieve : identificationHeaderFields) {
118                         String allowedHeaderToPass = possibleHeadersToRecieve.get(0);
119                         setNewHeader(possibleHeadersToRecieve, allowedHeaderToPass, request, mutableRequest);
120                 }
121
122                 // Getting optional headers from configuration.yaml
123                 // (optionalHeaderFields) and setting them to new request mutableRequest
124                 List<List<String>> optionalHeaderFields = configuration.getOptionalHeaderFields();
125                 for (List<String> possibleHeadersToRecieve : optionalHeaderFields) {
126                         String allowedHeaderToPass = possibleHeadersToRecieve.get(0);
127                         setNewHeader(possibleHeadersToRecieve, allowedHeaderToPass, request, mutableRequest);
128                 }
129
130                 // Print headers from original request for debug purposes
131                 printHeaders(request);
132
133                 // In case using webseal, validate all mandatory headers (identificationHeaderFields) are included in the new request (mutableRequest).
134                 // Via ecomp portal do not need to check the headers.
135                 boolean allHeadersExist = true;
136                 if (null != request.getHeader(Constants.WEBSEAL_USER_ID_HEADER)) {
137                         allHeadersExist = checkHeaders(mutableRequest);
138                 }
139                 
140                 if (allHeadersExist) {
141                         addCookies(response, mutableRequest, getMandatoryHeaders(request));
142                         addCookies(response, mutableRequest, getOptionalHeaders(request));
143                         RequestDispatcher rd = request.getRequestDispatcher("index.html");
144                         rd.forward(mutableRequest, response);
145                 } else {
146                         response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG);
147                 }
148         }
149
150         /**
151          * Print all request headers to the log
152          * 
153          * @param request
154          */
155         private void printHeaders(HttpServletRequest request) {
156
157                 if (log.isDebugEnabled()) {
158                         StringBuilder builder = new StringBuilder();
159                         String sessionId = "";
160                         if (request.getSession() != null) {
161                                 String id = request.getSession().getId();
162                                 if (id != null) {
163                                         sessionId = id;
164                                 }
165                         }
166
167                         builder.append("Receiving request with headers:" + NEW_LINE);
168                         log.debug("{}", request.getHeaderNames());
169                         @SuppressWarnings("unchecked")
170                         Enumeration<String> headerNames = request.getHeaderNames();
171                         if (headerNames != null) {
172                                 while (headerNames.hasMoreElements()) {
173                                         String headerName = headerNames.nextElement();
174                                         String headerValue = request.getHeader(headerName);
175                                         builder.append("session " + sessionId + " header: name = " + headerName + ", value = " + headerValue + NEW_LINE);
176                                 }
177                         }
178
179                         log.debug(builder.toString());
180                 }
181
182         }
183
184         /**
185          * Add cookies (that where set in the new request headers) in the response
186          * 
187          * @param response
188          * @param request
189          * @param headers
190          */
191         private void addCookies(HttpServletResponse response, HttpServletRequest request, String[] headers) {
192                 for (int i = 0; i < headers.length; i++) {
193                         String currHeader = headers[i];
194                         String headerValue = request.getHeader(currHeader);
195                         if (headerValue != null) {
196                                 response.addCookie(new Cookie(currHeader, headerValue));
197                         }
198                 }
199         }
200
201         /**
202          * Get mandatory headers (identificationHeaderFields) String array, and
203          * checks that each header exists in the new request
204          * 
205          * @param request
206          * @return boolean
207          */
208         private boolean checkHeaders(HttpServletRequest request) {
209                 String[] mandatoryHeaders = getMandatoryHeaders(request);
210
211                 boolean allHeadersExist = true;
212                 for (int i = 0; i < mandatoryHeaders.length; i++) {
213                         String headerValue = request.getHeader(mandatoryHeaders[i]);
214                         if (headerValue == null) {
215                                 allHeadersExist = false;
216                                 break;
217                         }
218                 }
219                 return allHeadersExist;
220         }
221
222         /**
223          * Get mandatory headers (identificationHeaderFields) from
224          * configuration.yaml file and return String[]
225          * 
226          * @param request
227          * @return String[]
228          */
229         private String[] getMandatoryHeaders(HttpServletRequest request) {
230                 Configuration configuration = getConfiguration(request);
231                 List<List<String>> identificationHeaderFields = configuration.getIdentificationHeaderFields();
232                 String[] mandatoryHeaders = new String[identificationHeaderFields.size()];
233                 for (int i = 0; i < identificationHeaderFields.size(); i++) {
234                         mandatoryHeaders[i] = identificationHeaderFields.get(i).get(0);
235                 }
236                 return mandatoryHeaders;
237         }
238
239         /**
240          * Get optional headers (optionalHeaderFields) from configuration.yaml file
241          * and return String[]
242          * 
243          * @param request
244          * @return String[]
245          */
246         private String[] getOptionalHeaders(HttpServletRequest request) {
247                 Configuration configuration = getConfiguration(request);
248                 List<List<String>> optionalHeaderFields = configuration.getOptionalHeaderFields();
249                 String[] optionalHeaders = new String[optionalHeaderFields.size()];
250                 for (int i = 0; i < optionalHeaderFields.size(); i++) {
251                         optionalHeaders[i] = optionalHeaderFields.get(i).get(0);
252                 }
253                 return optionalHeaders;
254         }
255
256         /**
257          * Return Configuration object to read from configuration.yaml
258          * 
259          * @param request
260          * @return Configuration
261          */
262         private Configuration getConfiguration(HttpServletRequest request) {
263                 ConfigurationManager configManager = (ConfigurationManager) request.getSession().getServletContext().getAttribute(org.openecomp.sdc.common.api.Constants.CONFIGURATION_MANAGER_ATTR);
264                 return configManager.getConfiguration();
265         }
266
267         private boolean setNewHeader(List<String> possibleOldHeaders, String newHeaderToSet, HttpServletRequest oldRequest, MutableHttpServletRequest newRequest) {
268                 boolean newHeaderIsSet = false;
269                 for (int i = 0; i < possibleOldHeaders.size() && !newHeaderIsSet; i++) {
270                         String headerValue = oldRequest.getHeader(possibleOldHeaders.get(i));
271                         if (headerValue != null) {
272                                 newRequest.putHeader(newHeaderToSet, headerValue);
273                                 newHeaderIsSet = true;
274                         }
275                 }
276                 return newHeaderIsSet;
277         }
278         
279         private static String getUserIdFromCookie(HttpServletRequest request) throws Exception {
280                 String userId = "";
281                 Cookie[] cookies = request.getCookies();
282                 Cookie userIdcookie = null;
283                 if (cookies != null)
284                         for (Cookie cookie : cookies)
285                                 if (cookie.getName().equals(Constants.ECOMP_PORTAL_COOKIE))
286                                         userIdcookie = cookie;
287                 if (userIdcookie != null) {
288                         userId = CipherUtil.decrypt(userIdcookie.getValue(),
289                                         PortalApiProperties.getProperty(PortalApiConstants.Decryption_Key));
290                 }
291                 return userId;
292
293         }
294 }