ea144838d48e4ef129f94a40100eb2043dfe7b2a
[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         commandBean.setLoginId(loginId);
69         commandBean.setLoginPwd(password);
70         commandBean.setUserid(loginId);
71         commandBean = loginService.findUser(commandBean,
72                 (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), new HashMap());
73         List<RoleFunction> roleFunctionList = roleService.getRoleFunctions(loginId);
74         if (commandBean.getUser() == null || !CipherUtil
75                 .decryptPKC(commandBean.getUser().getLoginPwd(), System.getenv("ENCRYPTION_KEY")).equals(password)) {
76             String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) ? commandBean.getLoginErrorMessage()
77                     : "login.error.external.invalid";
78             Map<String, String> model = new HashMap<>();
79             model.put("error", loginErrorMessage);
80             return new ModelAndView("login_external", "model", model);
81         } else {
82             // store the currently logged in user's information in the session
83             UserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(),
84                     commandBean.getBusinessDirectMenu(),
85                     SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_BACKDOOR), roleFunctionList);
86             initateSessionMgtHandler(request);
87             // user has been authenticated, now take them to the welcome page
88             return new ModelAndView("redirect:welcome.htm");
89         }
90     }
91
92     @Override
93     public ModelAndView doExternalLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
94
95         invalidateExistingSession(request);
96
97         LoginBean commandBean = new LoginBean();
98         String loginId = request.getParameter("loginId");
99         String password = request.getParameter("password");
100         commandBean.setLoginId(loginId);
101         commandBean.setLoginPwd(password);
102         commandBean.setUserid(loginId);
103         commandBean = loginService.findUser(commandBean,
104                 (String) request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), new HashMap());
105         List<RoleFunction> roleFunctionList = roleService.getRoleFunctions(loginId);
106
107         try {
108             if (commandBean.getUser() == null
109                     || !CipherUtil.decryptPKC(commandBean.getUser().getLoginPwd(), System.getenv("ENCRYPTION_KEY"))
110                     .equals(password)) {
111                 String loginErrorMessage = (commandBean.getLoginErrorMessage() != null)
112                         ? commandBean.getLoginErrorMessage()
113                                 : "login.error.external.invalid";
114                         Map<String, String> model = new HashMap<>();
115                         model.put("error", loginErrorMessage);
116                         return new ModelAndView("login_external", "model", model);
117             } else {
118                 // store the currently logged in user's information in the session
119                 UserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(),
120                         commandBean.getBusinessDirectMenu(),
121                         SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_BACKDOOR), roleFunctionList);
122                 initateSessionMgtHandler(request);
123                 // user has been authenticated, now take them to the welcome page
124                 return new ModelAndView("redirect:welcome");
125             }
126         } catch (CipherUtilException e) {
127             LOGGER.error(EELFLoggerDelegate.errorLogger, "Error in Cipher." + UserUtils.getStackTrace(e));
128             // store the currently logged in user's information in the session
129             UserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(),
130                     commandBean.getBusinessDirectMenu(),
131                     SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_BACKDOOR), roleFunctionList);
132             initateSessionMgtHandler(request);
133             // user has been authenticated, now take them to the welcome page
134             return new ModelAndView("redirect:welcome");
135         }
136     }
137
138     @Override
139     public String getUserId(HttpServletRequest request) throws PortalAPIException {
140         // Check ECOMP Portal cookie
141         Cookie ep = getCookie(request, EP_SERVICE);
142         if (ep == null) {
143             LOGGER.debug(EELFLoggerDelegate.debugLogger, "getUserId: no EP_SERVICE cookie, returning null");
144             return null;
145         }
146
147         String userid = null;
148         try {
149             userid = getUserIdFromCookie(request);
150         } catch (Exception e) {
151             LOGGER.error(EELFLoggerDelegate.errorLogger, "getUserId failed", e);
152         }
153         return userid;
154     }
155
156     /**
157      * Searches the request for the user-ID cookie and decrypts the value using a
158      * key configured in properties
159      *
160      * @param request HttpServletRequest
161      * @return User ID
162      * @throws CipherUtilException On any failure to decrypt
163      */
164     private String getUserIdFromCookie(HttpServletRequest request) throws CipherUtilException {
165         String userId = "";
166         Cookie userIdCookie = getCookie(request, USER_ID);
167         if (userIdCookie != null) {
168             final String cookieValue = userIdCookie.getValue();
169             if (!SystemProperties.containsProperty(SystemProperties.Decryption_Key))
170                 throw new IllegalStateException("Failed to find property " + SystemProperties.Decryption_Key);
171             final String decryptionKey = SystemProperties.getProperty(SystemProperties.Decryption_Key);
172             userId = CipherUtil.decrypt(cookieValue, decryptionKey);
173             LOGGER.debug(EELFLoggerDelegate.debugLogger, "getUserIdFromCookie: decrypted as {}", userId);
174         }
175         return userId;
176     }
177
178     /**
179      * Searches the request for the named cookie.
180      *
181      * @param request    HttpServletRequest
182      * @param cookieName Name of desired cookie
183      * @return Cookie if found; otherwise null.
184      */
185     private Cookie getCookie(HttpServletRequest request, String cookieName) {
186         Cookie[] cookies = request.getCookies();
187         if (cookies != null)
188             for (Cookie cookie : cookies)
189                 if (cookie.getName().equals(cookieName))
190                     return cookie;
191         return null;
192     }
193
194 }