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