2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
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
26 * https://creativecommons.org/licenses/by/4.0/
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.
34 * ============LICENSE_END============================================
38 package org.onap.portalapp.controller;
40 import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
42 import java.io.IOException;
43 import java.net.MalformedURLException;
45 import java.net.URLDecoder;
46 import java.util.Enumeration;
47 import java.util.HashMap;
48 import java.util.List;
50 import java.util.UUID;
52 import javax.servlet.http.Cookie;
53 import javax.servlet.http.HttpServletRequest;
54 import javax.servlet.http.HttpServletResponse;
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;
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;
82 import com.fasterxml.jackson.databind.DeserializationFeature;
83 import com.fasterxml.jackson.databind.JsonNode;
84 import com.fasterxml.jackson.databind.ObjectMapper;
88 public class LoginController extends EPUnRestrictedBaseController implements LoginService {
90 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginController.class);
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:";
99 private EPLoginService loginService;
101 private SharedContextService sharedContextService;
103 private EPRoleFunctionService ePRoleFunctionService;
105 private String viewName = "login";
107 private String welcomeView;
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);
114 if (authentication == null || "".equals(authentication) || "OICD".equals(authentication.trim()))
115 loginPage = "openIdLogin";
117 loginPage = getViewName();
118 return new ModelAndView(loginPage, "model", model);
121 @SuppressWarnings("rawtypes")
122 @RequestMapping(value = { "/open_source/login" }, method = RequestMethod.POST)
124 public String loginValidate(HttpServletRequest request, HttpServletResponse response) throws Exception {
126 ObjectMapper mapper = new ObjectMapper();
127 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
128 JsonNode root = mapper.readTree(request.getReader());
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);
136 HashMap additionalParamsMap = new HashMap();
137 StringBuilder sbAdditionalInfo = new StringBuilder();
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",
148 return loginErrorMessage;
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);
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());
170 } catch (Exception e) {
171 logger.info(EELFLoggerDelegate.errorLogger, "loginValidate: failed the shared context adding process ",
174 logger.info(EELFLoggerDelegate.debugLogger,
175 "loginValidate: PresetUp the EP service cookie and intial sessionManagement");
177 SessionCookieUtil.preSetUp(request, response);
178 SessionCookieUtil.setUpUserIdCookie(request, response, loginId);
180 JSONObject j = new JSONObject("{success: success}");
187 * Work around a bug in ecompsdkos version 1.1.0 which hard-codes this endpoint.
189 @RequestMapping(value = { "/process_csp" }, method = RequestMethod.GET)
190 public ModelAndView processCsp(HttpServletRequest request, HttpServletResponse response) throws Exception {
191 return processSingleSignOn(request, response);
194 * Remove this method after epsdk-app-common/.../SingleSignOnController.java is
198 @RequestMapping(value = { "/processSingleSignOn" }, method = RequestMethod.GET)
199 public ModelAndView processSingleSignOn(HttpServletRequest request, HttpServletResponse response) throws Exception {
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);
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));
217 return new ModelAndView(REDIRECT_COLON + DEFAULT_FAILURE_VIEW + ".htm");
221 StopWatch stopWatch = new StopWatch("LoginController.Login");
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);
234 MDC.put(EPSystemProperties.MDC_TIMER, String.valueOf(stopWatch.getTotalTimeMillis()));
235 logger.info(EELFLoggerDelegate.debugLogger, "Operation findUser is completed.");
236 } catch (Exception e) {
238 MDC.put(EPSystemProperties.MDC_TIMER, String.valueOf(stopWatch.getTotalTimeMillis()));
239 logger.info(EELFLoggerDelegate.errorLogger, "processSingleSignOn failed on user " + orgUserId, e);
241 MDC.remove(EPSystemProperties.MDC_TIMER);
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);
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));
258 return new ModelAndView(REDIRECT_COLON + DEFAULT_FAILURE_VIEW + ".htm");
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 {}",
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);
273 // Store user's information into share context
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());
289 } catch (Exception e) {
290 logger.info(EELFLoggerDelegate.errorLogger,
291 "processSingleSignOn: failed the shared context adding process", e);
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.");
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");
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);
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();
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);
330 return new ModelAndView(REDIRECT_COLON + forwardUrl);
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));
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);
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) {
360 return requestURL + "?" + queryString;
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);
378 return requestId.isEmpty() ? UUID.randomUUID().toString() : requestId;
381 public String getWelcomeView() {
385 public void setWelcomeView(String welcomeView) {
386 this.welcomeView = welcomeView;
390 public String getViewName() {
395 public void setViewName(String viewName) {
396 this.viewName = viewName;
399 public EPLoginService getLoginService() {
403 public void setLoginService(EPLoginService loginService) {
404 this.loginService = loginService;
407 public SharedContextService getSharedContextService() {
408 return sharedContextService;
411 public void setSharedContextService(SharedContextService sharedContextService) {
412 this.sharedContextService = sharedContextService;
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());