Merge "Fix sql injection vulnerability"
[portal.git] / ecomp-portal-BE-os / src / main / java / org / onap / portalapp / controller / LoginController.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38 package org.onap.portalapp.controller;
39
40 import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
41
42 import java.io.IOException;
43 import java.net.MalformedURLException;
44 import java.net.URL;
45 import java.net.URLDecoder;
46 import java.util.Enumeration;
47 import java.util.HashMap;
48 import java.util.List;
49 import java.util.Map;
50 import java.util.UUID;
51
52 import javax.servlet.http.Cookie;
53 import javax.servlet.http.HttpServletRequest;
54 import javax.servlet.http.HttpServletResponse;
55
56 import org.apache.commons.lang.StringUtils;
57 import org.json.JSONObject;
58 import org.onap.portalapp.command.EPLoginBean;
59 import org.onap.portalapp.portal.domain.SharedContext;
60 import org.onap.portalapp.portal.service.EPLoginService;
61 import org.onap.portalapp.portal.service.EPRoleFunctionService;
62 import org.onap.portalapp.portal.service.SharedContextService;
63 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
64 import org.onap.portalapp.portal.utils.EPSystemProperties;
65 import org.onap.portalapp.util.EPUserUtils;
66 import org.onap.portalapp.util.SessionCookieUtil;
67 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
68 import org.onap.portalsdk.core.menu.MenuProperties;
69 import org.onap.portalsdk.core.util.SystemProperties;
70 import org.slf4j.MDC;
71 import org.springframework.beans.factory.annotation.Autowired;
72 import org.springframework.http.HttpStatus;
73 import org.springframework.stereotype.Controller;
74 import org.springframework.util.StopWatch;
75 import org.springframework.web.bind.annotation.ExceptionHandler;
76 import org.springframework.web.bind.annotation.RequestMapping;
77 import org.springframework.web.bind.annotation.RequestMethod;
78 import org.springframework.web.bind.annotation.ResponseBody;
79 import org.springframework.web.servlet.ModelAndView;
80 import org.springframework.web.util.WebUtils;
81
82 import com.fasterxml.jackson.databind.DeserializationFeature;
83 import com.fasterxml.jackson.databind.JsonNode;
84 import com.fasterxml.jackson.databind.ObjectMapper;
85
86 @Controller
87 @RequestMapping("/")
88 public class LoginController extends EPUnRestrictedBaseController implements LoginService {
89
90         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginController.class);
91
92         public static final String DEFAULT_SUCCESS_VIEW = "applicationsHome";
93         public static final String DEFAULT_FAILURE_VIEW = "login";
94         public static final String ERROR_MESSAGE_KEY = "error";
95         public static final String REDIRECT_URL = "redirectUrl";
96         public static final String REDIRECT_COLON = "redirect:";
97
98         @Autowired
99         private EPLoginService loginService;
100         @Autowired
101         private SharedContextService sharedContextService;
102         @Autowired
103         private EPRoleFunctionService ePRoleFunctionService;
104
105         private String viewName = "login";
106
107         private String welcomeView;
108
109         @RequestMapping(value = { "/login.htm" }, method = RequestMethod.GET)
110         public ModelAndView login(HttpServletRequest request) {
111                 Map<String, Object> model = new HashMap<String, Object>();
112                 String authentication = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM);
113                 String loginPage;
114                 if (authentication == null || "".equals(authentication) || "OICD".equals(authentication.trim()))
115                         loginPage = "openIdLogin";
116                 else
117                         loginPage = getViewName();
118                 return new ModelAndView(loginPage, "model", model);
119         }
120
121         @SuppressWarnings("rawtypes")
122         @RequestMapping(value = { "/open_source/login" }, method = RequestMethod.POST)
123         @ResponseBody
124         public String loginValidate(HttpServletRequest request, HttpServletResponse response) throws Exception {
125
126                 ObjectMapper mapper = new ObjectMapper();
127                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
128                 JsonNode root = mapper.readTree(request.getReader());
129
130                 EPLoginBean commandBean = new EPLoginBean();
131                 String loginId = root.get("loginId").textValue();
132                 String password = root.get("password").textValue();
133                 commandBean.setLoginId(loginId);
134                 commandBean.setLoginPwd(password);
135                 
136                 HashMap additionalParamsMap = new HashMap();
137                 StringBuilder sbAdditionalInfo = new StringBuilder();
138
139                 commandBean = getLoginService().findUser(commandBean,
140                                 (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), additionalParamsMap);
141                 String fullURL = getFullURL(request);
142                 if (commandBean.getUser() == null) {
143                         String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) ? commandBean.getLoginErrorMessage()
144                                         : "login.error.external.invalid";
145                         logger.info(EELFLoggerDelegate.debugLogger, "loginId {} does not exist in the the DB.", loginId);
146                         sbAdditionalInfo.append(String.format("But the Login-Id: %s doesn't exist in the Database. Request-URL: %s",
147                                         loginId, fullURL));
148                         return loginErrorMessage;
149                 } else {
150                         // store the currently logged in user's information in the session
151                         EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(),
152                                         commandBean.getBusinessDirectMenu(),
153                                         SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM), ePRoleFunctionService);
154
155                         try {
156                                 logger.info(EELFLoggerDelegate.debugLogger, "loginValidate: store user info into share context begins");
157                                 String sessionId = request.getSession().getId();
158                                 List<SharedContext> existingSC = getSharedContextService().getSharedContexts(sessionId);
159                                 if (existingSC == null || existingSC.isEmpty()) {
160                                         getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_FIRST_NAME,
161                                                         commandBean.getUser().getFirstName());
162                                         getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_LAST_NAME,
163                                                         commandBean.getUser().getLastName());
164                                         getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_EMAIL,
165                                                         commandBean.getUser().getEmail());
166                                         getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_ORG_USERID,
167                                                         commandBean.getLoginId());
168                                 }
169
170                         } catch (Exception e) {
171                                 logger.info(EELFLoggerDelegate.errorLogger, "loginValidate: failed the shared context adding process ",
172                                                 e);
173                         }
174                         logger.info(EELFLoggerDelegate.debugLogger,
175                                         "loginValidate: PresetUp the EP service cookie and intial sessionManagement");
176
177                         SessionCookieUtil.preSetUp(request, response);
178                         SessionCookieUtil.setUpUserIdCookie(request, response, loginId);
179
180                         JSONObject j = new JSONObject("{success: success}");
181
182                         return j.toString();
183                 }
184         }
185
186         /*
187          * Work around a bug in ecompsdkos version 1.1.0 which hard-codes this endpoint.
188          */
189         @RequestMapping(value = { "/process_csp" }, method = RequestMethod.GET)
190         public ModelAndView processCsp(HttpServletRequest request, HttpServletResponse response) throws Exception {
191                 return processSingleSignOn(request, response);
192         }
193         /*
194          * Remove this method after epsdk-app-common/.../SingleSignOnController.java is
195          * repaired.
196          */
197
198         @RequestMapping(value = { "/processSingleSignOn" }, method = RequestMethod.GET)
199         public ModelAndView processSingleSignOn(HttpServletRequest request, HttpServletResponse response) throws Exception {
200
201                 Map<Object, Object> model = new HashMap<Object, Object>();
202                 HashMap<Object, Object> additionalParamsMap = new HashMap<Object, Object>();
203                 EPLoginBean commandBean = new EPLoginBean();
204                 MDC.put(MDC_KEY_REQUEST_ID, (getRequestId(request)==null || getRequestId(request).isEmpty()) ? UUID.randomUUID().toString():getRequestId(request));
205                 // get userId from cookie
206                 String orgUserId = SessionCookieUtil.getUserIdFromCookie(request, response);
207                 logger.info(EELFLoggerDelegate.debugLogger, "processSingleSignOn: begins with orgUserId {}", orgUserId);
208
209                 StringBuilder sbAdditionalInfo = new StringBuilder();
210                 validateDomain(request);
211                 if (orgUserId == null || orgUserId.length() == 0) {
212                         model.put(ERROR_MESSAGE_KEY, SystemProperties.MESSAGE_KEY_LOGIN_ERROR_COOKIE_EMPTY);
213                         if (request.getParameter(REDIRECT_URL) != null && request.getParameter(REDIRECT_URL).length() != 0) {
214                                 return new ModelAndView(REDIRECT_COLON + DEFAULT_FAILURE_VIEW + ".htm" + "?redirectUrl="
215                                                 + request.getParameter(REDIRECT_URL));
216                         } else {
217                                 return new ModelAndView(REDIRECT_COLON + DEFAULT_FAILURE_VIEW + ".htm");
218                         }
219                 } else {
220
221                         StopWatch stopWatch = new StopWatch("LoginController.Login");
222                         stopWatch.start();
223
224                         try {
225                                 logger.info(EELFLoggerDelegate.debugLogger,
226                                                 "Operation findUser is started to locate user {}  in the database.", orgUserId);
227                                 commandBean.setLoginId(orgUserId);
228                                 commandBean.setOrgUserId(orgUserId);
229                                 commandBean = getLoginService().findUser(commandBean,
230                                                 (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY),
231                                                 additionalParamsMap);
232
233                                 stopWatch.stop();
234                                 MDC.put(EPSystemProperties.MDC_TIMER, String.valueOf(stopWatch.getTotalTimeMillis()));
235                                 logger.info(EELFLoggerDelegate.debugLogger, "Operation findUser is completed.");
236                         } catch (Exception e) {
237                                 stopWatch.stop();
238                                 MDC.put(EPSystemProperties.MDC_TIMER, String.valueOf(stopWatch.getTotalTimeMillis()));
239                                 logger.info(EELFLoggerDelegate.errorLogger, "processSingleSignOn failed on user " + orgUserId, e);
240                         } finally {
241                                 MDC.remove(EPSystemProperties.MDC_TIMER);
242                         }
243
244                         sbAdditionalInfo.append("Login attempt is succeeded. ");
245                         String fullURL = getFullURL(request);
246                         if (commandBean.getUser() == null) {
247                                 logger.info(EELFLoggerDelegate.debugLogger,
248                                                 "processSingleSignOn: loginId {} does not exist in the the DB.", orgUserId);
249
250                                 sbAdditionalInfo.append(String.format(
251                                                 "But the Login-Id: %s doesn't exist in the Database. Created a Guest Session. Request-URL: %s",
252                                                 orgUserId, fullURL));
253                                 validateDomain(request);
254                                 if (request.getParameter(REDIRECT_URL) != null && request.getParameter(REDIRECT_URL).length() != 0) {
255                                         return new ModelAndView(REDIRECT_COLON + DEFAULT_FAILURE_VIEW + ".htm" + "?redirectUrl="
256                                                         + request.getParameter(REDIRECT_URL));
257                                 } else {
258                                         return new ModelAndView(REDIRECT_COLON + DEFAULT_FAILURE_VIEW + ".htm");
259                                 }
260                         } else {
261
262                                 sbAdditionalInfo.append(
263                                                 String.format("Login-Id: %s, Login-Method: %s, Request-URL: %s", orgUserId, "", fullURL));
264                                 logger.info(EELFLoggerDelegate.debugLogger, "processSingleSignOn: now set up user session for {}",
265                                                 orgUserId);
266
267                                 EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(),
268                                                 commandBean.getBusinessDirectMenu(),
269                                                 SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM), ePRoleFunctionService);
270                                 logger.info(EELFLoggerDelegate.debugLogger,
271                                                 "processSingleSignOn: now set up user session for {} finished", orgUserId);
272
273                                 // Store user's information into share context
274                                 try {
275                                         logger.info(EELFLoggerDelegate.debugLogger,
276                                                         "processSingleSignOn: store user info into share context begins");
277                                         String sessionId = request.getSession().getId();
278                                         List<SharedContext> existingSC = getSharedContextService().getSharedContexts(sessionId);
279                                         if (existingSC == null || existingSC.isEmpty()) {
280                                                 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_FIRST_NAME,
281                                                                 commandBean.getUser().getFirstName());
282                                                 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_LAST_NAME,
283                                                                 commandBean.getUser().getLastName());
284                                                 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_EMAIL,
285                                                                 commandBean.getUser().getEmail());
286                                                 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_ORG_USERID,
287                                                                 commandBean.getLoginId());
288                                         }
289                                 } catch (Exception e) {
290                                         logger.info(EELFLoggerDelegate.errorLogger,
291                                                         "processSingleSignOn: failed the shared context adding process", e);
292                                 }
293
294                                 logger.info(EELFLoggerDelegate.debugLogger,
295                                                 "processSingleSignOn: PresetUp the EP service cookie and intial sessionManagement");
296                                 SessionCookieUtil.preSetUp(request, response);
297                                 SessionCookieUtil.setUpUserIdCookie(request, response, orgUserId);
298                                 logger.info(EELFLoggerDelegate.debugLogger,
299                                                 "processSingleSignOn: PresetUp the EP service cookie and intial sessionManagement completed");
300                                 logger.info(EELFLoggerDelegate.debugLogger,
301                                                 commandBean.getUser().getOrgUserId() + " exists in the the system.");
302
303                                 // get redirectUrl from URL parameter
304                                 validateDomain(request);
305                                 if (request.getParameter(REDIRECT_URL) != null && request.getParameter(REDIRECT_URL).length() != 0) {
306                                         String forwardUrl = URLDecoder.decode(request.getParameter(REDIRECT_URL), "UTF-8");
307                                         // clean cookie
308                                         Cookie cookie2 = new Cookie(REDIRECT_URL, "");
309                                         // ONAP does not use https
310                                         cookie2.setSecure(false);
311                                         cookie2.setMaxAge(0);
312                                         cookie2.setDomain(EPSystemProperties.getProperty(EPSystemProperties.COOKIE_DOMAIN));
313                                         cookie2.setPath("/");
314                                         response.addCookie(cookie2);
315                                         return new ModelAndView(REDIRECT_COLON + forwardUrl);
316                                 }
317
318                                 // first check if redirectUrl exists or not
319                                 if (WebUtils.getCookie(request, REDIRECT_URL) != null) {
320                                         String forwardUrl = WebUtils.getCookie(request, REDIRECT_URL).getValue();
321                                         // clean cookie
322                                         Cookie cookie2 = new Cookie(REDIRECT_URL, "");
323                                         // ONAP does not use https
324                                         cookie2.setSecure(false);
325                                         cookie2.setMaxAge(0);
326                                         cookie2.setDomain(EPSystemProperties.getProperty(EPSystemProperties.COOKIE_DOMAIN));
327                                         cookie2.setPath("/");
328                                         response.addCookie(cookie2);
329
330                                         return new ModelAndView(REDIRECT_COLON + forwardUrl);
331                                 }
332                         }
333                 }
334
335                 // if user has been authenticated, now take them to the welcome page.
336                 logger.info(EELFLoggerDelegate.debugLogger, "processSingleSignOn: Now return to application home page");
337                 return new ModelAndView(REDIRECT_COLON + SystemProperties.getProperty(EPSystemProperties.FE_URL));
338         }
339
340         private void validateDomain(HttpServletRequest request) throws MalformedURLException {
341                 final String returnToAppUrl = request.getParameter(REDIRECT_URL);
342                 if (StringUtils.isNotBlank(returnToAppUrl)) {
343                         String hostName = new URL(returnToAppUrl).getHost();
344                         if (StringUtils.isNotBlank(hostName)
345                                         && !hostName.endsWith(EPSystemProperties.getProperty(EPCommonSystemProperties.COOKIE_DOMAIN))) {
346                                 logger.debug(EELFLoggerDelegate.debugLogger,
347                                                 "processSingleSignOn ()  accessing Unauthorized url  :" + hostName);
348                                 throw new SecurityException("accessing Unauthorized url : " + hostName);
349                         }
350                 }
351         }
352
353         private String getFullURL(HttpServletRequest request) {
354                 if (request != null) {
355                         String requestURL = request.getRequestURL().toString();
356                         String queryString = request.getQueryString();
357                         if (queryString == null) {
358                                 return requestURL;
359                         } else {
360                                 return requestURL + "?" + queryString;
361                         }
362                 }
363                 return "";
364         }
365
366         private String getRequestId(HttpServletRequest request) {
367                 Enumeration<String> headerNames = request.getHeaderNames();
368                 String requestId = "";
369                 while (headerNames.hasMoreElements()) {
370                         String headerName = headerNames.nextElement();
371                         logger.debug(EELFLoggerDelegate.debugLogger, "getRequestId: header {} has value {}", headerName,
372                                         request.getHeader(headerName));
373                         if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) {
374                                 requestId = request.getHeader(headerName);
375                                 break;
376                         }
377                 }
378                 return requestId.isEmpty() ? UUID.randomUUID().toString() : requestId;
379         }
380
381         public String getWelcomeView() {
382                 return welcomeView;
383         }
384
385         public void setWelcomeView(String welcomeView) {
386                 this.welcomeView = welcomeView;
387         }
388
389         @Override
390         public String getViewName() {
391                 return viewName;
392         }
393
394         @Override
395         public void setViewName(String viewName) {
396                 this.viewName = viewName;
397         }
398
399         public EPLoginService getLoginService() {
400                 return loginService;
401         }
402
403         public void setLoginService(EPLoginService loginService) {
404                 this.loginService = loginService;
405         }
406
407         public SharedContextService getSharedContextService() {
408                 return sharedContextService;
409         }
410
411         public void setSharedContextService(SharedContextService sharedContextService) {
412                 this.sharedContextService = sharedContextService;
413         }
414
415         @ExceptionHandler(Exception.class)
416         protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException {
417                 logger.warn(EELFLoggerDelegate.errorLogger, "Handling bad request", e);
418                 response.sendError(HttpStatus.BAD_REQUEST.value());
419         }
420 }