001    /**
002     * Copyright (c) 2000-2010 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.portlet.login.util;
016    
017    import com.liferay.portal.kernel.exception.SystemException;
018    import com.liferay.portal.kernel.log.Log;
019    import com.liferay.portal.kernel.log.LogFactoryUtil;
020    import com.liferay.portal.kernel.servlet.HttpHeaders;
021    import com.liferay.portal.kernel.servlet.SessionMessages;
022    import com.liferay.portal.kernel.util.GetterUtil;
023    import com.liferay.portal.kernel.util.ParamUtil;
024    import com.liferay.portal.kernel.util.StringPool;
025    import com.liferay.portal.kernel.util.Validator;
026    import com.liferay.portal.model.Company;
027    import com.liferay.portal.model.CompanyConstants;
028    import com.liferay.portal.model.User;
029    import com.liferay.portal.security.auth.AuthException;
030    import com.liferay.portal.security.auth.Authenticator;
031    import com.liferay.portal.service.ServiceContext;
032    import com.liferay.portal.service.ServiceContextFactory;
033    import com.liferay.portal.service.UserLocalServiceUtil;
034    import com.liferay.portal.theme.ThemeDisplay;
035    import com.liferay.portal.util.CookieKeys;
036    import com.liferay.portal.util.PortalUtil;
037    import com.liferay.portal.util.PortletKeys;
038    import com.liferay.portal.util.PropsValues;
039    import com.liferay.portal.util.WebKeys;
040    import com.liferay.portlet.PortletURLImpl;
041    import com.liferay.util.Encryptor;
042    
043    import java.util.ArrayList;
044    import java.util.Enumeration;
045    import java.util.HashMap;
046    import java.util.List;
047    import java.util.Map;
048    
049    import javax.portlet.ActionRequest;
050    import javax.portlet.PortletMode;
051    import javax.portlet.PortletModeException;
052    import javax.portlet.PortletRequest;
053    import javax.portlet.PortletURL;
054    import javax.portlet.WindowState;
055    import javax.portlet.WindowStateException;
056    
057    import javax.servlet.http.Cookie;
058    import javax.servlet.http.HttpServletRequest;
059    import javax.servlet.http.HttpServletResponse;
060    import javax.servlet.http.HttpSession;
061    
062    /**
063     * @author Brian Wing Shun Chan
064     * @author Scott Lee
065     */
066    public class LoginUtil {
067    
068            public static String getLogin(
069                            HttpServletRequest request, String paramName, Company company)
070                    throws SystemException {
071    
072                    String login = request.getParameter(paramName);
073    
074                    if ((login == null) || (login.equals(StringPool.NULL))) {
075                            login = GetterUtil.getString(
076                                    CookieKeys.getCookie(request, CookieKeys.LOGIN));
077    
078                            if (PropsValues.COMPANY_LOGIN_PREPOPULATE_DOMAIN &&
079                                    Validator.isNull(login) &&
080                                    company.getAuthType().equals(CompanyConstants.AUTH_TYPE_EA)) {
081    
082                                    login = "@" + company.getMx();
083                            }
084                    }
085    
086                    return login;
087            }
088    
089            public static PortletURL getLoginURL(
090                            HttpServletRequest request, long plid)
091                    throws PortletModeException, WindowStateException {
092    
093                    PortletURL portletURL = new PortletURLImpl(
094                            request, PortletKeys.LOGIN, plid, PortletRequest.RENDER_PHASE);
095    
096                    portletURL.setWindowState(WindowState.MAXIMIZED);
097                    portletURL.setPortletMode(PortletMode.VIEW);
098    
099                    portletURL.setParameter("saveLastPath", "0");
100                    portletURL.setParameter("struts_action", "/login/login");
101    
102                    return portletURL;
103            }
104    
105            public static void login(
106                            HttpServletRequest request, HttpServletResponse response,
107                            String login, String password, boolean rememberMe, String authType)
108                    throws Exception {
109    
110                    CookieKeys.validateSupportCookie(request);
111    
112                    HttpSession session = request.getSession();
113    
114                    long userId = GetterUtil.getLong(login);
115    
116                    int authResult = Authenticator.FAILURE;
117    
118                    Company company = PortalUtil.getCompany(request);
119    
120                    Map<String, String[]> headerMap = new HashMap<String, String[]>();
121    
122                    Enumeration<String> enu1 = request.getHeaderNames();
123    
124                    while (enu1.hasMoreElements()) {
125                            String name = enu1.nextElement();
126    
127                            Enumeration<String> enu2 = request.getHeaders(name);
128    
129                            List<String> headers = new ArrayList<String>();
130    
131                            while (enu2.hasMoreElements()) {
132                                    String value = enu2.nextElement();
133    
134                                    headers.add(value);
135                            }
136    
137                            headerMap.put(name, headers.toArray(new String[headers.size()]));
138                    }
139    
140                    Map<String, String[]> parameterMap = request.getParameterMap();
141    
142                    if (Validator.isNull(authType)) {
143                            authType = company.getAuthType();
144                    }
145    
146                    if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
147                            authResult = UserLocalServiceUtil.authenticateByEmailAddress(
148                                    company.getCompanyId(), login, password, headerMap,
149                                    parameterMap);
150    
151                            userId = UserLocalServiceUtil.getUserIdByEmailAddress(
152                                    company.getCompanyId(), login);
153                    }
154                    else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
155                            authResult = UserLocalServiceUtil.authenticateByScreenName(
156                                    company.getCompanyId(), login, password, headerMap,
157                                    parameterMap);
158    
159                            userId = UserLocalServiceUtil.getUserIdByScreenName(
160                                    company.getCompanyId(), login);
161                    }
162                    else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
163                            authResult = UserLocalServiceUtil.authenticateByUserId(
164                                    company.getCompanyId(), userId, password, headerMap,
165                                    parameterMap);
166                    }
167    
168                    if (authResult == Authenticator.SUCCESS) {
169                            if (PropsValues.SESSION_ENABLE_PHISHING_PROTECTION) {
170    
171                                    // Invalidate the previous session to prevent phishing
172    
173                                    String[] protectedAttributeNames =
174                                            PropsValues.SESSION_PHISHING_PROTECTED_ATTRIBUTES;
175    
176                                    Map<String, Object> protectedAttributes =
177                                            new HashMap<String, Object>();
178    
179                                    for (String protectedAttributeName : protectedAttributeNames) {
180                                            Object protectedAttributeValue = session.getAttribute(
181                                                    protectedAttributeName);
182    
183                                            if (protectedAttributeValue == null) {
184                                                    continue;
185                                            }
186    
187                                            protectedAttributes.put(
188                                                    protectedAttributeName, protectedAttributeValue);
189                                    }
190    
191                                    try {
192                                            session.invalidate();
193                                    }
194                                    catch (IllegalStateException ise) {
195    
196                                            // This only happens in Geronimo
197    
198                                            if (_log.isWarnEnabled()) {
199                                                    _log.warn(ise.getMessage());
200                                            }
201                                    }
202    
203                                    session = request.getSession(true);
204    
205                                    for (String protectedAttributeName : protectedAttributeNames) {
206                                            Object protectedAttributeValue = protectedAttributes.get(
207                                                    protectedAttributeName);
208    
209                                            if (protectedAttributeValue == null) {
210                                                    continue;
211                                            }
212    
213                                            session.setAttribute(
214                                                    protectedAttributeName, protectedAttributeValue);
215                                    }
216                            }
217    
218                            // Set cookies
219    
220                            String domain = CookieKeys.getDomain(request);
221    
222                            User user = UserLocalServiceUtil.getUserById(userId);
223    
224                            String userIdString = String.valueOf(userId);
225    
226                            session.setAttribute("j_username", userIdString);
227                            session.setAttribute("j_password", user.getPassword());
228                            session.setAttribute("j_remoteuser", userIdString);
229    
230                            if (PropsValues.SESSION_STORE_PASSWORD) {
231                                    session.setAttribute(WebKeys.USER_PASSWORD, password);
232                            }
233    
234                            Cookie companyIdCookie = new Cookie(
235                                    CookieKeys.COMPANY_ID, String.valueOf(company.getCompanyId()));
236    
237                            if (Validator.isNotNull(domain)) {
238                                    companyIdCookie.setDomain(domain);
239                            }
240    
241                            companyIdCookie.setPath(StringPool.SLASH);
242    
243                            Cookie idCookie = new Cookie(
244                                    CookieKeys.ID,
245                                    UserLocalServiceUtil.encryptUserId(userIdString));
246    
247                            if (Validator.isNotNull(domain)) {
248                                    idCookie.setDomain(domain);
249                            }
250    
251                            idCookie.setPath(StringPool.SLASH);
252    
253                            Cookie passwordCookie = new Cookie(
254                                    CookieKeys.PASSWORD,
255                                    Encryptor.encrypt(company.getKeyObj(), password));
256    
257                            if (Validator.isNotNull(domain)) {
258                                    passwordCookie.setDomain(domain);
259                            }
260    
261                            passwordCookie.setPath(StringPool.SLASH);
262    
263                            Cookie rememberMeCookie = new Cookie(
264                                    CookieKeys.REMEMBER_ME, Boolean.TRUE.toString());
265    
266                            if (Validator.isNotNull(domain)) {
267                                    rememberMeCookie.setDomain(domain);
268                            }
269    
270                            rememberMeCookie.setPath(StringPool.SLASH);
271    
272                            int loginMaxAge = PropsValues.COMPANY_SECURITY_AUTO_LOGIN_MAX_AGE;
273    
274                            if (PropsValues.SESSION_DISABLED) {
275                                    rememberMe = true;
276                            }
277    
278                            if (rememberMe) {
279                                    companyIdCookie.setMaxAge(loginMaxAge);
280                                    idCookie.setMaxAge(loginMaxAge);
281                                    passwordCookie.setMaxAge(loginMaxAge);
282                                    rememberMeCookie.setMaxAge(loginMaxAge);
283                            }
284                            else {
285    
286                                    // This was explicitly changed from 0 to -1 so that the cookie
287                                    // lasts as long as the browser. This allows an external servlet
288                                    // wrapped in AutoLoginFilter to work throughout the client
289                                    // connection. The cookies ARE removed on an actual logout, so
290                                    // there is no security issue. See LEP-4678 and LEP-5177.
291    
292                                    companyIdCookie.setMaxAge(-1);
293                                    idCookie.setMaxAge(-1);
294                                    passwordCookie.setMaxAge(-1);
295                                    rememberMeCookie.setMaxAge(0);
296                            }
297    
298                            Cookie loginCookie = new Cookie(CookieKeys.LOGIN, login);
299    
300                            if (Validator.isNotNull(domain)) {
301                                    loginCookie.setDomain(domain);
302                            }
303    
304                            loginCookie.setMaxAge(loginMaxAge);
305                            loginCookie.setPath(StringPool.SLASH);
306    
307                            Cookie screenNameCookie = new Cookie(
308                                    CookieKeys.SCREEN_NAME,
309                                    Encryptor.encrypt(company.getKeyObj(), user.getScreenName()));
310    
311                            if (Validator.isNotNull(domain)) {
312                                    screenNameCookie.setDomain(domain);
313                            }
314    
315                            screenNameCookie.setMaxAge(loginMaxAge);
316                            screenNameCookie.setPath(StringPool.SLASH);
317    
318                            boolean secure = request.isSecure();
319    
320                            if (secure) {
321                                    Boolean httpsInitial = (Boolean)session.getAttribute(
322                                            WebKeys.HTTPS_INITIAL);
323    
324                                    if ((httpsInitial == null) || !httpsInitial.booleanValue()) {
325                                            secure = false;
326                                    }
327                            }
328    
329                            CookieKeys.addCookie(request, response, companyIdCookie, secure);
330                            CookieKeys.addCookie(request, response, idCookie, secure);
331                            CookieKeys.addCookie(request, response, passwordCookie, secure);
332                            CookieKeys.addCookie(request, response, rememberMeCookie, secure);
333                            CookieKeys.addCookie(request, response, loginCookie, secure);
334                            CookieKeys.addCookie(request, response, screenNameCookie, secure);
335                    }
336                    else {
337                            throw new AuthException();
338                    }
339            }
340    
341            public static void sendPassword(ActionRequest actionRequest)
342                    throws Exception {
343    
344                    String toAddress = ParamUtil.getString(actionRequest, "emailAddress");
345    
346                    sendPassword(actionRequest, null, null, toAddress, null, null);
347            }
348    
349            public static void sendPassword(
350                            ActionRequest actionRequest, String fromName, String fromAddress,
351                            String toAddress, String subject, String body)
352                    throws Exception {
353    
354                    HttpServletRequest request = PortalUtil.getHttpServletRequest(
355                            actionRequest);
356    
357                    ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(
358                            WebKeys.THEME_DISPLAY);
359    
360                    Company company = themeDisplay.getCompany();
361    
362                    if (!company.isSendPassword()) {
363                            return;
364                    }
365    
366                    String remoteAddr = request.getRemoteAddr();
367                    String remoteHost = request.getRemoteHost();
368                    String userAgent = request.getHeader(HttpHeaders.USER_AGENT);
369    
370                    ServiceContext serviceContext = ServiceContextFactory.getInstance(
371                            User.class.getName(), actionRequest);
372    
373                    UserLocalServiceUtil.sendPassword(
374                            company.getCompanyId(), toAddress, remoteAddr, remoteHost,
375                            userAgent, fromName, fromAddress, subject, body, serviceContext);
376    
377                    SessionMessages.add(actionRequest, "request_processed", toAddress);
378            }
379    
380            private static Log _log = LogFactoryUtil.getLog(LoginUtil.class);
381    
382    }