[SDC-29] rebase continue work to align source
[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().processEcompError(EcompErrorName.FePortalServletError, "Portal Servlet");
71                         FeEcompErrorManager.getInstance().logFePortalServletError("Portal Servlet");
72                         log.error("Error during getting portal page", e);
73                 }
74         }
75         
76         /**
77          * Building new HTTP request and setting headers for the request The request
78          * will dispatch to index.html
79          * 
80          * @param request
81          * @param response
82          * @throws ServletException
83          * @throws IOException
84          */
85         private void addRequestHeadersUsingWebseal(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
86                 
87                 response.setContentType("text/html");
88
89                 // Create new request object to dispatch
90                 MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request);
91
92                 // Get configuration object (reads data from configuration.yaml)
93                 Configuration configuration = getConfiguration(request);
94
95                 // Check if we got header from webseal
96                 String userId = request.getHeader(Constants.WEBSEAL_USER_ID_HEADER);
97                 if (null == userId) {
98                         // Authentication via ecomp portal
99                         try {
100                                 String userIdFromCookie = getUserIdFromCookie(request);
101                                 if (("").equals(userIdFromCookie)) {
102                                         // This is probably a webseal request, so missing header in request should be printed.
103                                         response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG);
104                                 }
105                                 userId = userIdFromCookie;
106                         } catch (Exception e) {
107                                 response.sendError(HttpServletResponse.SC_USE_PROXY, AUTHORIZATION_ERROR_MSG);
108                         }
109                 }
110                 
111                 // Replace webseal header with open source header
112                 mutableRequest.putHeader(Constants.USER_ID, userId);    
113                 
114                 // Getting identification headers from configuration.yaml
115                 // (identificationHeaderFields) and setting them to new request
116                 // mutableRequest
117                 List<List<String>> identificationHeaderFields = configuration.getIdentificationHeaderFields();
118                 for (List<String> possibleHeadersToRecieve : identificationHeaderFields) {
119                         String allowedHeaderToPass = possibleHeadersToRecieve.get(0);
120                         setNewHeader(possibleHeadersToRecieve, allowedHeaderToPass, request, mutableRequest);
121                 }
122
123                 // Getting optional headers from configuration.yaml
124                 // (optionalHeaderFields) and setting them to new request mutableRequest
125                 List<List<String>> optionalHeaderFields = configuration.getOptionalHeaderFields();
126                 for (List<String> possibleHeadersToRecieve : optionalHeaderFields) {
127                         String allowedHeaderToPass = possibleHeadersToRecieve.get(0);
128                         setNewHeader(possibleHeadersToRecieve, allowedHeaderToPass, request, mutableRequest);
129                 }
130
131                 // Print headers from original request for debug purposes
132                 printHeaders(request);
133
134                 // In case using webseal, validate all mandatory headers (identificationHeaderFields) are included in the new request (mutableRequest).
135                 // Via ecomp portal do not need to check the headers.
136                 boolean allHeadersExist = true;
137                 if (null != request.getHeader(Constants.WEBSEAL_USER_ID_HEADER)) {
138                         allHeadersExist = checkHeaders(mutableRequest);
139                 }
140                 
141                 if (allHeadersExist) {
142                         addCookies(response, mutableRequest, getMandatoryHeaders(request));
143                         addCookies(response, mutableRequest, getOptionalHeaders(request));
144                         RequestDispatcher rd = request.getRequestDispatcher("index.html");
145                         rd.forward(mutableRequest, response);
146                 } else {
147                         response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG);
148                 }
149         }
150
151         /**
152          * Print all request headers to the log
153          * 
154          * @param request
155          */
156         private void printHeaders(HttpServletRequest request) {
157
158                 if (log.isDebugEnabled()) {
159                         StringBuilder builder = new StringBuilder();
160                         String sessionId = "";
161                         if (request.getSession() != null) {
162                                 String id = request.getSession().getId();
163                                 if (id != null) {
164                                         sessionId = id;
165                                 }
166                         }
167
168                         builder.append("Receiving request with headers:" + NEW_LINE);
169                         log.debug("{}", request.getHeaderNames());
170                         @SuppressWarnings("unchecked")
171                         Enumeration<String> headerNames = request.getHeaderNames();
172                         if (headerNames != null) {
173                                 while (headerNames.hasMoreElements()) {
174                                         String headerName = headerNames.nextElement();
175                                         String headerValue = request.getHeader(headerName);
176                                         builder.append("session " + sessionId + " header: name = " + headerName + ", value = " + headerValue + NEW_LINE);
177                                 }
178                         }
179
180                         log.debug(builder.toString());
181                 }
182
183         }
184
185         /**
186          * Add cookies (that where set in the new request headers) in the response
187          * 
188          * @param response
189          * @param request
190          * @param headers
191          */
192         private void addCookies(HttpServletResponse response, HttpServletRequest request, String[] headers) {
193                 for (int i = 0; i < headers.length; i++) {
194                         String currHeader = headers[i];
195                         String headerValue = request.getHeader(currHeader);
196                         if (headerValue != null) {
197                                 response.addCookie(new Cookie(currHeader, headerValue));
198                         }
199                 }
200         }
201
202         /**
203          * Get mandatory headers (identificationHeaderFields) String array, and
204          * checks that each header exists in the new request
205          * 
206          * @param request
207          * @return boolean
208          */
209         private boolean checkHeaders(HttpServletRequest request) {
210                 String[] mandatoryHeaders = getMandatoryHeaders(request);
211
212                 boolean allHeadersExist = true;
213                 for (int i = 0; i < mandatoryHeaders.length; i++) {
214                         String headerValue = request.getHeader(mandatoryHeaders[i]);
215                         if (headerValue == null) {
216                                 allHeadersExist = false;
217                                 break;
218                         }
219                 }
220                 return allHeadersExist;
221         }
222
223         /**
224          * Get mandatory headers (identificationHeaderFields) from
225          * configuration.yaml file and return String[]
226          * 
227          * @param request
228          * @return String[]
229          */
230         private String[] getMandatoryHeaders(HttpServletRequest request) {
231                 Configuration configuration = getConfiguration(request);
232                 List<List<String>> identificationHeaderFields = configuration.getIdentificationHeaderFields();
233                 String[] mandatoryHeaders = new String[identificationHeaderFields.size()];
234                 for (int i = 0; i < identificationHeaderFields.size(); i++) {
235                         mandatoryHeaders[i] = identificationHeaderFields.get(i).get(0);
236                 }
237                 return mandatoryHeaders;
238         }
239
240         /**
241          * Get optional headers (optionalHeaderFields) from configuration.yaml file
242          * and return String[]
243          * 
244          * @param request
245          * @return String[]
246          */
247         private String[] getOptionalHeaders(HttpServletRequest request) {
248                 Configuration configuration = getConfiguration(request);
249                 List<List<String>> optionalHeaderFields = configuration.getOptionalHeaderFields();
250                 String[] optionalHeaders = new String[optionalHeaderFields.size()];
251                 for (int i = 0; i < optionalHeaderFields.size(); i++) {
252                         optionalHeaders[i] = optionalHeaderFields.get(i).get(0);
253                 }
254                 return optionalHeaders;
255         }
256
257         /**
258          * Return Configuration object to read from configuration.yaml
259          * 
260          * @param request
261          * @return Configuration
262          */
263         private Configuration getConfiguration(HttpServletRequest request) {
264                 ConfigurationManager configManager = (ConfigurationManager) request.getSession().getServletContext().getAttribute(org.openecomp.sdc.common.api.Constants.CONFIGURATION_MANAGER_ATTR);
265                 return configManager.getConfiguration();
266         }
267
268         private boolean setNewHeader(List<String> possibleOldHeaders, String newHeaderToSet, HttpServletRequest oldRequest, MutableHttpServletRequest newRequest) {
269                 boolean newHeaderIsSet = false;
270                 for (int i = 0; i < possibleOldHeaders.size() && !newHeaderIsSet; i++) {
271                         String headerValue = oldRequest.getHeader(possibleOldHeaders.get(i));
272                         if (headerValue != null) {
273                                 newRequest.putHeader(newHeaderToSet, headerValue);
274                                 newHeaderIsSet = true;
275                         }
276                 }
277                 return newHeaderIsSet;
278         }
279         
280         private static String getUserIdFromCookie(HttpServletRequest request) throws Exception {
281                 String userId = "";
282                 Cookie[] cookies = request.getCookies();
283                 Cookie userIdcookie = null;
284                 if (cookies != null)
285                         for (Cookie cookie : cookies)
286                                 if (cookie.getName().equals(Constants.USER_ID))
287                                         userIdcookie = cookie;
288                 if (userIdcookie != null) {
289                         userId = CipherUtil.decrypt(userIdcookie.getValue(),
290                                         PortalApiProperties.getProperty(PortalApiConstants.Decryption_Key));
291                 }
292                 return userId;
293
294         }
295 }