1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.portlet.login.util;
16  
17  import com.liferay.portal.kernel.exception.SystemException;
18  import com.liferay.portal.kernel.log.Log;
19  import com.liferay.portal.kernel.log.LogFactoryUtil;
20  import com.liferay.portal.kernel.servlet.HttpHeaders;
21  import com.liferay.portal.kernel.servlet.SessionMessages;
22  import com.liferay.portal.kernel.util.GetterUtil;
23  import com.liferay.portal.kernel.util.ParamUtil;
24  import com.liferay.portal.kernel.util.StringPool;
25  import com.liferay.portal.kernel.util.Validator;
26  import com.liferay.portal.model.Company;
27  import com.liferay.portal.model.CompanyConstants;
28  import com.liferay.portal.model.User;
29  import com.liferay.portal.security.auth.AuthException;
30  import com.liferay.portal.security.auth.Authenticator;
31  import com.liferay.portal.service.ServiceContext;
32  import com.liferay.portal.service.ServiceContextFactory;
33  import com.liferay.portal.service.UserLocalServiceUtil;
34  import com.liferay.portal.theme.ThemeDisplay;
35  import com.liferay.portal.util.CookieKeys;
36  import com.liferay.portal.util.PortalUtil;
37  import com.liferay.portal.util.PortletKeys;
38  import com.liferay.portal.util.PropsValues;
39  import com.liferay.portal.util.WebKeys;
40  import com.liferay.portlet.PortletURLImpl;
41  import com.liferay.util.Encryptor;
42  
43  import java.util.ArrayList;
44  import java.util.Enumeration;
45  import java.util.HashMap;
46  import java.util.List;
47  import java.util.Map;
48  
49  import javax.portlet.ActionRequest;
50  import javax.portlet.PortletMode;
51  import javax.portlet.PortletModeException;
52  import javax.portlet.PortletRequest;
53  import javax.portlet.PortletURL;
54  import javax.portlet.WindowState;
55  import javax.portlet.WindowStateException;
56  
57  import javax.servlet.http.Cookie;
58  import javax.servlet.http.HttpServletRequest;
59  import javax.servlet.http.HttpServletResponse;
60  import javax.servlet.http.HttpSession;
61  
62  /**
63   * <a href="LoginUtil.java.html"><b><i>View Source</i></b></a>
64   *
65   * @author Brian Wing Shun Chan
66   * @author Scott Lee
67   */
68  public class LoginUtil {
69  
70      public static String getLogin(
71              HttpServletRequest request, String paramName, Company company)
72          throws SystemException {
73  
74          String login = request.getParameter(paramName);
75  
76          if ((login == null) || (login.equals(StringPool.NULL))) {
77              login = GetterUtil.getString(
78                  CookieKeys.getCookie(request, CookieKeys.LOGIN));
79  
80              if (PropsValues.COMPANY_LOGIN_PREPOPULATE_DOMAIN &&
81                  Validator.isNull(login) &&
82                  company.getAuthType().equals(CompanyConstants.AUTH_TYPE_EA)) {
83  
84                  login = "@" + company.getMx();
85              }
86          }
87  
88          return login;
89      }
90  
91      public static PortletURL getLoginURL(
92              HttpServletRequest request, long plid)
93          throws PortletModeException, WindowStateException {
94  
95          PortletURL portletURL = new PortletURLImpl(
96              request, PortletKeys.LOGIN, plid, PortletRequest.RENDER_PHASE);
97  
98          portletURL.setWindowState(WindowState.MAXIMIZED);
99          portletURL.setPortletMode(PortletMode.VIEW);
100 
101         portletURL.setParameter("saveLastPath", "0");
102         portletURL.setParameter("struts_action", "/login/login");
103 
104         return portletURL;
105     }
106 
107     public static void login(
108             HttpServletRequest request, HttpServletResponse response,
109             String login, String password, boolean rememberMe, String authType)
110         throws Exception {
111 
112         CookieKeys.validateSupportCookie(request);
113 
114         HttpSession session = request.getSession();
115 
116         long userId = GetterUtil.getLong(login);
117 
118         int authResult = Authenticator.FAILURE;
119 
120         Company company = PortalUtil.getCompany(request);
121 
122         Map<String, String[]> headerMap = new HashMap<String, String[]>();
123 
124         Enumeration<String> enu1 = request.getHeaderNames();
125 
126         while (enu1.hasMoreElements()) {
127             String name = enu1.nextElement();
128 
129             Enumeration<String> enu2 = request.getHeaders(name);
130 
131             List<String> headers = new ArrayList<String>();
132 
133             while (enu2.hasMoreElements()) {
134                 String value = enu2.nextElement();
135 
136                 headers.add(value);
137             }
138 
139             headerMap.put(name, headers.toArray(new String[headers.size()]));
140         }
141 
142         Map<String, String[]> parameterMap = request.getParameterMap();
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);
152 
153             userId = UserLocalServiceUtil.getUserIdByEmailAddress(
154                 company.getCompanyId(), login);
155         }
156         else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
157             authResult = UserLocalServiceUtil.authenticateByScreenName(
158                 company.getCompanyId(), login, password, headerMap,
159                 parameterMap);
160 
161             userId = UserLocalServiceUtil.getUserIdByScreenName(
162                 company.getCompanyId(), login);
163         }
164         else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
165             authResult = UserLocalServiceUtil.authenticateByUserId(
166                 company.getCompanyId(), userId, password, headerMap,
167                 parameterMap);
168         }
169 
170         if (authResult == Authenticator.SUCCESS) {
171             if (PropsValues.SESSION_ENABLE_PHISHING_PROTECTION) {
172 
173                 // Invalidate the previous session to prevent phishing
174 
175                 String[] protectedAttributeNames =
176                     PropsValues.SESSION_PHISHING_PROTECTED_ATTRIBUTES;
177 
178                 Map<String, Object> protectedAttributes =
179                     new HashMap<String, Object>();
180 
181                 for (String protectedAttributeName : protectedAttributeNames) {
182                     Object protectedAttributeValue = session.getAttribute(
183                         protectedAttributeName);
184 
185                     if (protectedAttributeValue == null) {
186                         continue;
187                     }
188 
189                     protectedAttributes.put(
190                         protectedAttributeName, protectedAttributeValue);
191                 }
192 
193                 try {
194                     session.invalidate();
195                 }
196                 catch (IllegalStateException ise) {
197 
198                     // This only happens in Geronimo
199 
200                     if (_log.isWarnEnabled()) {
201                         _log.warn(ise.getMessage());
202                     }
203                 }
204 
205                 session = request.getSession(true);
206 
207                 for (String protectedAttributeName : protectedAttributeNames) {
208                     Object protectedAttributeValue = protectedAttributes.get(
209                         protectedAttributeName);
210 
211                     if (protectedAttributeValue == null) {
212                         continue;
213                     }
214 
215                     session.setAttribute(
216                         protectedAttributeName, protectedAttributeValue);
217                 }
218             }
219 
220             // Set cookies
221 
222             String domain = CookieKeys.getDomain(request);
223 
224             User user = UserLocalServiceUtil.getUserById(userId);
225 
226             String userIdString = String.valueOf(userId);
227 
228             session.setAttribute("j_username", userIdString);
229             session.setAttribute("j_password", user.getPassword());
230             session.setAttribute("j_remoteuser", userIdString);
231 
232             session.setAttribute(WebKeys.USER_PASSWORD, password);
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 }