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.EPRoleFunctionService;
40 import org.openecomp.portalapp.portal.service.EPRoleService;
41 import org.openecomp.portalapp.portal.service.SharedContextService;
42 import org.openecomp.portalapp.portal.utils.EPSystemProperties;
43 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
44 import org.openecomp.portalapp.service.EPProfileService;
45 import org.openecomp.portalapp.util.EPUserUtils;
46 import org.openecomp.portalapp.util.SessionCookieUtil;
47 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
48 import org.openecomp.portalsdk.core.menu.MenuProperties;
49 import org.openecomp.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
50 import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
51 import org.openecomp.portalsdk.core.util.SystemProperties;
52 import org.openecomp.portalsdk.core.web.support.AppUtils;
54 import org.springframework.beans.factory.annotation.Autowired;
55 import org.springframework.stereotype.Controller;
56 import org.springframework.util.StopWatch;
57 import org.springframework.web.bind.annotation.RequestMapping;
58 import org.springframework.web.bind.annotation.RequestMethod;
59 import org.springframework.web.bind.annotation.ResponseBody;
60 import org.springframework.web.servlet.ModelAndView;
61 import org.springframework.web.util.WebUtils;
63 import com.fasterxml.jackson.databind.DeserializationFeature;
64 import com.fasterxml.jackson.databind.JsonNode;
65 import com.fasterxml.jackson.databind.ObjectMapper;
69 public class LoginController extends EPUnRestrictedBaseController implements LoginService{
71 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginController.class);
73 public static final String DEFAULT_SUCCESS_VIEW = "applicationsHome";
74 public static final String DEFAULT_FAILURE_VIEW = "login";
75 public static final String ERROR_MESSAGE_KEY = "error";
76 public static final String REDIRECT_URL = "redirectUrl";
79 EPProfileService service;
81 private EPLoginService loginService;
83 private SharedContextService sharedContextService;
86 private EPRoleService roleService;
89 private EPRoleFunctionService ePRoleFunctionService;
91 String viewName = "login";
92 private String welcomeView;
94 public String getWelcomeView() {
98 public void setWelcomeView(String welcomeView) {
99 this.welcomeView = welcomeView;
102 @RequestMapping(value = {"/login.htm" }, method = RequestMethod.GET)
103 public ModelAndView login(HttpServletRequest request) {
104 Map<String, Object> model = new HashMap<String, Object>();
106 String authentication = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM);
110 if (authentication == null || authentication.equals("") || authentication.trim().equals("OIDC"))
111 loginPage = "openIdLogin";
113 loginPage = getViewName();
115 return new ModelAndView(loginPage,"model", model);
118 @SuppressWarnings("rawtypes")
119 @RequestMapping(value = {"/open_source/login" }, method = RequestMethod.POST)
120 public @ResponseBody String loginValidate(HttpServletRequest request, HttpServletResponse response) throws Exception{
122 ObjectMapper mapper = new ObjectMapper();
123 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
124 JsonNode root = mapper.readTree(request.getReader());
126 EPLoginBean commandBean = new EPLoginBean();
127 String loginId = root.get("loginId").textValue();
128 String password = root.get("password").textValue();
129 commandBean.setLoginId(loginId);
130 commandBean.setLoginPwd(CipherUtil.encrypt(password));
131 HashMap additionalParamsMap = new HashMap();
132 StringBuilder sbAdditionalInfo = new StringBuilder();
134 commandBean = getLoginService().findUser(commandBean, (String)request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY),
135 additionalParamsMap);
136 String fullURL = getFullURL(request);
137 if (commandBean.getUser() == null) {
138 String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) ? commandBean.getLoginErrorMessage()
139 : "login.error.external.invalid";
141 logger.info(EELFLoggerDelegate.debugLogger, "loginId = " + loginId + " does not exist in the the DB.");
142 logger.info(EELFLoggerDelegate.errorLogger, "loginId = " + loginId + " does not exist in the the DB.");
143 sbAdditionalInfo.append(String.format("But the Login-Id: %s doesn't exist in the Database. Request-URL: %s",
145 return loginErrorMessage;
148 // store the currently logged in user's information in the session
149 EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM),ePRoleFunctionService);
152 logger.info(EELFLoggerDelegate.debugLogger, "******************* store user info into share context begins");
153 String sessionId = request.getSession().getId();
154 List<SharedContext> existingSC = getSharedContextService().getSharedContexts(sessionId);
155 if(existingSC==null || existingSC.size()==0){
156 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_FIRST_NAME, commandBean.getUser().getFirstName());
157 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_LAST_NAME, commandBean.getUser().getLastName());
158 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_EMAIL, commandBean.getUser().getEmail());
159 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_ORG_USERID, commandBean.getLoginId());
163 logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
164 logger.info(EELFLoggerDelegate.errorLogger, "failed the shared context adding process " + e.getMessage());
165 logger.info(EELFLoggerDelegate.debugLogger, "********************** failed the shared context adding process " + e.getMessage());
167 logger.info(EELFLoggerDelegate.debugLogger, "********************* PresetUp the EP service cookie and intial sessionManagement");
169 SessionCookieUtil.preSetUp(request, response);
170 SessionCookieUtil.setUpUserIdCookie(request, response, loginId);
172 JSONObject j = new JSONObject("{success: success}");
180 /* Work around a bug in ecompsdkos version 1.1.0 which hard-codes this endpoint. */
181 @RequestMapping(value = {"/process_csp" }, method = RequestMethod.GET)
182 public ModelAndView processCsp(HttpServletRequest request, HttpServletResponse response) throws Exception {
183 return processSingleSignOn(request, response);
185 /* Remove this method after epsdk-app-common/.../SingleSignOnController.java is repaired. */
187 @RequestMapping(value = {"/processSingleSignOn" }, method = RequestMethod.GET)
188 public ModelAndView processSingleSignOn(HttpServletRequest request, HttpServletResponse response) throws Exception{
190 Map<Object, Object> model = new HashMap<Object, Object>();
191 HashMap<Object, Object> additionalParamsMap = new HashMap<Object, Object>();
192 EPLoginBean commandBean = new EPLoginBean();
193 MDC.put(MDC_KEY_REQUEST_ID, getRequestId(request));
194 String orgUserId = "";
195 //get userId from cookie
196 orgUserId = SessionCookieUtil.getUserIdFromCookie(request, response);
197 logger.info(EELFLoggerDelegate.debugLogger, "******************** process_singelSignOn process begins");
198 logger.info(EELFLoggerDelegate.debugLogger, "******************* We get the orgUserId " + orgUserId);
200 StringBuilder sbAdditionalInfo = new StringBuilder();
201 if ((orgUserId == null || orgUserId.length() == 0)) {
202 model.put(ERROR_MESSAGE_KEY, SystemProperties.MESSAGE_KEY_LOGIN_ERROR_COOKIE_EMPTY);
203 if(request.getParameter("redirectUrl")!=null && request.getParameter("redirectUrl").length()!=0){
204 return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm" + "?redirectUrl=" + request.getParameter("redirectUrl"));
206 return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm");
211 StopWatch stopWatch = new StopWatch("LoginController.Login");
215 logger.info(EELFLoggerDelegate.metricsLogger, "Operation findUser is started to locate " + orgUserId + " in the database.");
216 logger.info(EELFLoggerDelegate.debugLogger, "Operation findUser is started to locate " + orgUserId + " in the database.");
217 commandBean.setLoginId(orgUserId);
218 commandBean.setOrgUserId(orgUserId);
219 commandBean = getLoginService().findUser(commandBean, (String)request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), additionalParamsMap);
222 MDC.put(EPSystemProperties.MDC_TIMER, stopWatch.getTotalTimeMillis() + "ms");
223 logger.info(EELFLoggerDelegate.metricsLogger, "Operation findUser is completed.");
224 logger.info(EELFLoggerDelegate.debugLogger, "Operation findUser is completed.");
225 } catch(Exception e) {
227 MDC.put(EPSystemProperties.MDC_TIMER, stopWatch.getTotalTimeMillis() + "ms");
228 logger.info(EELFLoggerDelegate.errorLogger, "Exception occurred while performing findUser " + orgUserId + ". Details: " + EcompPortalUtils.getStackTrace(e));
229 logger.info(EELFLoggerDelegate.debugLogger, "Exception occurred while performing findUser " + orgUserId + ". Details: " + EcompPortalUtils.getStackTrace(e));
230 logger.info(EELFLoggerDelegate.metricsLogger, "Operation findUser is failed.");
232 MDC.remove(EPSystemProperties.MDC_TIMER);
235 sbAdditionalInfo.append("Login attempt is succeeded. ");
236 String fullURL = getFullURL(request);
237 if (commandBean.getUser() == null) {
238 logger.info(EELFLoggerDelegate.debugLogger, "loginId = " + orgUserId + " does not exist in the the DB.");
239 logger.info(EELFLoggerDelegate.errorLogger, "loginId = " + orgUserId + " does not exist in the the DB.");
240 logger.info(EELFLoggerDelegate.debugLogger, "loginId = " + orgUserId + " does not exist in the the DB.");
242 sbAdditionalInfo.append(String.format("But the Login-Id: %s doesn't exist in the Database. Created a Guest Session. Request-URL: %s",
243 orgUserId, fullURL));
244 if(request.getParameter("redirectUrl")!=null && request.getParameter("redirectUrl").length()!=0){
245 return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm" + "?redirectUrl=" + request.getParameter("redirectUrl"));
247 return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm");
252 sbAdditionalInfo.append(String.format("Login-Id: %s, Login-Method: %s, Request-URL: %s", orgUserId, "", fullURL));
253 logger.info(EELFLoggerDelegate.debugLogger, "*********************** now set up user session for " + orgUserId);
255 EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM),ePRoleFunctionService);
256 logger.info(EELFLoggerDelegate.debugLogger, "*********************** now set up user session for " + orgUserId + " finished");
258 //Store user's information into share context
260 logger.info(EELFLoggerDelegate.debugLogger, "******************* store user info into share context begins");
262 String sessionId = request.getSession().getId();
263 List<SharedContext> existingSC = getSharedContextService().getSharedContexts(sessionId);
264 if(existingSC==null || existingSC.size()==0){
265 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_FIRST_NAME, commandBean.getUser().getFirstName());
266 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_LAST_NAME, commandBean.getUser().getLastName());
267 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_EMAIL, commandBean.getUser().getEmail());
268 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_ORG_USERID, commandBean.getLoginId());
272 logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
273 logger.info(EELFLoggerDelegate.errorLogger, "failed the shared context adding process " + e.getMessage());
274 logger.info(EELFLoggerDelegate.debugLogger, "********************** failed the shared context adding process " + e.getMessage());
278 logger.info(EELFLoggerDelegate.debugLogger, "********************* PresetUp the EP service cookie and intial sessionManagement");
280 SessionCookieUtil.preSetUp(request, response);
281 SessionCookieUtil.setUpUserIdCookie(request, response, orgUserId);
282 logger.info(EELFLoggerDelegate.debugLogger, "********************* PresetUp the EP service cookie and intial sessionManagement completed");
283 logger.info(EELFLoggerDelegate.errorLogger, commandBean.getUser().getOrgUserId() + " exists in the the system.");
284 logger.info(EELFLoggerDelegate.debugLogger, commandBean.getUser().getOrgUserId() + " exists in the the system.");
286 String redirect = "redirectUrl";
288 //get redirectUrl from URL parameter
289 if(request.getParameter(redirect)!=null && request.getParameter(redirect).length()!=0){
290 String forwardUrl = URLDecoder.decode(request.getParameter(redirect),"UTF-8");
292 Cookie cookie2 = new Cookie(redirect, "");
293 cookie2.setMaxAge(0);
294 cookie2.setDomain(EPSystemProperties.getProperty(EPSystemProperties.COOKIE_DOMAIN));
295 cookie2.setPath("/");
296 response.addCookie(cookie2);
297 return new ModelAndView("redirect:" + forwardUrl);
300 //first check if redirectUrl exists or not
301 if(WebUtils.getCookie(request, redirect)!=null){
302 String forwardUrl = WebUtils.getCookie(request, redirect).getValue();
304 Cookie cookie2 = new Cookie(redirect, "");
305 cookie2.setMaxAge(0);
306 cookie2.setDomain(EPSystemProperties.getProperty(EPSystemProperties.COOKIE_DOMAIN));
307 cookie2.setPath("/");
308 response.addCookie(cookie2);
310 return new ModelAndView("redirect:" + forwardUrl);
315 // if user has been authenticated, now take them to the welcome page.
316 //return new ModelAndView("redirect:" + DEFAULT_SUCCESS_VIEW + ".htm");
317 logger.info(EELFLoggerDelegate.debugLogger, "********************** Now return to application home page");
319 return new ModelAndView("redirect:" + SystemProperties.getProperty(EPSystemProperties.FE_URL));
322 // Re-enable for BE/FE separation. For 1607, at last minute we decided to go out
323 // without BE/FE separation.
325 //return new ModelAndView("redirect:" + SystemProperties.getProperty(EPSystemProperties.FE_URL));
329 public String getFullURL(HttpServletRequest request) {
330 if (request != null) {
331 StringBuffer requestURL = request.getRequestURL();
332 String queryString = request.getQueryString();
334 if (queryString == null) {
335 return requestURL.toString();
337 return requestURL.append('?').append(queryString).toString();
343 public String getRequestId(HttpServletRequest request) {
344 Enumeration<String> headerNames = request.getHeaderNames();
346 String requestId = "";
348 while (headerNames.hasMoreElements()) {
349 String headerName = (String) headerNames.nextElement();
350 logger.debug(EELFLoggerDelegate.debugLogger,
351 "One header is " + headerName + " : " + request.getHeader(headerName));
352 if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) {
353 requestId = request.getHeader(headerName);
357 } catch (Exception e) {
358 logger.error(EELFLoggerDelegate.errorLogger, "HEADER!!!! Exception : " + EcompPortalUtils.getStackTrace(e));
361 return (requestId.isEmpty() ? UUID.randomUUID().toString() : requestId);
364 public String getJessionId(HttpServletRequest request){
366 return request.getSession().getId();
368 Cookie ep = WebUtils.getCookie(request, JSESSIONID);
370 return request.getSession().getId();
372 return ep.getValue();
377 protected void initateSessionMgtHandler(HttpServletRequest request) {
378 String jSessionId = getJessionId(request);
379 PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request));
383 public String getViewName() {
386 public void setViewName(String viewName) {
387 this.viewName = viewName;
389 public EPLoginService getLoginService() {
393 public void setLoginService(EPLoginService loginService) {
394 this.loginService = loginService;
397 public SharedContextService getSharedContextService() {
398 return sharedContextService;
401 public void setSharedContextService(SharedContextService sharedContextService) {
402 this.sharedContextService = sharedContextService;