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.net.MalformedURLException;
44 import java.net.URLDecoder;
45 import java.util.Enumeration;
46 import java.util.HashMap;
47 import java.util.List;
49 import java.util.UUID;
51 import javax.servlet.http.Cookie;
52 import javax.servlet.http.HttpServletRequest;
53 import javax.servlet.http.HttpServletResponse;
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;
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;
79 import com.fasterxml.jackson.databind.DeserializationFeature;
80 import com.fasterxml.jackson.databind.JsonNode;
81 import com.fasterxml.jackson.databind.ObjectMapper;
85 public class LoginController extends EPUnRestrictedBaseController implements LoginService {
87 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginController.class);
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:";
96 private EPLoginService loginService;
98 private SharedContextService sharedContextService;
100 private EPRoleFunctionService ePRoleFunctionService;
102 private String viewName = "login";
104 private String welcomeView;
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);
111 if (authentication == null || "".equals(authentication) || "OICD".equals(authentication.trim()))
112 loginPage = "openIdLogin";
114 loginPage = getViewName();
115 return new ModelAndView(loginPage, "model", model);
118 @SuppressWarnings("rawtypes")
119 @RequestMapping(value = { "/open_source/login" }, method = RequestMethod.POST)
121 public String loginValidate(HttpServletRequest request, HttpServletResponse response) throws Exception {
123 ObjectMapper mapper = new ObjectMapper();
124 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
125 JsonNode root = mapper.readTree(request.getReader());
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);
133 HashMap additionalParamsMap = new HashMap();
134 StringBuilder sbAdditionalInfo = new StringBuilder();
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",
145 return loginErrorMessage;
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);
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());
167 } catch (Exception e) {
168 logger.info(EELFLoggerDelegate.errorLogger, "loginValidate: failed the shared context adding process ",
171 logger.info(EELFLoggerDelegate.debugLogger,
172 "loginValidate: PresetUp the EP service cookie and intial sessionManagement");
174 SessionCookieUtil.preSetUp(request, response);
175 SessionCookieUtil.setUpUserIdCookie(request, response, loginId);
177 JSONObject j = new JSONObject("{success: success}");
184 * Work around a bug in ecompsdkos version 1.1.0 which hard-codes this endpoint.
186 @RequestMapping(value = { "/process_csp" }, method = RequestMethod.GET)
187 public ModelAndView processCsp(HttpServletRequest request, HttpServletResponse response) throws Exception {
188 return processSingleSignOn(request, response);
191 * Remove this method after epsdk-app-common/.../SingleSignOnController.java is
195 @RequestMapping(value = { "/processSingleSignOn" }, method = RequestMethod.GET)
196 public ModelAndView processSingleSignOn(HttpServletRequest request, HttpServletResponse response) throws Exception {
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);
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));
214 return new ModelAndView(REDIRECT_COLON + DEFAULT_FAILURE_VIEW + ".htm");
218 StopWatch stopWatch = new StopWatch("LoginController.Login");
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);
231 MDC.put(EPSystemProperties.MDC_TIMER, String.valueOf(stopWatch.getTotalTimeMillis()));
232 logger.info(EELFLoggerDelegate.debugLogger, "Operation findUser is completed.");
233 } catch (Exception e) {
235 MDC.put(EPSystemProperties.MDC_TIMER, String.valueOf(stopWatch.getTotalTimeMillis()));
236 logger.info(EELFLoggerDelegate.errorLogger, "processSingleSignOn failed on user " + orgUserId, e);
238 MDC.remove(EPSystemProperties.MDC_TIMER);
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);
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));
255 return new ModelAndView(REDIRECT_COLON + DEFAULT_FAILURE_VIEW + ".htm");
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 {}",
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);
270 // Store user's information into share context
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());
286 } catch (Exception e) {
287 logger.info(EELFLoggerDelegate.errorLogger,
288 "processSingleSignOn: failed the shared context adding process", e);
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.");
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");
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);
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();
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);
327 return new ModelAndView(REDIRECT_COLON + forwardUrl);
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));
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);
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) {
357 return requestURL + "?" + queryString;
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);
375 return requestId.isEmpty() ? UUID.randomUUID().toString() : requestId;
378 public String getWelcomeView() {
382 public void setWelcomeView(String welcomeView) {
383 this.welcomeView = welcomeView;
387 public String getViewName() {
392 public void setViewName(String viewName) {
393 this.viewName = viewName;
396 public EPLoginService getLoginService() {
400 public void setLoginService(EPLoginService loginService) {
401 this.loginService = loginService;
404 public SharedContextService getSharedContextService() {
405 return sharedContextService;
408 public void setSharedContextService(SharedContextService sharedContextService) {
409 this.sharedContextService = sharedContextService;