001    /**
002     * Copyright (c) 2000-2013 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.cluster.ClusterExecutorUtil;
018    import com.liferay.portal.kernel.cluster.ClusterNode;
019    import com.liferay.portal.kernel.exception.PortalException;
020    import com.liferay.portal.kernel.exception.SystemException;
021    import com.liferay.portal.kernel.json.JSONFactoryUtil;
022    import com.liferay.portal.kernel.json.JSONObject;
023    import com.liferay.portal.kernel.log.Log;
024    import com.liferay.portal.kernel.log.LogFactoryUtil;
025    import com.liferay.portal.kernel.messaging.DestinationNames;
026    import com.liferay.portal.kernel.messaging.MessageBusUtil;
027    import com.liferay.portal.kernel.servlet.SessionMessages;
028    import com.liferay.portal.kernel.util.CookieKeys;
029    import com.liferay.portal.kernel.util.GetterUtil;
030    import com.liferay.portal.kernel.util.Http;
031    import com.liferay.portal.kernel.util.MapUtil;
032    import com.liferay.portal.kernel.util.ParamUtil;
033    import com.liferay.portal.kernel.util.StringPool;
034    import com.liferay.portal.kernel.util.StringUtil;
035    import com.liferay.portal.kernel.util.Validator;
036    import com.liferay.portal.liveusers.LiveUsers;
037    import com.liferay.portal.model.Company;
038    import com.liferay.portal.model.CompanyConstants;
039    import com.liferay.portal.model.User;
040    import com.liferay.portal.model.UserTracker;
041    import com.liferay.portal.security.auth.AuthException;
042    import com.liferay.portal.security.auth.AuthenticatedUserUUIDStoreUtil;
043    import com.liferay.portal.security.auth.Authenticator;
044    import com.liferay.portal.service.CompanyLocalServiceUtil;
045    import com.liferay.portal.service.ServiceContext;
046    import com.liferay.portal.service.ServiceContextFactory;
047    import com.liferay.portal.service.UserLocalServiceUtil;
048    import com.liferay.portal.theme.ThemeDisplay;
049    import com.liferay.portal.util.PortalUtil;
050    import com.liferay.portal.util.PortletKeys;
051    import com.liferay.portal.util.PropsValues;
052    import com.liferay.portal.util.WebKeys;
053    import com.liferay.portlet.PortletURLFactoryUtil;
054    import com.liferay.util.Encryptor;
055    
056    import java.util.ArrayList;
057    import java.util.Enumeration;
058    import java.util.HashMap;
059    import java.util.List;
060    import java.util.Map;
061    
062    import javax.portlet.ActionRequest;
063    import javax.portlet.PortletMode;
064    import javax.portlet.PortletModeException;
065    import javax.portlet.PortletPreferences;
066    import javax.portlet.PortletRequest;
067    import javax.portlet.PortletURL;
068    import javax.portlet.WindowState;
069    import javax.portlet.WindowStateException;
070    
071    import javax.servlet.http.Cookie;
072    import javax.servlet.http.HttpServletRequest;
073    import javax.servlet.http.HttpServletResponse;
074    import javax.servlet.http.HttpSession;
075    
076    /**
077     * @author Brian Wing Shun Chan
078     * @author Scott Lee
079     */
080    public class LoginUtil {
081    
082            public static long getAuthenticatedUserId(
083                            HttpServletRequest request, String login, String password,
084                            String authType)
085                    throws PortalException, SystemException {
086    
087                    long userId = GetterUtil.getLong(login);
088    
089                    Company company = PortalUtil.getCompany(request);
090    
091                    String requestURI = request.getRequestURI();
092    
093                    String contextPath = PortalUtil.getPathContext();
094    
095                    if (requestURI.startsWith(contextPath.concat("/api/liferay"))) {
096                            throw new AuthException();
097                    }
098                    else {
099                            Map<String, String[]> headerMap = new HashMap<String, String[]>();
100    
101                            Enumeration<String> enu1 = request.getHeaderNames();
102    
103                            while (enu1.hasMoreElements()) {
104                                    String name = enu1.nextElement();
105    
106                                    Enumeration<String> enu2 = request.getHeaders(name);
107    
108                                    List<String> headers = new ArrayList<String>();
109    
110                                    while (enu2.hasMoreElements()) {
111                                            String value = enu2.nextElement();
112    
113                                            headers.add(value);
114                                    }
115    
116                                    headerMap.put(
117                                            name, headers.toArray(new String[headers.size()]));
118                            }
119    
120                            Map<String, String[]> parameterMap = request.getParameterMap();
121                            Map<String, Object> resultsMap = new HashMap<String, Object>();
122    
123                            if (Validator.isNull(authType)) {
124                                    authType = company.getAuthType();
125                            }
126    
127                            int authResult = Authenticator.FAILURE;
128    
129                            if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
130                                    authResult = UserLocalServiceUtil.authenticateByEmailAddress(
131                                            company.getCompanyId(), login, password, headerMap,
132                                            parameterMap, resultsMap);
133    
134                                    userId = MapUtil.getLong(resultsMap, "userId", userId);
135                            }
136                            else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
137                                    authResult = UserLocalServiceUtil.authenticateByScreenName(
138                                            company.getCompanyId(), login, password, headerMap,
139                                            parameterMap, resultsMap);
140    
141                                    userId = MapUtil.getLong(resultsMap, "userId", userId);
142                            }
143                            else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
144                                    authResult = UserLocalServiceUtil.authenticateByUserId(
145                                            company.getCompanyId(), userId, password, headerMap,
146                                            parameterMap, resultsMap);
147                            }
148    
149                            if (authResult != Authenticator.SUCCESS) {
150                                    throw new AuthException();
151                            }
152                    }
153    
154                    return userId;
155            }
156    
157            public static String getEmailFromAddress(
158                            PortletPreferences preferences, long companyId)
159                    throws SystemException {
160    
161                    return PortalUtil.getEmailFromAddress(
162                            preferences, companyId, PropsValues.LOGIN_EMAIL_FROM_ADDRESS);
163            }
164    
165            public static String getEmailFromName(
166                            PortletPreferences preferences, long companyId)
167                    throws SystemException {
168    
169                    return PortalUtil.getEmailFromName(
170                            preferences, companyId, PropsValues.LOGIN_EMAIL_FROM_NAME);
171            }
172    
173            public static String getLogin(
174                            HttpServletRequest request, String paramName, Company company)
175                    throws SystemException {
176    
177                    String login = request.getParameter(paramName);
178    
179                    if ((login == null) || login.equals(StringPool.NULL)) {
180                            login = GetterUtil.getString(
181                                    CookieKeys.getCookie(request, CookieKeys.LOGIN, false));
182    
183                            if (PropsValues.COMPANY_LOGIN_PREPOPULATE_DOMAIN &&
184                                    Validator.isNull(login) &&
185                                    company.getAuthType().equals(CompanyConstants.AUTH_TYPE_EA)) {
186    
187                                    login = "@" + company.getMx();
188                            }
189                    }
190    
191                    return login;
192            }
193    
194            public static PortletURL getLoginURL(HttpServletRequest request, long plid)
195                    throws PortletModeException, WindowStateException {
196    
197                    PortletURL portletURL = PortletURLFactoryUtil.create(
198                            request, PortletKeys.LOGIN, plid, PortletRequest.RENDER_PHASE);
199    
200                    portletURL.setParameter("saveLastPath", Boolean.FALSE.toString());
201                    portletURL.setParameter("struts_action", "/login/login");
202                    portletURL.setPortletMode(PortletMode.VIEW);
203                    portletURL.setWindowState(WindowState.MAXIMIZED);
204    
205                    return portletURL;
206            }
207    
208            public static void login(
209                            HttpServletRequest request, HttpServletResponse response,
210                            String login, String password, boolean rememberMe, String authType)
211                    throws Exception {
212    
213                    CookieKeys.validateSupportCookie(request);
214    
215                    HttpSession session = request.getSession();
216    
217                    Company company = PortalUtil.getCompany(request);
218    
219                    long userId = getAuthenticatedUserId(
220                            request, login, password, authType);
221    
222                    if (!PropsValues.AUTH_SIMULTANEOUS_LOGINS) {
223                            signOutSimultaneousLogins(userId);
224                    }
225    
226                    if (PropsValues.SESSION_ENABLE_PHISHING_PROTECTION) {
227                            session = renewSession(request, session);
228                    }
229    
230                    // Set cookies
231    
232                    String domain = CookieKeys.getDomain(request);
233    
234                    User user = UserLocalServiceUtil.getUserById(userId);
235    
236                    String userIdString = String.valueOf(userId);
237    
238                    session.setAttribute("j_username", userIdString);
239    
240                    if (PropsValues.PORTAL_JAAS_PLAIN_PASSWORD) {
241                            session.setAttribute("j_password", password);
242                    }
243                    else {
244                            session.setAttribute("j_password", user.getPassword());
245                    }
246    
247                    session.setAttribute("j_remoteuser", userIdString);
248    
249                    if (PropsValues.SESSION_STORE_PASSWORD) {
250                            session.setAttribute(WebKeys.USER_PASSWORD, password);
251                    }
252    
253                    Cookie companyIdCookie = new Cookie(
254                            CookieKeys.COMPANY_ID, String.valueOf(company.getCompanyId()));
255    
256                    if (Validator.isNotNull(domain)) {
257                            companyIdCookie.setDomain(domain);
258                    }
259    
260                    companyIdCookie.setPath(StringPool.SLASH);
261    
262                    Cookie idCookie = new Cookie(
263                            CookieKeys.ID,
264                            Encryptor.encrypt(company.getKeyObj(), userIdString));
265    
266                    if (Validator.isNotNull(domain)) {
267                            idCookie.setDomain(domain);
268                    }
269    
270                    idCookie.setPath(StringPool.SLASH);
271    
272                    Cookie passwordCookie = new Cookie(
273                            CookieKeys.PASSWORD,
274                            Encryptor.encrypt(company.getKeyObj(), password));
275    
276                    if (Validator.isNotNull(domain)) {
277                            passwordCookie.setDomain(domain);
278                    }
279    
280                    passwordCookie.setPath(StringPool.SLASH);
281    
282                    Cookie rememberMeCookie = new Cookie(
283                            CookieKeys.REMEMBER_ME, Boolean.TRUE.toString());
284    
285                    if (Validator.isNotNull(domain)) {
286                            rememberMeCookie.setDomain(domain);
287                    }
288    
289                    rememberMeCookie.setPath(StringPool.SLASH);
290    
291                    int loginMaxAge = PropsValues.COMPANY_SECURITY_AUTO_LOGIN_MAX_AGE;
292    
293                    String userUUID = userIdString.concat(StringPool.PERIOD).concat(
294                            String.valueOf(System.nanoTime()));
295    
296                    Cookie userUUIDCookie = new Cookie(
297                            CookieKeys.USER_UUID,
298                            Encryptor.encrypt(company.getKeyObj(), userUUID));
299    
300                    userUUIDCookie.setPath(StringPool.SLASH);
301    
302                    session.setAttribute(WebKeys.USER_UUID, userUUID);
303    
304                    if (PropsValues.SESSION_DISABLED) {
305                            rememberMe = true;
306                    }
307    
308                    if (rememberMe) {
309                            companyIdCookie.setMaxAge(loginMaxAge);
310                            idCookie.setMaxAge(loginMaxAge);
311                            passwordCookie.setMaxAge(loginMaxAge);
312                            rememberMeCookie.setMaxAge(loginMaxAge);
313                            userUUIDCookie.setMaxAge(loginMaxAge);
314                    }
315                    else {
316    
317                            // This was explicitly changed from 0 to -1 so that the cookie lasts
318                            // as long as the browser. This allows an external servlet wrapped
319                            // in AutoLoginFilter to work throughout the client connection. The
320                            // cookies ARE removed on an actual logout, so there is no security
321                            // issue. See LEP-4678 and LEP-5177.
322    
323                            companyIdCookie.setMaxAge(-1);
324                            idCookie.setMaxAge(-1);
325                            passwordCookie.setMaxAge(-1);
326                            rememberMeCookie.setMaxAge(0);
327                            userUUIDCookie.setMaxAge(-1);
328                    }
329    
330                    Cookie loginCookie = new Cookie(CookieKeys.LOGIN, login);
331    
332                    if (Validator.isNotNull(domain)) {
333                            loginCookie.setDomain(domain);
334                    }
335    
336                    loginCookie.setMaxAge(loginMaxAge);
337                    loginCookie.setPath(StringPool.SLASH);
338    
339                    Cookie screenNameCookie = new Cookie(
340                            CookieKeys.SCREEN_NAME,
341                            Encryptor.encrypt(company.getKeyObj(), user.getScreenName()));
342    
343                    if (Validator.isNotNull(domain)) {
344                            screenNameCookie.setDomain(domain);
345                    }
346    
347                    screenNameCookie.setMaxAge(loginMaxAge);
348                    screenNameCookie.setPath(StringPool.SLASH);
349    
350                    boolean secure = request.isSecure();
351    
352                    if (secure && !PropsValues.COMPANY_SECURITY_AUTH_REQUIRES_HTTPS &&
353                            !StringUtil.equalsIgnoreCase(
354                                    Http.HTTPS, PropsValues.WEB_SERVER_PROTOCOL)) {
355    
356                            Boolean httpsInitial = (Boolean)session.getAttribute(
357                                    WebKeys.HTTPS_INITIAL);
358    
359                            if ((httpsInitial == null) || !httpsInitial.booleanValue()) {
360                                    secure = false;
361                            }
362                    }
363    
364                    CookieKeys.addCookie(request, response, companyIdCookie, secure);
365                    CookieKeys.addCookie(request, response, idCookie, secure);
366                    CookieKeys.addCookie(request, response, userUUIDCookie, secure);
367    
368                    if (rememberMe) {
369                            CookieKeys.addCookie(request, response, loginCookie, secure);
370                            CookieKeys.addCookie(request, response, passwordCookie, secure);
371                            CookieKeys.addCookie(request, response, rememberMeCookie, secure);
372                            CookieKeys.addCookie(request, response, screenNameCookie, secure);
373                    }
374    
375                    AuthenticatedUserUUIDStoreUtil.register(userUUID);
376            }
377    
378            public static HttpSession renewSession(
379                            HttpServletRequest request, HttpSession session)
380                    throws Exception {
381    
382                    // Invalidate the previous session to prevent phishing
383    
384                    String[] protectedAttributeNames =
385                            PropsValues.SESSION_PHISHING_PROTECTED_ATTRIBUTES;
386    
387                    Map<String, Object> protectedAttributes = new HashMap<String, Object>();
388    
389                    for (String protectedAttributeName : protectedAttributeNames) {
390                            Object protectedAttributeValue = session.getAttribute(
391                                    protectedAttributeName);
392    
393                            if (protectedAttributeValue == null) {
394                                    continue;
395                            }
396    
397                            protectedAttributes.put(
398                                    protectedAttributeName, protectedAttributeValue);
399                    }
400    
401                    try {
402                            session.invalidate();
403                    }
404                    catch (IllegalStateException ise) {
405    
406                            // This only happens in Geronimo
407    
408                            if (_log.isWarnEnabled()) {
409                                    _log.warn(ise.getMessage());
410                            }
411                    }
412    
413                    session = request.getSession(true);
414    
415                    for (String protectedAttributeName : protectedAttributeNames) {
416                            Object protectedAttributeValue = protectedAttributes.get(
417                                    protectedAttributeName);
418    
419                            if (protectedAttributeValue == null) {
420                                    continue;
421                            }
422    
423                            session.setAttribute(
424                                    protectedAttributeName, protectedAttributeValue);
425                    }
426    
427                    return session;
428            }
429    
430            public static void sendPassword(ActionRequest actionRequest)
431                    throws Exception {
432    
433                    String toAddress = ParamUtil.getString(actionRequest, "emailAddress");
434    
435                    sendPassword(actionRequest, null, null, toAddress, null, null);
436            }
437    
438            public static void sendPassword(
439                            ActionRequest actionRequest, String fromName, String fromAddress,
440                            String toAddress, String subject, String body)
441                    throws Exception {
442    
443                    HttpServletRequest request = PortalUtil.getHttpServletRequest(
444                            actionRequest);
445    
446                    ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(
447                            WebKeys.THEME_DISPLAY);
448    
449                    Company company = themeDisplay.getCompany();
450    
451                    if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
452                            return;
453                    }
454    
455                    ServiceContext serviceContext = ServiceContextFactory.getInstance(
456                            User.class.getName(), actionRequest);
457    
458                    UserLocalServiceUtil.sendPassword(
459                            company.getCompanyId(), toAddress, fromName, fromAddress, subject,
460                            body, serviceContext);
461    
462                    SessionMessages.add(actionRequest, "requestProcessed", toAddress);
463            }
464    
465            public static void signOutSimultaneousLogins(long userId) throws Exception {
466                    long companyId = CompanyLocalServiceUtil.getCompanyIdByUserId(userId);
467    
468                    Map<String, UserTracker> sessionUsers = LiveUsers.getSessionUsers(
469                            companyId);
470    
471                    List<UserTracker> userTrackers = new ArrayList<UserTracker>(
472                            sessionUsers.values());
473    
474                    for (UserTracker userTracker : userTrackers) {
475                            if (userId != userTracker.getUserId()) {
476                                    continue;
477                            }
478    
479                            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
480    
481                            ClusterNode clusterNode = ClusterExecutorUtil.getLocalClusterNode();
482    
483                            if (clusterNode != null) {
484                                    jsonObject.put("clusterNodeId", clusterNode.getClusterNodeId());
485                            }
486    
487                            jsonObject.put("command", "signOut");
488                            jsonObject.put("companyId", companyId);
489                            jsonObject.put("sessionId", userTracker.getSessionId());
490                            jsonObject.put("userId", userId);
491    
492                            MessageBusUtil.sendMessage(
493                                    DestinationNames.LIVE_USERS, jsonObject.toString());
494                    }
495            }
496    
497            private static Log _log = LogFactoryUtil.getLog(LoginUtil.class);
498    
499    }