2 * ================================================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ================================================================================
20 package org.openecomp.portalapp.controller;
22 import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
24 import java.net.URLDecoder;
25 import java.util.Enumeration;
26 import java.util.HashMap;
27 import java.util.List;
29 import java.util.UUID;
31 import javax.servlet.http.Cookie;
32 import javax.servlet.http.HttpServletRequest;
33 import javax.servlet.http.HttpServletResponse;
35 import org.json.JSONObject;
36 import org.openecomp.portalapp.command.EPLoginBean;
37 import org.openecomp.portalapp.portal.domain.SharedContext;
38 import org.openecomp.portalapp.portal.service.EPLoginService;
39 import org.openecomp.portalapp.portal.service.EPRoleService;
40 import org.openecomp.portalapp.portal.service.SharedContextService;
41 import org.openecomp.portalapp.portal.utils.EPSystemProperties;
42 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
43 import org.openecomp.portalapp.service.EPProfileService;
44 import org.openecomp.portalapp.util.EPUserUtils;
45 import org.openecomp.portalapp.util.SessionCookieUtil;
46 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
47 import org.openecomp.portalsdk.core.menu.MenuProperties;
48 import org.openecomp.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
49 import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
50 import org.openecomp.portalsdk.core.util.SystemProperties;
51 import org.openecomp.portalsdk.core.web.support.AppUtils;
53 import org.springframework.beans.factory.annotation.Autowired;
54 import org.springframework.stereotype.Controller;
55 import org.springframework.util.StopWatch;
56 import org.springframework.web.bind.annotation.RequestMapping;
57 import org.springframework.web.bind.annotation.RequestMethod;
58 import org.springframework.web.bind.annotation.ResponseBody;
59 import org.springframework.web.servlet.ModelAndView;
60 import org.springframework.web.util.WebUtils;
62 import com.fasterxml.jackson.databind.DeserializationFeature;
63 import com.fasterxml.jackson.databind.JsonNode;
64 import com.fasterxml.jackson.databind.ObjectMapper;
68 public class LoginController extends EPUnRestrictedBaseController implements LoginService{
70 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginController.class);
72 public static final String DEFAULT_SUCCESS_VIEW = "applicationsHome";
73 public static final String DEFAULT_FAILURE_VIEW = "login";
74 public static final String ERROR_MESSAGE_KEY = "error";
75 public static final String REDIRECT_URL = "redirectUrl";
78 EPProfileService service;
80 private EPLoginService loginService;
82 private SharedContextService sharedContextService;
85 private EPRoleService roleService;
87 String viewName = "login";
88 private String welcomeView;
90 public String getWelcomeView() {
94 public void setWelcomeView(String welcomeView) {
95 this.welcomeView = welcomeView;
98 @RequestMapping(value = {"/login.htm" }, method = RequestMethod.GET)
99 public ModelAndView login(HttpServletRequest request) {
100 Map<String, Object> model = new HashMap<String, Object>();
102 String authentication = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM);
106 if (authentication == null || authentication.equals("") || authentication.trim().equals("OIDC"))
107 loginPage = "openIdLogin";
109 loginPage = getViewName();
111 return new ModelAndView(loginPage,"model", model);
114 @SuppressWarnings("rawtypes")
115 @RequestMapping(value = {"/open_source/login" }, method = RequestMethod.POST)
116 public @ResponseBody String loginValidate(HttpServletRequest request, HttpServletResponse response) throws Exception{
118 ObjectMapper mapper = new ObjectMapper();
119 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
120 JsonNode root = mapper.readTree(request.getReader());
122 EPLoginBean commandBean = new EPLoginBean();
123 String loginId = root.get("loginId").textValue();
124 String password = root.get("password").textValue();
125 commandBean.setLoginId(loginId);
126 commandBean.setLoginPwd(CipherUtil.encrypt(password));
127 HashMap additionalParamsMap = new HashMap();
128 StringBuilder sbAdditionalInfo = new StringBuilder();
130 commandBean = getLoginService().findUser(commandBean, (String)request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY),
131 additionalParamsMap);
132 String fullURL = getFullURL(request);
133 if (commandBean.getUser() == null) {
134 String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) ? commandBean.getLoginErrorMessage()
135 : "login.error.external.invalid";
137 logger.info(EELFLoggerDelegate.debugLogger, "loginId = " + loginId + " does not exist in the the DB.");
138 logger.info(EELFLoggerDelegate.errorLogger, "loginId = " + loginId + " does not exist in the the DB.");
139 sbAdditionalInfo.append(String.format("But the Login-Id: %s doesn't exist in the Database. Request-URL: %s",
141 return loginErrorMessage;
144 // store the currently logged in user's information in the session
145 EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM),
146 roleService.getRoleFunctions());
149 logger.info(EELFLoggerDelegate.debugLogger, "******************* store user info into share context begins");
150 String sessionId = request.getSession().getId();
151 List<SharedContext> existingSC = getSharedContextService().getSharedContexts(sessionId);
152 if(existingSC==null || existingSC.size()==0){
153 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_FIRST_NAME, commandBean.getUser().getFirstName());
154 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_LAST_NAME, commandBean.getUser().getLastName());
155 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_EMAIL, commandBean.getUser().getEmail());
156 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_ORG_USERID, commandBean.getLoginId());
160 logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
161 logger.info(EELFLoggerDelegate.errorLogger, "failed the shared context adding process " + e.getMessage());
162 logger.info(EELFLoggerDelegate.debugLogger, "********************** failed the shared context adding process " + e.getMessage());
164 logger.info(EELFLoggerDelegate.debugLogger, "********************* PresetUp the EP service cookie and intial sessionManagement");
166 SessionCookieUtil.preSetUp(request, response);
167 SessionCookieUtil.setUpUserIdCookie(request, response, loginId);
169 JSONObject j = new JSONObject("{success: success}");
177 /* Work around a bug in ecompsdkos version 1.1.0 which hard-codes this endpoint. */
178 @RequestMapping(value = {"/process_csp" }, method = RequestMethod.GET)
179 public ModelAndView processCsp(HttpServletRequest request, HttpServletResponse response) throws Exception {
180 return processSingleSignOn(request, response);
182 /* Remove this method after epsdk-app-common/.../SingleSignOnController.java is repaired. */
184 @RequestMapping(value = {"/processSingleSignOn" }, method = RequestMethod.GET)
185 public ModelAndView processSingleSignOn(HttpServletRequest request, HttpServletResponse response) throws Exception{
187 Map<Object, Object> model = new HashMap<Object, Object>();
188 HashMap<Object, Object> additionalParamsMap = new HashMap<Object, Object>();
189 EPLoginBean commandBean = new EPLoginBean();
190 MDC.put(MDC_KEY_REQUEST_ID, getRequestId(request));
191 String orgUserId = "";
192 //get userId from cookie
193 orgUserId = SessionCookieUtil.getUserIdFromCookie(request, response);
194 logger.info(EELFLoggerDelegate.debugLogger, "******************** process_singelSignOn process begins");
195 logger.info(EELFLoggerDelegate.debugLogger, "******************* We get the orgUserId " + orgUserId);
197 StringBuilder sbAdditionalInfo = new StringBuilder();
198 if ((orgUserId == null || orgUserId.length() == 0)) {
199 model.put(ERROR_MESSAGE_KEY, SystemProperties.MESSAGE_KEY_LOGIN_ERROR_COOKIE_EMPTY);
200 if(request.getParameter("redirectUrl")!=null && request.getParameter("redirectUrl").length()!=0){
201 return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm" + "?redirectUrl=" + request.getParameter("redirectUrl"));
203 return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm");
208 StopWatch stopWatch = new StopWatch("LoginController.Login");
212 logger.info(EELFLoggerDelegate.metricsLogger, "Operation findUser is started to locate " + orgUserId + " in the database.");
213 logger.info(EELFLoggerDelegate.debugLogger, "Operation findUser is started to locate " + orgUserId + " in the database.");
214 commandBean.setLoginId(orgUserId);
215 commandBean.setOrgUserId(orgUserId);
216 commandBean = getLoginService().findUser(commandBean, (String)request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), additionalParamsMap);
219 MDC.put(EPSystemProperties.MDC_TIMER, stopWatch.getTotalTimeMillis() + "ms");
220 logger.info(EELFLoggerDelegate.metricsLogger, "Operation findUser is completed.");
221 logger.info(EELFLoggerDelegate.debugLogger, "Operation findUser is completed.");
222 } catch(Exception e) {
224 MDC.put(EPSystemProperties.MDC_TIMER, stopWatch.getTotalTimeMillis() + "ms");
225 logger.info(EELFLoggerDelegate.errorLogger, "Exception occurred while performing findUser " + orgUserId + ". Details: " + EcompPortalUtils.getStackTrace(e));
226 logger.info(EELFLoggerDelegate.debugLogger, "Exception occurred while performing findUser " + orgUserId + ". Details: " + EcompPortalUtils.getStackTrace(e));
227 logger.info(EELFLoggerDelegate.metricsLogger, "Operation findUser is failed.");
229 MDC.remove(EPSystemProperties.MDC_TIMER);
232 sbAdditionalInfo.append("Login attempt is succeeded. ");
233 String fullURL = getFullURL(request);
234 if (commandBean.getUser() == null) {
235 logger.info(EELFLoggerDelegate.debugLogger, "loginId = " + orgUserId + " does not exist in the the DB.");
236 logger.info(EELFLoggerDelegate.errorLogger, "loginId = " + orgUserId + " does not exist in the the DB.");
237 logger.info(EELFLoggerDelegate.debugLogger, "loginId = " + orgUserId + " does not exist in the the DB.");
239 sbAdditionalInfo.append(String.format("But the Login-Id: %s doesn't exist in the Database. Created a Guest Session. Request-URL: %s",
240 orgUserId, fullURL));
241 if(request.getParameter("redirectUrl")!=null && request.getParameter("redirectUrl").length()!=0){
242 return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm" + "?redirectUrl=" + request.getParameter("redirectUrl"));
244 return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm");
249 sbAdditionalInfo.append(String.format("Login-Id: %s, Login-Method: %s, Request-URL: %s", orgUserId, "", fullURL));
250 logger.info(EELFLoggerDelegate.debugLogger, "*********************** now set up user session for " + orgUserId);
252 EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM), roleService.getRoleFunctions());
253 logger.info(EELFLoggerDelegate.debugLogger, "*********************** now set up user session for " + orgUserId + " finished");
255 //Store user's information into share context
257 logger.info(EELFLoggerDelegate.debugLogger, "******************* store user info into share context begins");
259 String sessionId = request.getSession().getId();
260 List<SharedContext> existingSC = getSharedContextService().getSharedContexts(sessionId);
261 if(existingSC==null || existingSC.size()==0){
262 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_FIRST_NAME, commandBean.getUser().getFirstName());
263 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_LAST_NAME, commandBean.getUser().getLastName());
264 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_EMAIL, commandBean.getUser().getEmail());
265 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_ORG_USERID, commandBean.getLoginId());
269 logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
270 logger.info(EELFLoggerDelegate.errorLogger, "failed the shared context adding process " + e.getMessage());
271 logger.info(EELFLoggerDelegate.debugLogger, "********************** failed the shared context adding process " + e.getMessage());
275 logger.info(EELFLoggerDelegate.debugLogger, "********************* PresetUp the EP service cookie and intial sessionManagement");
277 SessionCookieUtil.preSetUp(request, response);
278 SessionCookieUtil.setUpUserIdCookie(request, response, orgUserId);
279 logger.info(EELFLoggerDelegate.debugLogger, "********************* PresetUp the EP service cookie and intial sessionManagement completed");
280 logger.info(EELFLoggerDelegate.errorLogger, commandBean.getUser().getOrgUserId() + " exists in the the system.");
281 logger.info(EELFLoggerDelegate.debugLogger, commandBean.getUser().getOrgUserId() + " exists in the the system.");
283 String redirect = "redirectUrl";
285 //get redirectUrl from URL parameter
286 if(request.getParameter(redirect)!=null && request.getParameter(redirect).length()!=0){
287 String forwardUrl = URLDecoder.decode(request.getParameter(redirect),"UTF-8");
289 Cookie cookie2 = new Cookie(redirect, "");
290 cookie2.setMaxAge(0);
291 cookie2.setDomain(EPSystemProperties.getProperty(EPSystemProperties.COOKIE_DOMAIN));
292 cookie2.setPath("/");
293 response.addCookie(cookie2);
294 return new ModelAndView("redirect:" + forwardUrl);
297 //first check if redirectUrl exists or not
298 if(WebUtils.getCookie(request, redirect)!=null){
299 String forwardUrl = WebUtils.getCookie(request, redirect).getValue();
301 Cookie cookie2 = new Cookie(redirect, "");
302 cookie2.setMaxAge(0);
303 cookie2.setDomain(EPSystemProperties.getProperty(EPSystemProperties.COOKIE_DOMAIN));
304 cookie2.setPath("/");
305 response.addCookie(cookie2);
307 return new ModelAndView("redirect:" + forwardUrl);
312 // if user has been authenticated, now take them to the welcome page.
313 //return new ModelAndView("redirect:" + DEFAULT_SUCCESS_VIEW + ".htm");
314 logger.info(EELFLoggerDelegate.debugLogger, "********************** Now return to application home page");
316 return new ModelAndView("redirect:" + SystemProperties.getProperty(EPSystemProperties.FE_URL));
319 // Re-enable for BE/FE separation. For 1607, at last minute we decided to go out
320 // without BE/FE separation.
322 //return new ModelAndView("redirect:" + SystemProperties.getProperty(EPSystemProperties.FE_URL));
326 public String getFullURL(HttpServletRequest request) {
327 if (request != null) {
328 StringBuffer requestURL = request.getRequestURL();
329 String queryString = request.getQueryString();
331 if (queryString == null) {
332 return requestURL.toString();
334 return requestURL.append('?').append(queryString).toString();
340 public String getRequestId(HttpServletRequest request) {
341 Enumeration<String> headerNames = request.getHeaderNames();
343 String requestId = "";
345 while (headerNames.hasMoreElements()) {
346 String headerName = (String) headerNames.nextElement();
347 logger.debug(EELFLoggerDelegate.debugLogger,
348 "One header is " + headerName + " : " + request.getHeader(headerName));
349 if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) {
350 requestId = request.getHeader(headerName);
354 } catch (Exception e) {
355 logger.error(EELFLoggerDelegate.errorLogger, "HEADER!!!! Exception : " + EcompPortalUtils.getStackTrace(e));
358 return (requestId.isEmpty() ? UUID.randomUUID().toString() : requestId);
361 public String getJessionId(HttpServletRequest request){
363 return request.getSession().getId();
365 Cookie ep = WebUtils.getCookie(request, JSESSIONID);
367 return request.getSession().getId();
369 return ep.getValue();
374 protected void initateSessionMgtHandler(HttpServletRequest request) {
375 String jSessionId = getJessionId(request);
376 PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request));
380 public String getViewName() {
383 public void setViewName(String viewName) {
384 this.viewName = viewName;
386 public EPLoginService getLoginService() {
390 public void setLoginService(EPLoginService loginService) {
391 this.loginService = loginService;
394 public SharedContextService getSharedContextService() {
395 return sharedContextService;
398 public void setSharedContextService(SharedContextService sharedContextService) {
399 this.sharedContextService = sharedContextService;