Merge "[UI] Optional trust of all SSL Certificates"
[validation.git] / ui / src / main / java / org / akraino / validation / ui / login / LoginStrategyImpl.java
1 /*
2  * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may
5  * not use this file except in compliance with the License. You may obtain
6  * a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13  * implied. See the License for the specific language governing
14  * permissions and limitations under the License.
15  */
16
17 package org.akraino.validation.ui.login;
18
19 import java.io.IOException;
20 import java.util.HashMap;
21 import java.util.List;
22 import java.util.Map;
23
24 import javax.servlet.http.Cookie;
25 import javax.servlet.http.HttpServletRequest;
26 import javax.servlet.http.HttpServletResponse;
27
28 import org.onap.portalsdk.core.auth.LoginStrategy;
29 import org.onap.portalsdk.core.command.LoginBean;
30 import org.onap.portalsdk.core.domain.RoleFunction;
31 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
32 import org.onap.portalsdk.core.menu.MenuProperties;
33 import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
34 import org.onap.portalsdk.core.onboarding.exception.PortalAPIException;
35 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
36 import org.onap.portalsdk.core.service.LoginService;
37 import org.onap.portalsdk.core.service.RoleService;
38 import org.onap.portalsdk.core.util.SystemProperties;
39 import org.onap.portalsdk.core.web.support.UserUtils;
40 import org.springframework.beans.factory.annotation.Autowired;
41 import org.springframework.web.servlet.ModelAndView;
42
43 /**
44  * Implements basic single-signon login strategy for open-source applications
45  * when users start at Portal. Extracts an encrypted user ID sent by Portal.
46  */
47 public class LoginStrategyImpl extends LoginStrategy {
48
49     private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(LoginStrategyImpl.class);
50
51     @Autowired
52     private RoleService roleService;
53
54     @Autowired
55     private LoginService loginService;
56
57     /**
58      * login for open source is same as external login in the non-open-source
59      * version.
60      */
61     @Override
62     public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
63         invalidateExistingSession(request);
64
65         LoginBean commandBean = new LoginBean();
66         String loginId = request.getParameter("loginId");
67         String password = request.getParameter("password");
68         String redirectUrl = request.getParameter("redirectUrl");
69         commandBean.setLoginId(loginId);
70         commandBean.setLoginPwd(password);
71         commandBean.setUserid(loginId);
72         commandBean = loginService.findUser(commandBean,
73                 (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), new HashMap());
74         List<RoleFunction> roleFunctionList = roleService.getRoleFunctions(loginId);
75         if (commandBean.getUser() == null || !CipherUtil
76                 .decryptPKC(commandBean.getUser().getLoginPwd(), System.getenv("ENCRYPTION_KEY")).equals(password)) {
77             String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) ? commandBean.getLoginErrorMessage()
78                     : "login.error.external.invalid";
79             Map<String, String> model = new HashMap<>();
80             model.put("error", loginErrorMessage);
81             if (redirectUrl == null || redirectUrl.equals("")) {
82                 return new ModelAndView("login_external", "model", model);
83             } else {
84                 return new ModelAndView(
85                         "redirect:login_external.htm?redirectUrl=" + request.getParameter("redirectUrl"));
86             }
87         } else {
88             // store the currently logged in user's information in the session
89             UserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(),
90                     commandBean.getBusinessDirectMenu(),
91                     SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_BACKDOOR), roleFunctionList);
92             initateSessionMgtHandler(request);
93             // user has been authenticated, now take them to the welcome or redirection page
94             if (redirectUrl == null || redirectUrl.equals("")) {
95                 return new ModelAndView("redirect:welcome.htm");
96             } else {
97                 return new ModelAndView("redirect:"
98                         + redirectUrl.substring(redirectUrl.lastIndexOf("/bluvalui/") + 10, redirectUrl.length()));
99             }
100         }
101     }
102
103     @Override
104     public ModelAndView doExternalLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
105
106         invalidateExistingSession(request);
107
108         LoginBean commandBean = new LoginBean();
109         String loginId = request.getParameter("loginId");
110         String password = request.getParameter("password");
111         String redirectUrl = request.getParameter("redirectUrl");
112         commandBean.setLoginId(loginId);
113         commandBean.setLoginPwd(password);
114         commandBean.setUserid(loginId);
115         commandBean = loginService.findUser(commandBean,
116                 (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), new HashMap());
117         List<RoleFunction> roleFunctionList = roleService.getRoleFunctions(loginId);
118
119         try {
120             if (commandBean.getUser() == null
121                     || !CipherUtil.decryptPKC(commandBean.getUser().getLoginPwd(), System.getenv("ENCRYPTION_KEY"))
122                     .equals(password)) {
123                 String loginErrorMessage = (commandBean.getLoginErrorMessage() != null)
124                         ? commandBean.getLoginErrorMessage()
125                                 : "login.error.external.invalid";
126                         Map<String, String> model = new HashMap<>();
127                         model.put("error", loginErrorMessage);
128                         if (redirectUrl == null || redirectUrl.equals("")) {
129                             return new ModelAndView("login_external", "model", model);
130                         } else {
131                             return new ModelAndView(
132                                     "redirect:login_external.htm?redirectUrl=" + request.getParameter("redirectUrl"));
133                         }
134             } else {
135                 // store the currently logged in user's information in the session
136                 UserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(),
137                         commandBean.getBusinessDirectMenu(),
138                         SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_BACKDOOR), roleFunctionList);
139                 initateSessionMgtHandler(request);
140                 // user has been authenticated, now take them to the welcome or redirection page
141                 if (redirectUrl == null || redirectUrl.equals("")) {
142                     return new ModelAndView("redirect:welcome.htm");
143                 } else {
144                     return new ModelAndView("redirect:"
145                             + redirectUrl.substring(redirectUrl.lastIndexOf("/bluvalui/") + 10, redirectUrl.length()));
146                 }
147             }
148         } catch (CipherUtilException e) {
149             LOGGER.error(EELFLoggerDelegate.errorLogger, "Error in Cipher." + UserUtils.getStackTrace(e));
150             // store the currently logged in user's information in the session
151             UserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(),
152                     commandBean.getBusinessDirectMenu(),
153                     SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_BACKDOOR), roleFunctionList);
154             initateSessionMgtHandler(request);
155             // user has been authenticated, now take them to the welcome or redirection page
156             if (redirectUrl == null || redirectUrl.equals("")) {
157                 return new ModelAndView("redirect:welcome.htm");
158             } else {
159                 return new ModelAndView("redirect:"
160                         + redirectUrl.substring(redirectUrl.lastIndexOf("/bluvalui/") + 10, redirectUrl.length()));
161             }
162         }
163     }
164
165     @Override
166     public String getUserId(HttpServletRequest request) throws PortalAPIException {
167         // Check ECOMP Portal cookie
168         Cookie ep = getCookie(request, EP_SERVICE);
169         if (ep == null) {
170             LOGGER.debug(EELFLoggerDelegate.debugLogger, "getUserId: no EP_SERVICE cookie, returning null");
171             return null;
172         }
173
174         String userid = null;
175         try {
176             userid = getUserIdFromCookie(request);
177         } catch (Exception e) {
178             LOGGER.error(EELFLoggerDelegate.errorLogger, "getUserId failed", e);
179         }
180         return userid;
181     }
182
183     /**
184      * Searches the request for the user-ID cookie and decrypts the value using a
185      * key configured in properties
186      *
187      * @param request HttpServletRequest
188      * @return User ID
189      * @throws CipherUtilException On any failure to decrypt
190      */
191     private String getUserIdFromCookie(HttpServletRequest request) throws CipherUtilException {
192         String userId = "";
193         Cookie userIdCookie = getCookie(request, USER_ID);
194         if (userIdCookie != null) {
195             final String cookieValue = userIdCookie.getValue();
196             if (!SystemProperties.containsProperty(SystemProperties.Decryption_Key))
197                 throw new IllegalStateException("Failed to find property " + SystemProperties.Decryption_Key);
198             final String decryptionKey = SystemProperties.getProperty(SystemProperties.Decryption_Key);
199             userId = CipherUtil.decrypt(cookieValue, decryptionKey);
200             LOGGER.debug(EELFLoggerDelegate.debugLogger, "getUserIdFromCookie: decrypted as {}", userId);
201         }
202         return userId;
203     }
204
205     /**
206      * Searches the request for the named cookie.
207      *
208      * @param request    HttpServletRequest
209      * @param cookieName Name of desired cookie
210      * @return Cookie if found; otherwise null.
211      */
212     private Cookie getCookie(HttpServletRequest request, String cookieName) {
213         Cookie[] cookies = request.getCookies();
214         if (cookies != null)
215             for (Cookie cookie : cookies)
216                 if (cookie.getName().equals(cookieName))
217                     return cookie;
218         return null;
219     }
220
221 }