001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.servlet.filters.autologin;
016    
017    import com.liferay.portal.kernel.log.Log;
018    import com.liferay.portal.kernel.log.LogFactoryUtil;
019    import com.liferay.portal.kernel.security.auto.login.AutoLogin;
020    import com.liferay.portal.kernel.servlet.ProtectedServletRequest;
021    import com.liferay.portal.kernel.util.GetterUtil;
022    import com.liferay.portal.kernel.util.StringBundler;
023    import com.liferay.portal.kernel.util.StringPool;
024    import com.liferay.portal.kernel.util.StringUtil;
025    import com.liferay.portal.kernel.util.Validator;
026    import com.liferay.portal.model.User;
027    import com.liferay.portal.security.pwd.PasswordEncryptorUtil;
028    import com.liferay.portal.service.UserLocalServiceUtil;
029    import com.liferay.portal.servlet.filters.BasePortalFilter;
030    import com.liferay.portal.util.Portal;
031    import com.liferay.portal.util.PortalInstances;
032    import com.liferay.portal.util.PortalUtil;
033    import com.liferay.portal.util.PropsValues;
034    import com.liferay.portal.util.WebKeys;
035    import com.liferay.portlet.login.util.LoginUtil;
036    import com.liferay.registry.Registry;
037    import com.liferay.registry.RegistryUtil;
038    import com.liferay.registry.ServiceReference;
039    import com.liferay.registry.ServiceTracker;
040    import com.liferay.registry.ServiceTrackerCustomizer;
041    
042    import java.util.List;
043    import java.util.concurrent.CopyOnWriteArrayList;
044    
045    import javax.servlet.FilterChain;
046    import javax.servlet.http.HttpServletRequest;
047    import javax.servlet.http.HttpServletResponse;
048    import javax.servlet.http.HttpSession;
049    
050    /**
051     * @author Brian Wing Shun Chan
052     * @author Peter Fellwock
053     * @author Raymond Aug??
054     */
055    public class AutoLoginFilter extends BasePortalFilter {
056    
057            public AutoLoginFilter() {
058                    Registry registry = RegistryUtil.getRegistry();
059    
060                    _serviceTracker = registry.trackServices(
061                            AutoLogin.class, new AutoLoginServiceTrackerCustomizer());
062    
063                    _serviceTracker.open();
064            }
065    
066            protected String getLoginRemoteUser(
067                            HttpServletRequest request, HttpServletResponse response,
068                            HttpSession session, String[] credentials)
069                    throws Exception {
070    
071                    if ((credentials == null) || (credentials.length != 3)) {
072                            return null;
073                    }
074    
075                    String jUsername = credentials[0];
076                    String jPassword = credentials[1];
077                    boolean encPassword = GetterUtil.getBoolean(credentials[2]);
078    
079                    if (Validator.isNull(jUsername) || Validator.isNull(jPassword)) {
080                            return null;
081                    }
082    
083                    long userId = GetterUtil.getLong(jUsername);
084    
085                    if (userId <= 0) {
086                            return null;
087                    }
088    
089                    User user = UserLocalServiceUtil.fetchUserById(userId);
090    
091                    if ((user == null) || user.isLockout()) {
092                            return null;
093                    }
094    
095                    if (!PropsValues.AUTH_SIMULTANEOUS_LOGINS) {
096                            LoginUtil.signOutSimultaneousLogins(userId);
097                    }
098    
099                    if (PropsValues.SESSION_ENABLE_PHISHING_PROTECTION) {
100                            session = LoginUtil.renewSession(request, session);
101                    }
102    
103                    session.setAttribute("j_username", jUsername);
104    
105                    // Not having access to the unencrypted password will not allow you to
106                    // connect to external resources that require it (mail server)
107    
108                    if (encPassword) {
109                            session.setAttribute("j_password", jPassword);
110                    }
111                    else {
112                            session.setAttribute(
113                                    "j_password", PasswordEncryptorUtil.encrypt(jPassword));
114    
115                            if (PropsValues.SESSION_STORE_PASSWORD) {
116                                    session.setAttribute(WebKeys.USER_PASSWORD, jPassword);
117                            }
118                    }
119    
120                    session.setAttribute("j_remoteuser", jUsername);
121    
122                    if (PropsValues.PORTAL_JAAS_ENABLE) {
123                            String redirect = PortalUtil.getPathMain().concat(
124                                    "/portal/protected");
125    
126                            if (PropsValues.AUTH_FORWARD_BY_LAST_PATH) {
127                                    String autoLoginRedirect = (String)request.getAttribute(
128                                            AutoLogin.AUTO_LOGIN_REDIRECT_AND_CONTINUE);
129    
130                                    redirect = redirect.concat("?redirect=");
131    
132                                    if (Validator.isNotNull(autoLoginRedirect)) {
133                                            redirect = redirect.concat(autoLoginRedirect);
134                                    }
135                                    else {
136                                            redirect = redirect.concat(
137                                                    PortalUtil.getCurrentCompleteURL(request));
138                                    }
139                            }
140    
141                            response.sendRedirect(redirect);
142                    }
143    
144                    return jUsername;
145            }
146    
147            @Override
148            protected void processFilter(
149                            HttpServletRequest request, HttpServletResponse response,
150                            FilterChain filterChain)
151                    throws Exception {
152    
153                    HttpSession session = request.getSession();
154    
155                    String host = PortalUtil.getHost(request);
156    
157                    if (PortalInstances.isAutoLoginIgnoreHost(host)) {
158                            if (_log.isDebugEnabled()) {
159                                    _log.debug("Ignore host " + host);
160                            }
161    
162                            processFilter(
163                                    AutoLoginFilter.class, request, response, filterChain);
164    
165                            return;
166                    }
167    
168                    String contextPath = PortalUtil.getPathContext();
169    
170                    String path = StringUtil.toLowerCase(request.getRequestURI());
171    
172                    if (!contextPath.equals(StringPool.SLASH) &&
173                            path.contains(contextPath)) {
174    
175                            path = path.substring(contextPath.length());
176                    }
177    
178                    if (PortalInstances.isAutoLoginIgnorePath(path)) {
179                            if (_log.isDebugEnabled()) {
180                                    _log.debug("Ignore path " + path);
181                            }
182    
183                            processFilter(
184                                    AutoLoginFilter.class, request, response, filterChain);
185    
186                            return;
187                    }
188    
189                    String remoteUser = request.getRemoteUser();
190                    String jUserName = (String)session.getAttribute("j_username");
191    
192                    // PLACEHOLDER 01
193                    // PLACEHOLDER 02
194                    // PLACEHOLDER 03
195                    // PLACEHOLDER 04
196                    // PLACEHOLDER 05
197    
198                    if (!PropsValues.AUTH_LOGIN_DISABLED &&
199                            (remoteUser == null) && (jUserName == null)) {
200    
201                            for (AutoLogin autoLogin : _autoLogins) {
202                                    try {
203                                            String[] credentials = autoLogin.login(request, response);
204    
205                                            String redirect = (String)request.getAttribute(
206                                                    AutoLogin.AUTO_LOGIN_REDIRECT);
207    
208                                            if (Validator.isNotNull(redirect)) {
209                                                    response.sendRedirect(redirect);
210    
211                                                    return;
212                                            }
213    
214                                            String loginRemoteUser = getLoginRemoteUser(
215                                                    request, response, session, credentials);
216    
217                                            if (loginRemoteUser != null) {
218                                                    request = new ProtectedServletRequest(
219                                                            request, loginRemoteUser);
220    
221                                                    if (PropsValues.PORTAL_JAAS_ENABLE) {
222                                                            return;
223                                                    }
224    
225                                                    if (!PropsValues.AUTH_FORWARD_BY_LAST_PATH) {
226                                                            redirect = Portal.PATH_MAIN;
227                                                    }
228                                                    else {
229                                                            redirect = (String)request.getAttribute(
230                                                                    AutoLogin.AUTO_LOGIN_REDIRECT_AND_CONTINUE);
231                                                    }
232    
233                                                    if (Validator.isNotNull(redirect)) {
234                                                            response.sendRedirect(redirect);
235    
236                                                            return;
237                                                    }
238                                            }
239                                    }
240                                    catch (Exception e) {
241                                            StringBundler sb = new StringBundler(4);
242    
243                                            sb.append("Current URL ");
244    
245                                            String currentURL = PortalUtil.getCurrentURL(request);
246    
247                                            sb.append(currentURL);
248    
249                                            sb.append(" generates exception: ");
250                                            sb.append(e.getMessage());
251    
252                                            if (currentURL.endsWith(_PATH_CHAT_LATEST)) {
253                                                    if (_log.isWarnEnabled()) {
254                                                            _log.warn(sb.toString());
255                                                    }
256                                            }
257                                            else {
258                                                    _log.error(sb.toString());
259                                            }
260                                    }
261                            }
262                    }
263    
264                    processFilter(AutoLoginFilter.class, request, response, filterChain);
265            }
266    
267            private static final String _PATH_CHAT_LATEST = "/-/chat/latest";
268    
269            private static final Log _log = LogFactoryUtil.getLog(
270                    AutoLoginFilter.class);
271    
272            private static final List<AutoLogin> _autoLogins =
273                    new CopyOnWriteArrayList<>();
274    
275            private final ServiceTracker<?, AutoLogin> _serviceTracker;
276    
277            private class AutoLoginServiceTrackerCustomizer
278                    implements ServiceTrackerCustomizer<AutoLogin, AutoLogin> {
279    
280                    @Override
281                    public AutoLogin addingService(
282                            ServiceReference<AutoLogin> serviceReference) {
283    
284                            Registry registry = RegistryUtil.getRegistry();
285    
286                            AutoLogin autoLogin = registry.getService(serviceReference);
287    
288                            if (autoLogin == null) {
289                                    return null;
290                            }
291    
292                            _autoLogins.add(autoLogin);
293    
294                            return autoLogin;
295                    }
296    
297                    @Override
298                    public void modifiedService(
299                            ServiceReference<AutoLogin> serviceReference, AutoLogin autoLogin) {
300                    }
301    
302                    @Override
303                    public void removedService(
304                            ServiceReference<AutoLogin> serviceReference, AutoLogin autoLogin) {
305    
306                            Registry registry = RegistryUtil.getRegistry();
307    
308                            registry.ungetService(serviceReference);
309    
310                            _autoLogins.remove(autoLogin);
311                    }
312    
313            }
314    
315    }