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.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;
84 import com.fasterxml.jackson.databind.DeserializationFeature;
85 import com.fasterxml.jackson.databind.JsonNode;
86 import com.fasterxml.jackson.databind.ObjectMapper;
90 public class LoginController extends EPUnRestrictedBaseController implements LoginService {
92 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginController.class);
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:";
101 private EPLoginService loginService;
103 private SharedContextService sharedContextService;
105 private EPRoleFunctionService ePRoleFunctionService;
107 private String viewName = "login";
109 private String welcomeView;
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);
116 if (authentication == null || "".equals(authentication) || "OICD".equals(authentication.trim()))
117 loginPage = "openIdLogin";
119 loginPage = getViewName();
120 return new ModelAndView(loginPage, "model", model);
123 @SuppressWarnings("rawtypes")
124 @PostMapping(value = { "/open_source/login" })
126 public String loginValidate(HttpServletRequest request, HttpServletResponse response) throws Exception {
128 ObjectMapper mapper = new ObjectMapper();
129 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
130 JsonNode root = mapper.readTree(request.getReader());
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);
138 HashMap additionalParamsMap = new HashMap();
139 StringBuilder sbAdditionalInfo = new StringBuilder();
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",
150 return loginErrorMessage;
152 // store the currently logged in user's information in the session
153 EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(),
154 commandBean.getBusinessDirectMenu(), ePRoleFunctionService);
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());
171 } catch (Exception e) {
172 logger.info(EELFLoggerDelegate.errorLogger, "loginValidate: failed the shared context adding process ",
175 logger.info(EELFLoggerDelegate.debugLogger,
176 "loginValidate: PresetUp the EP service cookie and intial sessionManagement");
178 SessionCookieUtil.preSetUp(request, response);
179 SessionCookieUtil.setUpUserIdCookie(request, response, loginId);
181 JSONObject j = new JSONObject("{success: success}");
188 * Work around a bug in ecompsdkos version 1.1.0 which hard-codes this endpoint.
190 @RequestMapping(value = { "/process_csp" }, method = RequestMethod.GET)
191 public ModelAndView processCsp(HttpServletRequest request, HttpServletResponse response) throws Exception {
192 return processSingleSignOn(request, response);
195 * Remove this method after epsdk-app-common/.../SingleSignOnController.java is
199 @GetMapping(value = { "/processSingleSignOn" })
200 public ModelAndView processSingleSignOn(HttpServletRequest request, HttpServletResponse response) throws Exception {
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);
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));
218 return new ModelAndView(REDIRECT_COLON + DEFAULT_FAILURE_VIEW + ".htm");
222 StopWatch stopWatch = new StopWatch("LoginController.Login");
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);
235 MDC.put(EPSystemProperties.MDC_TIMER, String.valueOf(stopWatch.getTotalTimeMillis()));
236 logger.info(EELFLoggerDelegate.debugLogger, "Operation findUser is completed.");
237 } catch (Exception e) {
239 MDC.put(EPSystemProperties.MDC_TIMER, String.valueOf(stopWatch.getTotalTimeMillis()));
240 logger.info(EELFLoggerDelegate.errorLogger, "processSingleSignOn failed on user " + orgUserId, e);
242 MDC.remove(EPSystemProperties.MDC_TIMER);
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);
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));
259 return new ModelAndView(REDIRECT_COLON + DEFAULT_FAILURE_VIEW + ".htm");
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 {}",
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);
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());