1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portlet.login.util;
24  
25  import com.liferay.portal.SystemException;
26  import com.liferay.portal.kernel.log.Log;
27  import com.liferay.portal.kernel.log.LogFactoryUtil;
28  import com.liferay.portal.kernel.servlet.HttpHeaders;
29  import com.liferay.portal.kernel.servlet.SessionMessages;
30  import com.liferay.portal.kernel.util.GetterUtil;
31  import com.liferay.portal.kernel.util.ParamUtil;
32  import com.liferay.portal.kernel.util.StringPool;
33  import com.liferay.portal.kernel.util.Validator;
34  import com.liferay.portal.model.Company;
35  import com.liferay.portal.model.CompanyConstants;
36  import com.liferay.portal.model.User;
37  import com.liferay.portal.security.auth.AuthException;
38  import com.liferay.portal.security.auth.Authenticator;
39  import com.liferay.portal.service.UserLocalServiceUtil;
40  import com.liferay.portal.struts.LastPath;
41  import com.liferay.portal.theme.ThemeDisplay;
42  import com.liferay.portal.util.CookieKeys;
43  import com.liferay.portal.util.PortalUtil;
44  import com.liferay.portal.util.PortletKeys;
45  import com.liferay.portal.util.PropsValues;
46  import com.liferay.portal.util.WebKeys;
47  import com.liferay.portlet.PortletURLImpl;
48  import com.liferay.util.Encryptor;
49  
50  import java.util.ArrayList;
51  import java.util.Enumeration;
52  import java.util.HashMap;
53  import java.util.List;
54  import java.util.Map;
55  
56  import javax.portlet.ActionRequest;
57  import javax.portlet.PortletMode;
58  import javax.portlet.PortletModeException;
59  import javax.portlet.PortletRequest;
60  import javax.portlet.PortletURL;
61  import javax.portlet.WindowState;
62  import javax.portlet.WindowStateException;
63  
64  import javax.servlet.http.Cookie;
65  import javax.servlet.http.HttpServletRequest;
66  import javax.servlet.http.HttpServletResponse;
67  import javax.servlet.http.HttpSession;
68  
69  /**
70   * <a href="LoginUtil.java.html"><b><i>View Source</i></b></a>
71   *
72   * @author Brian Wing Shun Chan
73   * @author Scott Lee
74   *
75   */
76  public class LoginUtil {
77  
78      public static String getLogin(
79              HttpServletRequest request, String paramName, Company company)
80          throws SystemException {
81  
82          String login = request.getParameter(paramName);
83  
84          if ((login == null) || (login.equals(StringPool.NULL))) {
85              login = GetterUtil.getString(
86                  CookieKeys.getCookie(request, CookieKeys.LOGIN));
87  
88              if (PropsValues.COMPANY_LOGIN_PREPOPULATE_DOMAIN &&
89                  Validator.isNull(login) &&
90                  company.getAuthType().equals(CompanyConstants.AUTH_TYPE_EA)) {
91  
92                  login = "@" + company.getMx();
93              }
94          }
95  
96          return login;
97      }
98  
99      public static PortletURL getLoginURL(
100             HttpServletRequest request, long plid)
101         throws PortletModeException, WindowStateException {
102 
103         PortletURL portletURL = new PortletURLImpl(
104             request, PortletKeys.LOGIN, plid, PortletRequest.RENDER_PHASE);
105 
106         portletURL.setWindowState(WindowState.MAXIMIZED);
107         portletURL.setPortletMode(PortletMode.VIEW);
108 
109         portletURL.setParameter("saveLastPath", "0");
110         portletURL.setParameter("struts_action", "/login/login");
111 
112         return portletURL;
113     }
114 
115     public static void login(
116             HttpServletRequest request, HttpServletResponse response,
117             String login, String password, boolean rememberMe, String authType)
118         throws Exception {
119 
120         CookieKeys.validateSupportCookie(request);
121 
122         HttpSession session = request.getSession();
123 
124         long userId = GetterUtil.getLong(login);
125 
126         int authResult = Authenticator.FAILURE;
127 
128         Company company = PortalUtil.getCompany(request);
129 
130         Map<String, String[]> headerMap = new HashMap<String, String[]>();
131 
132         Enumeration<String> enu1 = request.getHeaderNames();
133 
134         while (enu1.hasMoreElements()) {
135             String name = enu1.nextElement();
136 
137             Enumeration<String> enu2 = request.getHeaders(name);
138 
139             List<String> headers = new ArrayList<String>();
140 
141             while (enu2.hasMoreElements()) {
142                 String value = enu2.nextElement();
143 
144                 headers.add(value);
145             }
146 
147             headerMap.put(name, headers.toArray(new String[headers.size()]));
148         }
149 
150         Map<String, String[]> parameterMap = request.getParameterMap();
151 
152         if (Validator.isNull(authType)) {
153             authType = company.getAuthType();
154         }
155 
156         if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
157             authResult = UserLocalServiceUtil.authenticateByEmailAddress(
158                 company.getCompanyId(), login, password, headerMap,
159                 parameterMap);
160 
161             userId = UserLocalServiceUtil.getUserIdByEmailAddress(
162                 company.getCompanyId(), login);
163         }
164         else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
165             authResult = UserLocalServiceUtil.authenticateByScreenName(
166                 company.getCompanyId(), login, password, headerMap,
167                 parameterMap);
168 
169             userId = UserLocalServiceUtil.getUserIdByScreenName(
170                 company.getCompanyId(), login);
171         }
172         else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
173             authResult = UserLocalServiceUtil.authenticateByUserId(
174                 company.getCompanyId(), userId, password, headerMap,
175                 parameterMap);
176         }
177 
178         if (authResult == Authenticator.SUCCESS) {
179             if (PropsValues.SESSION_ENABLE_PHISHING_PROTECTION) {
180 
181                 // Invalidate the previous session to prevent phishing
182 
183                 Boolean httpsInitial = (Boolean)session.getAttribute(
184                     WebKeys.HTTPS_INITIAL);
185 
186                 LastPath lastPath = (LastPath)session.getAttribute(
187                     WebKeys.LAST_PATH);
188 
189                 try {
190                     session.invalidate();
191                 }
192                 catch (IllegalStateException ise) {
193 
194                     // This only happens in Geronimo
195 
196                     if (_log.isWarnEnabled()) {
197                         _log.warn(ise.getMessage());
198                     }
199                 }
200 
201                 session = request.getSession(true);
202 
203                 if (httpsInitial != null) {
204                     session.setAttribute(WebKeys.HTTPS_INITIAL, httpsInitial);
205                 }
206 
207                 if (lastPath != null) {
208                     session.setAttribute(WebKeys.LAST_PATH, lastPath);
209                 }
210             }
211 
212             // Set cookies
213 
214             String domain = CookieKeys.getDomain(request);
215 
216             User user = UserLocalServiceUtil.getUserById(userId);
217 
218             String userIdString = String.valueOf(userId);
219 
220             session.setAttribute("j_username", userIdString);
221             session.setAttribute("j_password", user.getPassword());
222             session.setAttribute("j_remoteuser", userIdString);
223 
224             session.setAttribute(WebKeys.USER_PASSWORD, password);
225 
226             Cookie companyIdCookie = new Cookie(
227                 CookieKeys.COMPANY_ID, String.valueOf(company.getCompanyId()));
228 
229             if (Validator.isNotNull(domain)) {
230                 companyIdCookie.setDomain(domain);
231             }
232 
233             companyIdCookie.setPath(StringPool.SLASH);
234 
235             Cookie idCookie = new Cookie(
236                 CookieKeys.ID,
237                 UserLocalServiceUtil.encryptUserId(userIdString));
238 
239             if (Validator.isNotNull(domain)) {
240                 idCookie.setDomain(domain);
241             }
242 
243             idCookie.setPath(StringPool.SLASH);
244 
245             Cookie passwordCookie = new Cookie(
246                 CookieKeys.PASSWORD,
247                 Encryptor.encrypt(company.getKeyObj(), password));
248 
249             if (Validator.isNotNull(domain)) {
250                 passwordCookie.setDomain(domain);
251             }
252 
253             passwordCookie.setPath(StringPool.SLASH);
254 
255             Cookie rememberMeCookie = new Cookie(
256                 CookieKeys.REMEMBER_ME, Boolean.TRUE.toString());
257 
258             if (Validator.isNotNull(domain)) {
259                 rememberMeCookie.setDomain(domain);
260             }
261 
262             rememberMeCookie.setPath(StringPool.SLASH);
263 
264             int loginMaxAge = PropsValues.COMPANY_SECURITY_AUTO_LOGIN_MAX_AGE;
265 
266             if (PropsValues.SESSION_DISABLED) {
267                 rememberMe = true;
268             }
269 
270             if (rememberMe) {
271                 companyIdCookie.setMaxAge(loginMaxAge);
272                 idCookie.setMaxAge(loginMaxAge);
273                 passwordCookie.setMaxAge(loginMaxAge);
274                 rememberMeCookie.setMaxAge(loginMaxAge);
275             }
276             else {
277 
278                 // This was explicitly changed from 0 to -1 so that the cookie
279                 // lasts as long as the browser. This allows an external servlet
280                 // wrapped in AutoLoginFilter to work throughout the client
281                 // connection. The cookies ARE removed on an actual logout, so
282                 // there is no security issue. See LEP-4678 and LEP-5177.
283 
284                 companyIdCookie.setMaxAge(-1);
285                 idCookie.setMaxAge(-1);
286                 passwordCookie.setMaxAge(-1);
287                 rememberMeCookie.setMaxAge(0);
288             }
289 
290             Cookie loginCookie = new Cookie(CookieKeys.LOGIN, login);
291 
292             if (Validator.isNotNull(domain)) {
293                 loginCookie.setDomain(domain);
294             }
295 
296             loginCookie.setMaxAge(loginMaxAge);
297             loginCookie.setPath(StringPool.SLASH);
298 
299             Cookie screenNameCookie = new Cookie(
300                 CookieKeys.SCREEN_NAME,
301                 Encryptor.encrypt(company.getKeyObj(), user.getScreenName()));
302 
303             if (Validator.isNotNull(domain)) {
304                 screenNameCookie.setDomain(domain);
305             }
306 
307             screenNameCookie.setMaxAge(loginMaxAge);
308             screenNameCookie.setPath(StringPool.SLASH);
309 
310             boolean secure = request.isSecure();
311 
312             if (secure) {
313                 Boolean httpsInitial = (Boolean)session.getAttribute(
314                     WebKeys.HTTPS_INITIAL);
315 
316                 if ((httpsInitial == null) || !httpsInitial.booleanValue()) {
317                     secure = false;
318                 }
319             }
320 
321             CookieKeys.addCookie(request, response, companyIdCookie, secure);
322             CookieKeys.addCookie(request, response, idCookie, secure);
323             CookieKeys.addCookie(request, response, passwordCookie, secure);
324             CookieKeys.addCookie(request, response, rememberMeCookie, secure);
325             CookieKeys.addCookie(request, response, loginCookie, secure);
326             CookieKeys.addCookie(request, response, screenNameCookie, secure);
327         }
328         else {
329             throw new AuthException();
330         }
331     }
332 
333     public static void sendPassword(ActionRequest actionRequest)
334         throws Exception {
335 
336         sendPassword(actionRequest, null, null, null, null);
337     }
338 
339     public static void sendPassword(
340             ActionRequest actionRequest, String fromName,
341             String fromAddress, String subject, String body)
342         throws Exception {
343 
344         HttpServletRequest request = PortalUtil.getHttpServletRequest(
345             actionRequest);
346 
347         ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(
348             WebKeys.THEME_DISPLAY);
349 
350         Company company = themeDisplay.getCompany();
351 
352         if (!company.isSendPassword()) {
353             return;
354         }
355 
356         String emailAddress = ParamUtil.getString(request, "emailAddress");
357 
358         String remoteAddr = request.getRemoteAddr();
359         String remoteHost = request.getRemoteHost();
360         String userAgent = request.getHeader(HttpHeaders.USER_AGENT);
361 
362         UserLocalServiceUtil.sendPassword(
363             company.getCompanyId(), emailAddress, remoteAddr, remoteHost,
364             userAgent, fromName, fromAddress, subject, body);
365 
366         SessionMessages.add(actionRequest, "request_processed", emailAddress);
367     }
368 
369     private static Log _log = LogFactoryUtil.getLog(LoginUtil.class);
370 
371 }