33cc4dd7704091fdfbebd4d99798d0ec80cf332d
[portal.git] / ecomp-portal-BE-os / src / main / java / org / openecomp / portalapp / controller / LoginController.java
1 /*-
2  * ================================================================================
3  * ECOMP Portal
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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  * ================================================================================
19  */
20 package org.openecomp.portalapp.controller;
21
22 import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
23
24 import java.net.URLDecoder;
25 import java.util.Enumeration;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.UUID;
30
31 import javax.servlet.http.Cookie;
32 import javax.servlet.http.HttpServletRequest;
33 import javax.servlet.http.HttpServletResponse;
34
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;
53 import org.slf4j.MDC;
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;
62
63 import com.fasterxml.jackson.databind.DeserializationFeature;
64 import com.fasterxml.jackson.databind.JsonNode;
65 import com.fasterxml.jackson.databind.ObjectMapper;
66
67 @Controller
68 @RequestMapping("/")
69 public class LoginController extends EPUnRestrictedBaseController implements LoginService{
70         
71         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginController.class);
72         
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";
77         
78         @Autowired
79         EPProfileService service;
80         @Autowired
81         private EPLoginService loginService;
82         @Autowired
83         private SharedContextService sharedContextService;
84         
85         @Autowired
86         private EPRoleService roleService;
87         
88         @Autowired
89         private EPRoleFunctionService ePRoleFunctionService;
90         
91         String viewName = "login";
92         private String welcomeView;
93
94     public String getWelcomeView() {
95         return welcomeView;
96     }
97
98     public void setWelcomeView(String welcomeView) {
99         this.welcomeView = welcomeView;
100     }
101     
102         @RequestMapping(value = {"/login.htm" }, method = RequestMethod.GET)
103         public ModelAndView login(HttpServletRequest request) {
104                 Map<String, Object> model = new HashMap<String, Object>();
105                 
106                 String authentication = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM);
107                 
108                 String loginPage;
109                 
110                 if (authentication == null || authentication.equals("") || authentication.trim().equals("OIDC"))                                
111                         loginPage = "openIdLogin";
112                 else
113                         loginPage =  getViewName();
114                 
115                 return new ModelAndView(loginPage,"model", model);
116         }
117         
118         @SuppressWarnings("rawtypes")
119         @RequestMapping(value = {"/open_source/login" }, method = RequestMethod.POST)
120         public @ResponseBody String loginValidate(HttpServletRequest request, HttpServletResponse response) throws Exception{
121                 
122                 ObjectMapper mapper = new ObjectMapper();
123                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
124                 JsonNode root = mapper.readTree(request.getReader());
125                 
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();
133               
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";
140
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", 
144                                         loginId, fullURL));
145                         return loginErrorMessage;
146               }
147               else {
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);
150                 
151                 try{
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());
160                         }
161                             
162                     }catch(Exception e){
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());
166                     }
167                         logger.info(EELFLoggerDelegate.debugLogger, "********************* PresetUp the EP service cookie and intial sessionManagement");
168
169                     SessionCookieUtil.preSetUp(request, response); 
170                     SessionCookieUtil.setUpUserIdCookie(request, response, loginId);
171   
172                     JSONObject j = new JSONObject("{success: success}");
173                
174                 return j.toString();
175                
176               }
177         
178         }
179         
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);
184         }
185         /* Remove this method after epsdk-app-common/.../SingleSignOnController.java is repaired. */
186
187         @RequestMapping(value = {"/processSingleSignOn" }, method = RequestMethod.GET)
188         public ModelAndView processSingleSignOn(HttpServletRequest request, HttpServletResponse response) throws Exception{
189                 
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);
199
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"));
205                         }else{
206                                  return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm");
207                         }
208                 }
209                 else {
210                         
211                         StopWatch stopWatch = new StopWatch("LoginController.Login");
212                         stopWatch.start();
213                                                 
214                         try {
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);
220                                 
221                                 stopWatch.stop();
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) {
226                                 stopWatch.stop();
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.");
231                         } finally {
232                                 MDC.remove(EPSystemProperties.MDC_TIMER);
233                         }
234                         
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.");
241
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"));
246                                 }else{
247                                          return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm");
248                                 }
249                         }
250                         else {
251                     
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);
254
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");
257
258                             //Store user's information into share context       
259                             try{
260                                         logger.info(EELFLoggerDelegate.debugLogger, "******************* store user info into share context begins");
261
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());
269                                 }
270                                     
271                             }catch(Exception e){
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());
275
276                             }
277                             
278                                 logger.info(EELFLoggerDelegate.debugLogger, "********************* PresetUp the EP service cookie and intial sessionManagement");
279
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.");
285
286                             String redirect = "redirectUrl";
287                             
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");
291                                 //clean cookie
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);
298                             }
299                             
300                             //first check if redirectUrl exists or not
301                                 if(WebUtils.getCookie(request, redirect)!=null){
302                                 String forwardUrl = WebUtils.getCookie(request, redirect).getValue();
303                                 //clean cookie
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);               
309                                 
310                                 return new ModelAndView("redirect:" + forwardUrl);
311                         }
312                         }
313                 }
314                 
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");
318
319                 return new ModelAndView("redirect:" + SystemProperties.getProperty(EPSystemProperties.FE_URL));
320                 
321                 //
322                 // Re-enable for BE/FE separation.  For 1607, at last minute we decided to go out
323                 // without BE/FE separation.
324                 //
325                 //return new ModelAndView("redirect:" + SystemProperties.getProperty(EPSystemProperties.FE_URL));
326                 
327         }
328         
329         public String getFullURL(HttpServletRequest request) {
330                 if (request != null) {
331                         StringBuffer requestURL = request.getRequestURL();
332                         String queryString = request.getQueryString();
333
334                         if (queryString == null) {
335                                 return requestURL.toString();
336                         } else {
337                                 return requestURL.append('?').append(queryString).toString();
338                         }
339                 }
340                 return "";
341         }
342         
343         public String getRequestId(HttpServletRequest request) {
344                 Enumeration<String> headerNames = request.getHeaderNames();
345
346                 String requestId = "";
347                 try {
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);
354                                         break;
355                                 }
356                         }
357                 } catch (Exception e) {
358                         logger.error(EELFLoggerDelegate.errorLogger, "HEADER!!!! Exception : " + EcompPortalUtils.getStackTrace(e));
359                 }
360
361                 return (requestId.isEmpty() ? UUID.randomUUID().toString() : requestId);
362         }
363         
364     public String getJessionId(HttpServletRequest request){
365                 
366                 return request.getSession().getId();
367                 /*
368                 Cookie ep = WebUtils.getCookie(request, JSESSIONID);
369                 if(ep==null){
370                         return request.getSession().getId();
371                 }
372                 return ep.getValue();
373                 */
374         }
375         
376         
377         protected void initateSessionMgtHandler(HttpServletRequest request) {
378                 String jSessionId = getJessionId(request);
379                 PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request));
380         }
381         
382
383         public String getViewName() {
384                 return viewName;
385         }
386         public void setViewName(String viewName) {
387                 this.viewName = viewName;
388         }
389         public EPLoginService getLoginService() {
390         return loginService;
391     }
392
393     public void setLoginService(EPLoginService loginService) {
394         this.loginService = loginService;
395     }
396
397         public SharedContextService getSharedContextService() {
398                 return sharedContextService;
399         }
400
401         public void setSharedContextService(SharedContextService sharedContextService) {
402                 this.sharedContextService = sharedContextService;
403         }
404     
405
406
407 }