added annotations
[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.GetMapping;
78 import org.springframework.web.bind.annotation.PostMapping;
79 import org.springframework.web.bind.annotation.RequestMethod;
80 import org.springframework.web.bind.annotation.ResponseBody;
81 import org.springframework.web.servlet.ModelAndView;
82 import org.springframework.web.util.WebUtils;
83
84 import com.fasterxml.jackson.databind.DeserializationFeature;
85 import com.fasterxml.jackson.databind.JsonNode;
86 import com.fasterxml.jackson.databind.ObjectMapper;
87
88 @Controller
89 @RequestMapping("/")
90 public class LoginController extends EPUnRestrictedBaseController implements LoginService {
91
92         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginController.class);
93
94         public static final String DEFAULT_SUCCESS_VIEW = "applicationsHome";
95         public static final String DEFAULT_FAILURE_VIEW = "login";
96         public static final String ERROR_MESSAGE_KEY = "error";
97         public static final String REDIRECT_URL = "redirectUrl";
98         public static final String REDIRECT_COLON = "redirect:";
99
100         @Autowired
101         private EPLoginService loginService;
102         @Autowired
103         private SharedContextService sharedContextService;
104         @Autowired
105         private EPRoleFunctionService ePRoleFunctionService;
106
107         private String viewName = "login";
108
109         private String welcomeView;
110
111         @GetMapping(value = { "/login.htm" })
112         public ModelAndView login(HttpServletRequest request) {
113                 Map<String, Object> model = new HashMap<String, Object>();
114                 String authentication = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM);
115                 String loginPage;
116                 if (authentication == null || "".equals(authentication) || "OICD".equals(authentication.trim()))
117                         loginPage = "openIdLogin";
118                 else
119                         loginPage = getViewName();
120                 return new ModelAndView(loginPage, "model", model);
121         }
122
123         @SuppressWarnings("rawtypes")
124         @PostMapping(value = { "/open_source/login" })
125         @ResponseBody
126         public String loginValidate(HttpServletRequest request, HttpServletResponse response) throws Exception {
127
128                 ObjectMapper mapper = new ObjectMapper();
129                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
130                 JsonNode root = mapper.readTree(request.getReader());
131
132                 EPLoginBean commandBean = new EPLoginBean();
133                 String loginId = root.get("loginId").textValue();
134                 String password = root.get("password").textValue();
135                 commandBean.setLoginId(loginId);
136                 commandBean.setLoginPwd(password);
137                 
138                 HashMap additionalParamsMap = new HashMap();
139                 StringBuilder sbAdditionalInfo = new StringBuilder();
140
141                 commandBean = getLoginService().findUser(commandBean,
142                                 (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), additionalParamsMap);
143                 String fullURL = getFullURL(request);
144                 if (commandBean.getUser() == null) {
145                         String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) ? commandBean.getLoginErrorMessage()
146                                         : "login.error.external.invalid";
147                         logger.info(EELFLoggerDelegate.debugLogger, "loginId {} does not exist in the the DB.", loginId);
148                         sbAdditionalInfo.append(String.format("But the Login-Id: %s doesn't exist in the Database. Request-URL: %s",
149                                         loginId, fullURL));
150                         return loginErrorMessage;
151                 } else {
152                         // store the currently logged in user's information in the session
153                         EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(),
154                                         commandBean.getBusinessDirectMenu(), ePRoleFunctionService);
155
156                         try {
157                                 logger.info(EELFLoggerDelegate.debugLogger, "loginValidate: store user info into share context begins");
158                                 String sessionId = request.getSession().getId();
159                                 List<SharedContext> existingSC = getSharedContextService().getSharedContexts(sessionId);
160                                 if (existingSC == null || existingSC.isEmpty()) {
161                                         getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_FIRST_NAME,
162                                                         commandBean.getUser().getFirstName());
163                                         getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_LAST_NAME,
164                                                         commandBean.getUser().getLastName());
165                                         getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_EMAIL,
166                                                         commandBean.getUser().getEmail());
167                                         getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_ORG_USERID,
168                                                         commandBean.getLoginId());
169                                 }
170
171                         } catch (Exception e) {
172                                 logger.info(EELFLoggerDelegate.errorLogger, "loginValidate: failed the shared context adding process ",
173                                                 e);
174                         }
175                         logger.info(EELFLoggerDelegate.debugLogger,
176                                         "loginValidate: PresetUp the EP service cookie and intial sessionManagement");
177
178                         SessionCookieUtil.preSetUp(request, response);
179                         SessionCookieUtil.setUpUserIdCookie(request, response, loginId);
180
181                         JSONObject j = new JSONObject("{success: success}");
182
183                         return j.toString();
184                 }
185         }
186
187         /*
188          * Work around a bug in ecompsdkos version 1.1.0 which hard-codes this endpoint.
189          */
190         @RequestMapping(value = { "/process_csp" }, method = RequestMethod.GET)
191         public ModelAndView processCsp(HttpServletRequest request, HttpServletResponse response) throws Exception {
192                 return processSingleSignOn(request, response);
193         }
194         /*
195          * Remove this method after epsdk-app-common/.../SingleSignOnController.java is
196          * repaired.
197          */
198
199         @GetMapping(value = { "/processSingleSignOn" })
200         public ModelAndView processSingleSignOn(HttpServletRequest request, HttpServletResponse response) throws Exception {
201
202                 Map<Object, Object> model = new HashMap<Object, Object>();
203                 HashMap<Object, Object> additionalParamsMap = new HashMap<Object, Object>();
204                 EPLoginBean commandBean = new EPLoginBean();
205                 MDC.put(MDC_KEY_REQUEST_ID, (getRequestId(request)==null || getRequestId(request).isEmpty()) ? UUID.randomUUID().toString():getRequestId(request));
206                 // get userId from cookie
207                 String orgUserId = SessionCookieUtil.getUserIdFromCookie(request, response);
208                 logger.info(EELFLoggerDelegate.debugLogger, "processSingleSignOn: begins with orgUserId {}", orgUserId);
209
210                 StringBuilder sbAdditionalInfo = new StringBuilder();
211                 validateDomain(request);
212                 if (orgUserId == null || orgUserId.length() == 0) {
213                         model.put(ERROR_MESSAGE_KEY, SystemProperties.MESSAGE_KEY_LOGIN_ERROR_COOKIE_EMPTY);
214                         if (request.getParameter(REDIRECT_URL) != null && request.getParameter(REDIRECT_URL).length() != 0) {
215                                 return new ModelAndView(REDIRECT_COLON + DEFAULT_FAILURE_VIEW + ".htm" + "?redirectUrl="
216                                                 + request.getParameter(REDIRECT_URL));
217                         } else {
218                                 return new ModelAndView(REDIRECT_COLON + DEFAULT_FAILURE_VIEW + ".htm");
219                         }
220                 } else {
221
222                         StopWatch stopWatch = new StopWatch("LoginController.Login");
223                         stopWatch.start();
224
225                         try {
226                                 logger.info(EELFLoggerDelegate.debugLogger,
227                                                 "Operation findUser is started to locate user {}  in the database.", orgUserId);
228                                 commandBean.setLoginId(orgUserId);
229                                 commandBean.setOrgUserId(orgUserId);
230                                 commandBean = getLoginService().findUser(commandBean,
231                                                 (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY),
232                                                 additionalParamsMap);
233
234                                 stopWatch.stop();
235                                 MDC.put(EPSystemProperties.MDC_TIMER, String.valueOf(stopWatch.getTotalTimeMillis()));
236                                 logger.info(EELFLoggerDelegate.debugLogger, "Operation findUser is completed.");
237                         } catch (Exception e) {
238                                 stopWatch.stop();
239                                 MDC.put(EPSystemProperties.MDC_TIMER, String.valueOf(stopWatch.getTotalTimeMillis()));
240                                 logger.info(EELFLoggerDelegate.errorLogger, "processSingleSignOn failed on user " + orgUserId, e);
241                         } finally {
242                                 MDC.remove(EPSystemProperties.MDC_TIMER);
243                         }
244
245                         sbAdditionalInfo.append("Login attempt is succeeded. ");
246                         String fullURL = getFullURL(request);
247                         if (commandBean.getUser() == null) {
248                                 logger.info(EELFLoggerDelegate.debugLogger,
249                                                 "processSingleSignOn: loginId {} does not exist in the the DB.", orgUserId);
250
251                                 sbAdditionalInfo.append(String.format(
252                                                 "But the Login-Id: %s doesn't exist in the Database. Created a Guest Session. Request-URL: %s",
253                                                 orgUserId, fullURL));
254                                 validateDomain(request);
255                                 if (request.getParameter(REDIRECT_URL) != null && request.getParameter(REDIRECT_URL).length() != 0) {
256                                         return new ModelAndView(REDIRECT_COLON + DEFAULT_FAILURE_VIEW + ".htm" + "?redirectUrl="
257                                                         + request.getParameter(REDIRECT_URL));
258                                 } else {
259                                         return new ModelAndView(REDIRECT_COLON + DEFAULT_FAILURE_VIEW + ".htm");
260                                 }
261                         } else {
262
263                                 sbAdditionalInfo.append(
264                                                 String.format("Login-Id: %s, Login-Method: %s, Request-URL: %s", orgUserId, "", fullURL));
265                                 logger.info(EELFLoggerDelegate.debugLogger, "processSingleSignOn: now set up user session for {}",
266                                                 orgUserId);
267
268                                 EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(),
269                                                 commandBean.getBusinessDirectMenu(), 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 }