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