nexus site path corrected
[portal.git] / ecomp-portal-BE / 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.HashMap;
26 import java.util.List;
27 import java.util.Map;
28
29 import javax.servlet.http.Cookie;
30 import javax.servlet.http.HttpServletRequest;
31 import javax.servlet.http.HttpServletResponse;
32
33 import org.json.JSONObject;
34 import org.openecomp.portalapp.command.EPLoginBean;
35 import org.openecomp.portalapp.portal.domain.SharedContext;
36 import org.openecomp.portalapp.portal.service.EPLoginService;
37 import org.openecomp.portalapp.portal.service.SharedContextService;
38 import org.openecomp.portalapp.portal.utils.EPSystemProperties;
39 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
40 import org.openecomp.portalapp.service.EPProfileService;
41 import org.openecomp.portalapp.util.EPUserUtils;
42 import org.openecomp.portalapp.util.SessionCookieUtil;
43 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
44 import org.openecomp.portalsdk.core.menu.MenuProperties;
45 import org.openecomp.portalsdk.core.onboarding.crossapi.PortalTimeoutHandler;
46 import org.openecomp.portalsdk.core.util.CipherUtil;
47 import org.openecomp.portalsdk.core.util.SystemProperties;
48 import org.openecomp.portalsdk.core.web.support.AppUtils;
49 import org.slf4j.MDC;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.stereotype.Controller;
52 import org.springframework.util.StopWatch;
53 import org.springframework.web.bind.annotation.RequestMapping;
54 import org.springframework.web.bind.annotation.RequestMethod;
55 import org.springframework.web.bind.annotation.ResponseBody;
56 import org.springframework.web.servlet.ModelAndView;
57 import org.springframework.web.util.WebUtils;
58
59 import com.fasterxml.jackson.databind.DeserializationFeature;
60 import com.fasterxml.jackson.databind.JsonNode;
61 import com.fasterxml.jackson.databind.ObjectMapper;
62
63 @Controller
64 @RequestMapping("/")
65 public class LoginController extends EPUnRestrictedBaseController implements LoginService{
66         
67         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginController.class);
68         
69         public static final String DEFAULT_SUCCESS_VIEW = "applicationsHome";
70         public static final String DEFAULT_FAILURE_VIEW = "login";
71         public static final String ERROR_MESSAGE_KEY    = "error";
72         public static final String REDIRECT_URL = "redirectUrl";
73         
74         @Autowired
75         EPProfileService service;
76         @Autowired
77         private EPLoginService loginService;
78         @Autowired
79         private SharedContextService sharedContextService;
80         
81         String viewName = "login";
82         private String welcomeView;
83
84     public String getWelcomeView() {
85         return welcomeView;
86     }
87
88     public void setWelcomeView(String welcomeView) {
89         this.welcomeView = welcomeView;
90     }
91     
92         @RequestMapping(value = {"/login.htm" }, method = RequestMethod.GET)
93         public ModelAndView login(HttpServletRequest request, HttpServletResponse response) {
94                 Map<String, Object> model = new HashMap<String, Object>();
95                 
96                 String authentication = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM);
97                 
98                 String loginPage;
99                 
100                 if (authentication == null || authentication.equals("") || authentication.trim().equals("OIDC"))                                
101                         loginPage = "openIdLogin";
102                 else
103                         loginPage =  getViewName();
104                 
105                 return new ModelAndView(loginPage,"model", model);
106         }
107         
108         @SuppressWarnings("rawtypes")
109         @RequestMapping(value = {"/open_source/login" }, method = RequestMethod.POST)
110         public @ResponseBody String loginValidate(HttpServletRequest request, HttpServletResponse response) throws Exception{
111                 
112                 ObjectMapper mapper = new ObjectMapper();
113                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
114                 JsonNode root = mapper.readTree(request.getReader());
115                 
116               EPLoginBean commandBean = new EPLoginBean();
117               String        loginId = root.get("loginId").textValue(); 
118               String        password = root.get("password").textValue();
119               commandBean.setLoginId(loginId);
120               commandBean.setLoginPwd(CipherUtil.encrypt(password));
121               HashMap additionalParamsMap = new HashMap();
122               StringBuilder sbAdditionalInfo = new StringBuilder();
123               
124               commandBean = getLoginService().findUser(commandBean, (String)request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), 
125                           additionalParamsMap);
126               String fullURL = EPUserUtils.getFullURL(request);
127               if (commandBean.getUser() == null) {
128                 String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) ? commandBean.getLoginErrorMessage() 
129                                 : "login.error.external.invalid";
130
131                         logger.info(EELFLoggerDelegate.debugLogger, "loginId = " + loginId + " does not exist in the the DB.");
132                         logger.info(EELFLoggerDelegate.errorLogger, "loginId = " + loginId + " does not exist in the the DB.");
133                         sbAdditionalInfo.append(String.format("But the Login-Id: %s doesn't exist in the Database. Request-URL: %s", 
134                                         loginId, fullURL));
135                         return loginErrorMessage;
136               }
137               else {
138                 // store the currently logged in user's information in the session
139                 EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), 
140                                 null);
141                 
142                 try{
143                         logger.info(EELFLoggerDelegate.debugLogger, "******************* store user info into share context begins");
144                         String sessionId = request.getSession().getId();                                
145                         List<SharedContext> existingSC = getSharedContextService().getSharedContexts(sessionId);
146                         if(existingSC==null || existingSC.size()==0){
147                                 getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_FIRST_NAME, commandBean.getUser().getFirstName());
148                                     getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_LAST_NAME, commandBean.getUser().getLastName());
149                                     getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_EMAIL, commandBean.getUser().getEmail());
150                                     getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_ORG_USERID, commandBean.getLoginId());
151                         }
152                             
153                     }catch(Exception e){
154                         logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
155                                 logger.info(EELFLoggerDelegate.errorLogger, "failed the shared context adding process " + e.getMessage());
156                                 logger.info(EELFLoggerDelegate.debugLogger, "********************** failed the shared context adding process " + e.getMessage());
157                     }
158                         logger.info(EELFLoggerDelegate.debugLogger, "********************* PresetUp the EP service cookie and intial sessionManagement");
159
160                     SessionCookieUtil.preSetUp(request, response); 
161                     SessionCookieUtil.setUpUserIdCookie(request, response, loginId);
162   
163                     JSONObject j = new JSONObject("{success: success}");
164                     
165                 return j.toString();
166                
167               }
168         
169         }
170         
171         @RequestMapping(value = {"/processSingleSignOn" }, method = RequestMethod.GET)
172         public ModelAndView processSingelSignOn(HttpServletRequest request, HttpServletResponse response) throws Exception{
173                 
174                 Map<Object, Object>             model = new HashMap<Object, Object>();
175                 HashMap<Object, Object> additionalParamsMap = new HashMap<Object, Object>();
176                 EPLoginBean commandBean = new EPLoginBean();
177                 MDC.put(MDC_KEY_REQUEST_ID, EPUserUtils.getRequestId(request));
178                 String  orgUserId = "";
179                 //get userId from cookie
180                 orgUserId = SessionCookieUtil.getUserIdFromCookie(request, response);
181                 logger.info(EELFLoggerDelegate.debugLogger, "******************** process_singelSignOn process begins");
182                 logger.info(EELFLoggerDelegate.debugLogger, "******************* We get the orgUserId " + orgUserId);
183
184                 StringBuilder sbAdditionalInfo = new StringBuilder();
185                 if ((orgUserId == null || orgUserId.length() == 0)) {
186                         model.put(ERROR_MESSAGE_KEY, SystemProperties.MESSAGE_KEY_LOGIN_ERROR_COOKIE_EMPTY);
187                         if(request.getParameter("redirectUrl")!=null && request.getParameter("redirectUrl").length()!=0){
188                              return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm" + "?redirectUrl=" + request.getParameter("redirectUrl"));
189                         }else{
190                                  return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm");
191                         }
192                 }
193                 else {
194                         
195                         StopWatch stopWatch = new StopWatch("LoginController.Login");
196                         stopWatch.start();
197                                                 
198                         try {
199                                 logger.info(EELFLoggerDelegate.metricsLogger, "Operation findUser is started to locate " + orgUserId + " in the database.");
200                                 logger.info(EELFLoggerDelegate.debugLogger, "Operation findUser is started to locate " + orgUserId + " in the database.");
201                                 commandBean.setLoginId(orgUserId);
202                                 commandBean.setOrgUserId(orgUserId);
203                                 commandBean = getLoginService().findUserWithoutPassword(commandBean, (String)request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), additionalParamsMap);
204                                 
205                                 stopWatch.stop();
206                                 MDC.put(EPSystemProperties.MDC_TIMER, stopWatch.getTotalTimeMillis() + "ms");
207                                 logger.info(EELFLoggerDelegate.metricsLogger, "Operation findUser is completed.");
208                                 logger.info(EELFLoggerDelegate.debugLogger, "Operation findUser is completed.");
209                         } catch(Exception e) {
210                                 stopWatch.stop();
211                                 MDC.put(EPSystemProperties.MDC_TIMER, stopWatch.getTotalTimeMillis() + "ms");
212                                 logger.info(EELFLoggerDelegate.errorLogger, "Exception occurred while performing findUser " + orgUserId + ". Details: " + EcompPortalUtils.getStackTrace(e));
213                                 logger.info(EELFLoggerDelegate.debugLogger, "Exception occurred while performing findUser " + orgUserId + ". Details: " + EcompPortalUtils.getStackTrace(e));
214                                 logger.info(EELFLoggerDelegate.metricsLogger, "Operation findUser is failed.");
215                         } finally {
216                                 MDC.remove(EPSystemProperties.MDC_TIMER);
217                         }
218                         
219                         sbAdditionalInfo.append("Login attempt is succeeded. ");
220                         String fullURL = EPUserUtils.getFullURL(request);
221                         if (commandBean.getUser() == null) {
222                                 logger.info(EELFLoggerDelegate.debugLogger, "loginId = " + orgUserId + " does not exist in the the DB.");
223                                 logger.info(EELFLoggerDelegate.errorLogger, "loginId = " + orgUserId + " does not exist in the the DB.");
224                                 logger.info(EELFLoggerDelegate.debugLogger, "loginId = " + orgUserId + " does not exist in the the DB.");
225
226                                 sbAdditionalInfo.append(String.format("But the Login-Id: %s doesn't exist in the Database. Created a Guest Session. Request-URL: %s", 
227                                                 orgUserId, fullURL));
228                                 if(request.getParameter("redirectUrl")!=null && request.getParameter("redirectUrl").length()!=0){
229                                      return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm" + "?redirectUrl=" + request.getParameter("redirectUrl"));
230                                 }else{
231                                          return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm");
232                                 }
233                         }
234                         else {
235                     
236                             sbAdditionalInfo.append(String.format("Login-Id: %s, Login-Method: %s, Request-URL: %s", orgUserId, "", fullURL));
237                                 logger.info(EELFLoggerDelegate.debugLogger, "*********************** now set up user session for " + orgUserId);
238
239                             EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), "");
240                                 logger.info(EELFLoggerDelegate.debugLogger, "*********************** now set up user session for " + orgUserId + " finished");
241
242                             //Store user's information into share context       
243                             try{
244                                         logger.info(EELFLoggerDelegate.debugLogger, "******************* store user info into share context begins");
245
246                                 String sessionId = request.getSession().getId();                                
247                                 List<SharedContext> existingSC = getSharedContextService().getSharedContexts(sessionId);
248                                 if(existingSC==null || existingSC.size()==0){
249                                         getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_FIRST_NAME, commandBean.getUser().getFirstName());
250                                             getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_LAST_NAME, commandBean.getUser().getLastName());
251                                             getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_EMAIL, commandBean.getUser().getEmail());
252                                             getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_ORG_USERID, commandBean.getLoginId());
253                                 }
254                                     
255                             }catch(Exception e){
256                                 logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
257                                         logger.info(EELFLoggerDelegate.errorLogger, "failed the shared context adding process " + e.getMessage());
258                                         logger.info(EELFLoggerDelegate.debugLogger, "********************** failed the shared context adding process " + e.getMessage());
259
260                             }
261                             
262                                 logger.info(EELFLoggerDelegate.debugLogger, "********************* PresetUp the EP service cookie and intial sessionManagement");
263
264                             SessionCookieUtil.preSetUp(request, response); 
265                             SessionCookieUtil.setUpUserIdCookie(request, response, orgUserId);
266                                 logger.info(EELFLoggerDelegate.debugLogger, "********************* PresetUp the EP service cookie and intial sessionManagement completed");
267                                 logger.info(EELFLoggerDelegate.errorLogger, commandBean.getUser().getOrgUserId() + " exists in the the system.");
268                                 logger.info(EELFLoggerDelegate.debugLogger, commandBean.getUser().getOrgUserId() + " exists in the the system.");
269
270                             String redirect = "redirectUrl";
271                             
272                                 //get redirectUrl from URL parameter
273                             if(request.getParameter(redirect)!=null && request.getParameter(redirect).length()!=0){
274                                 String forwardUrl = URLDecoder.decode(request.getParameter(redirect),"UTF-8");
275                                 //clean cookie
276                                 Cookie cookie2 = new Cookie(redirect, "");
277                                 cookie2.setMaxAge(0);
278                                 cookie2.setDomain(EPSystemProperties.getProperty(EPSystemProperties.COOKIE_DOMAIN));
279                                 cookie2.setPath("/");
280                                 response.addCookie(cookie2);
281                                 return new ModelAndView("redirect:" + forwardUrl);
282                             }
283                             
284                             //first check if redirectUrl exists or not
285                                 if(WebUtils.getCookie(request, redirect)!=null){
286                                 String forwardUrl = WebUtils.getCookie(request, redirect).getValue();
287                                 //clean cookie
288                                 Cookie cookie2 = new Cookie(redirect, "");
289                             cookie2.setMaxAge(0);
290                             cookie2.setDomain(EPSystemProperties.getProperty(EPSystemProperties.COOKIE_DOMAIN));
291                             cookie2.setPath("/");
292                             response.addCookie(cookie2);               
293                                 
294                                 return new ModelAndView("redirect:" + forwardUrl);
295                         }
296                         }
297                 }
298                 
299                 // if user has been authenticated, now take them to the welcome page.
300                 //return new ModelAndView("redirect:" + DEFAULT_SUCCESS_VIEW + ".htm");
301                 logger.info(EELFLoggerDelegate.debugLogger, "********************** Now return to application home page");
302
303                 return new ModelAndView("redirect:" + SystemProperties.getProperty(EPSystemProperties.FE_URL));
304                 
305                 //
306                 // Re-enable for BE/FE separation.  For 1607, at last minute we decided to go out
307                 // without BE/FE separation.
308                 //
309                 //return new ModelAndView("redirect:" + SystemProperties.getProperty(EPSystemProperties.FE_URL));
310                 
311         }
312         
313     public String getJessionId(HttpServletRequest request){
314                 
315                 return request.getSession().getId();
316                 /*
317                 Cookie ep = WebUtils.getCookie(request, JSESSIONID);
318                 if(ep==null){
319                         return request.getSession().getId();
320                 }
321                 return ep.getValue();
322                 */
323         }
324         
325         
326         protected void initateSessionMgtHandler(HttpServletRequest request) {
327                 String jSessionId = getJessionId(request);
328                 PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request));
329         }
330         
331
332         public String getViewName() {
333                 return viewName;
334         }
335         public void setViewName(String viewName) {
336                 this.viewName = viewName;
337         }
338         public EPLoginService getLoginService() {
339         return loginService;
340     }
341
342     public void setLoginService(EPLoginService loginService) {
343         this.loginService = loginService;
344     }
345
346         public SharedContextService getSharedContextService() {
347                 return sharedContextService;
348         }
349
350         public void setSharedContextService(SharedContextService sharedContextService) {
351                 this.sharedContextService = sharedContextService;
352         }
353     
354
355
356 }