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