001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
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.MapUtil;
024    import com.liferay.portal.kernel.util.ParamUtil;
025    import com.liferay.portal.kernel.util.StringPool;
026    import com.liferay.portal.kernel.util.Validator;
027    import com.liferay.portal.model.Company;
028    import com.liferay.portal.model.CompanyConstants;
029    import com.liferay.portal.model.User;
030    import com.liferay.portal.security.auth.AuthException;
031    import com.liferay.portal.security.auth.Authenticator;
032    import com.liferay.portal.service.ServiceContext;
033    import com.liferay.portal.service.ServiceContextFactory;
034    import com.liferay.portal.service.UserLocalServiceUtil;
035    import com.liferay.portal.theme.ThemeDisplay;
036    import com.liferay.portal.util.CookieKeys;
037    import com.liferay.portal.util.PortalUtil;
038    import com.liferay.portal.util.PortletKeys;
039    import com.liferay.portal.util.PropsValues;
040    import com.liferay.portal.util.WebKeys;
041    import com.liferay.portlet.PortletURLImpl;
042    import com.liferay.util.Encryptor;
043    
044    import java.util.ArrayList;
045    import java.util.Enumeration;
046    import java.util.HashMap;
047    import java.util.List;
048    import java.util.Map;
049    
050    import javax.portlet.ActionRequest;
051    import javax.portlet.PortletMode;
052    import javax.portlet.PortletModeException;
053    import javax.portlet.PortletRequest;
054    import javax.portlet.PortletURL;
055    import javax.portlet.WindowState;
056    import javax.portlet.WindowStateException;
057    
058    import javax.servlet.http.Cookie;
059    import javax.servlet.http.HttpServletRequest;
060    import javax.servlet.http.HttpServletResponse;
061    import javax.servlet.http.HttpSession;
062    
063    /**
064     * @author Brian Wing Shun Chan
065     * @author Scott Lee
066     */
067    public class LoginUtil {
068    
069            public static String getLogin(
070                            HttpServletRequest request, String paramName, Company company)
071                    throws SystemException {
072    
073                    String login = request.getParameter(paramName);
074    
075                    if ((login == null) || (login.equals(StringPool.NULL))) {
076                            login = GetterUtil.getString(
077                                    CookieKeys.getCookie(request, CookieKeys.LOGIN));
078    
079                            if (PropsValues.COMPANY_LOGIN_PREPOPULATE_DOMAIN &&
080                                    Validator.isNull(login) &&
081                                    company.getAuthType().equals(CompanyConstants.AUTH_TYPE_EA)) {
082    
083                                    login = "@" + company.getMx();
084                            }
085                    }
086    
087                    return login;
088            }
089    
090            public static PortletURL getLoginURL(
091                            HttpServletRequest request, long plid)
092                    throws PortletModeException, WindowStateException {
093    
094                    PortletURL portletURL = new PortletURLImpl(
095                            request, PortletKeys.LOGIN, plid, PortletRequest.RENDER_PHASE);
096    
097                    portletURL.setWindowState(WindowState.MAXIMIZED);
098                    portletURL.setPortletMode(PortletMode.VIEW);
099    
100                    portletURL.setParameter("saveLastPath", "0");
101                    portletURL.setParameter("struts_action", "/login/login");
102    
103                    return portletURL;
104            }
105    
106            public static void login(
107                            HttpServletRequest request, HttpServletResponse response,
108                            String login, String password, boolean rememberMe, String authType)
109                    throws Exception {
110    
111                    CookieKeys.validateSupportCookie(request);
112    
113                    HttpSession session = request.getSession();
114    
115                    long userId = GetterUtil.getLong(login);
116    
117                    int authResult = Authenticator.FAILURE;
118    
119                    Company company = PortalUtil.getCompany(request);
120    
121                    Map<String, String[]> headerMap = new HashMap<String, String[]>();
122    
123                    Enumeration<String> enu1 = request.getHeaderNames();
124    
125                    while (enu1.hasMoreElements()) {
126                            String name = enu1.nextElement();
127    
128                            Enumeration<String> enu2 = request.getHeaders(name);
129    
130                            List<String> headers = new ArrayList<String>();
131    
132                            while (enu2.hasMoreElements()) {
133                                    String value = enu2.nextElement();
134    
135                                    headers.add(value);
136                            }
137    
138                            headerMap.put(name, headers.toArray(new String[headers.size()]));
139                    }
140    
141                    Map<String, String[]> parameterMap = request.getParameterMap();
142                    Map<String, Object> resultsMap = new HashMap<String, Object>();
143    
144                    if (Validator.isNull(authType)) {
145                            authType = company.getAuthType();
146                    }
147    
148                    if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
149                            authResult = UserLocalServiceUtil.authenticateByEmailAddress(
150                                    company.getCompanyId(), login, password, headerMap,
151                                    parameterMap, resultsMap);
152    
153                            userId = MapUtil.getLong(resultsMap, "userId", userId);
154                    }
155                    else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
156                            authResult = UserLocalServiceUtil.authenticateByScreenName(
157                                    company.getCompanyId(), login, password, headerMap,
158                                    parameterMap, resultsMap);
159    
160                            userId = MapUtil.getLong(resultsMap, "userId", userId);
161                    }
162                    else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
163                            authResult = UserLocalServiceUtil.authenticateByUserId(
164                                    company.getCompanyId(), userId, password, headerMap,
165                                    parameterMap, resultsMap);
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    }