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