1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    *
5    *
6    *
7    * The contents of this file are subject to the terms of the Liferay Enterprise
8    * Subscription License ("License"). You may not use this file except in
9    * compliance with the License. You can obtain a copy of the License by
10   * contacting Liferay, Inc. See the License for the specific language governing
11   * permissions and limitations under the License, including but not limited to
12   * distribution rights 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.theme.ThemeDisplay;
41  import com.liferay.portal.util.CookieKeys;
42  import com.liferay.portal.util.PortalUtil;
43  import com.liferay.portal.util.PortletKeys;
44  import com.liferay.portal.util.PropsValues;
45  import com.liferay.portal.util.WebKeys;
46  import com.liferay.portlet.PortletURLImpl;
47  import com.liferay.util.Encryptor;
48  
49  import java.util.ArrayList;
50  import java.util.Enumeration;
51  import java.util.HashMap;
52  import java.util.List;
53  import java.util.Map;
54  
55  import javax.portlet.ActionRequest;
56  import javax.portlet.PortletMode;
57  import javax.portlet.PortletModeException;
58  import javax.portlet.PortletRequest;
59  import javax.portlet.PortletURL;
60  import javax.portlet.WindowState;
61  import javax.portlet.WindowStateException;
62  
63  import javax.servlet.http.Cookie;
64  import javax.servlet.http.HttpServletRequest;
65  import javax.servlet.http.HttpServletResponse;
66  import javax.servlet.http.HttpSession;
67  
68  /**
69   * <a href="LoginUtil.java.html"><b><i>View Source</i></b></a>
70   *
71   * @author Brian Wing Shun Chan
72   * @author Scott Lee
73   */
74  public class LoginUtil {
75  
76      public static String getLogin(
77              HttpServletRequest request, String paramName, Company company)
78          throws SystemException {
79  
80          String login = request.getParameter(paramName);
81  
82          if ((login == null) || (login.equals(StringPool.NULL))) {
83              login = GetterUtil.getString(
84                  CookieKeys.getCookie(request, CookieKeys.LOGIN));
85  
86              if (PropsValues.COMPANY_LOGIN_PREPOPULATE_DOMAIN &&
87                  Validator.isNull(login) &&
88                  company.getAuthType().equals(CompanyConstants.AUTH_TYPE_EA)) {
89  
90                  login = "@" + company.getMx();
91              }
92          }
93  
94          return login;
95      }
96  
97      public static PortletURL getLoginURL(
98              HttpServletRequest request, long plid)
99          throws PortletModeException, WindowStateException {
100 
101         PortletURL portletURL = new PortletURLImpl(
102             request, PortletKeys.LOGIN, plid, PortletRequest.RENDER_PHASE);
103 
104         portletURL.setWindowState(WindowState.MAXIMIZED);
105         portletURL.setPortletMode(PortletMode.VIEW);
106 
107         portletURL.setParameter("saveLastPath", "0");
108         portletURL.setParameter("struts_action", "/login/login");
109 
110         return portletURL;
111     }
112 
113     public static void login(
114             HttpServletRequest request, HttpServletResponse response,
115             String login, String password, boolean rememberMe, String authType)
116         throws Exception {
117 
118         CookieKeys.validateSupportCookie(request);
119 
120         HttpSession session = request.getSession();
121 
122         long userId = GetterUtil.getLong(login);
123 
124         int authResult = Authenticator.FAILURE;
125 
126         Company company = PortalUtil.getCompany(request);
127 
128         Map<String, String[]> headerMap = new HashMap<String, String[]>();
129 
130         Enumeration<String> enu1 = request.getHeaderNames();
131 
132         while (enu1.hasMoreElements()) {
133             String name = enu1.nextElement();
134 
135             Enumeration<String> enu2 = request.getHeaders(name);
136 
137             List<String> headers = new ArrayList<String>();
138 
139             while (enu2.hasMoreElements()) {
140                 String value = enu2.nextElement();
141 
142                 headers.add(value);
143             }
144 
145             headerMap.put(name, headers.toArray(new String[headers.size()]));
146         }
147 
148         Map<String, String[]> parameterMap = request.getParameterMap();
149 
150         if (Validator.isNull(authType)) {
151             authType = company.getAuthType();
152         }
153 
154         if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
155             authResult = UserLocalServiceUtil.authenticateByEmailAddress(
156                 company.getCompanyId(), login, password, headerMap,
157                 parameterMap);
158 
159             userId = UserLocalServiceUtil.getUserIdByEmailAddress(
160                 company.getCompanyId(), login);
161         }
162         else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
163             authResult = UserLocalServiceUtil.authenticateByScreenName(
164                 company.getCompanyId(), login, password, headerMap,
165                 parameterMap);
166 
167             userId = UserLocalServiceUtil.getUserIdByScreenName(
168                 company.getCompanyId(), login);
169         }
170         else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
171             authResult = UserLocalServiceUtil.authenticateByUserId(
172                 company.getCompanyId(), userId, password, headerMap,
173                 parameterMap);
174         }
175 
176         if (authResult == Authenticator.SUCCESS) {
177             if (PropsValues.SESSION_ENABLE_PHISHING_PROTECTION) {
178 
179                 // Invalidate the previous session to prevent phishing
180 
181                 String[] protectedAttributeNames =
182                     PropsValues.SESSION_PHISHING_PROTECTED_ATTRIBUTES;
183 
184                 Map<String, Object> protectedAttributes =
185                     new HashMap<String, Object>();
186 
187                 for (String protectedAttributeName : protectedAttributeNames) {
188                     Object protectedAttributeValue = session.getAttribute(
189                         protectedAttributeName);
190 
191                     if (protectedAttributeValue == null) {
192                         continue;
193                     }
194 
195                     protectedAttributes.put(
196                         protectedAttributeName, protectedAttributeValue);
197                 }
198 
199                 try {
200                     session.invalidate();
201                 }
202                 catch (IllegalStateException ise) {
203 
204                     // This only happens in Geronimo
205 
206                     if (_log.isWarnEnabled()) {
207                         _log.warn(ise.getMessage());
208                     }
209                 }
210 
211                 session = request.getSession(true);
212 
213                 for (String protectedAttributeName : protectedAttributeNames) {
214                     Object protectedAttributeValue = protectedAttributes.get(
215                         protectedAttributeName);
216 
217                     if (protectedAttributeValue == null) {
218                         continue;
219                     }
220 
221                     session.setAttribute(
222                         protectedAttributeName, protectedAttributeValue);
223                 }
224             }
225 
226             // Set cookies
227 
228             String domain = CookieKeys.getDomain(request);
229 
230             User user = UserLocalServiceUtil.getUserById(userId);
231 
232             String userIdString = String.valueOf(userId);
233 
234             session.setAttribute("j_username", userIdString);
235             session.setAttribute("j_password", user.getPassword());
236             session.setAttribute("j_remoteuser", userIdString);
237 
238             session.setAttribute(WebKeys.USER_PASSWORD, password);
239 
240             Cookie companyIdCookie = new Cookie(
241                 CookieKeys.COMPANY_ID, String.valueOf(company.getCompanyId()));
242 
243             if (Validator.isNotNull(domain)) {
244                 companyIdCookie.setDomain(domain);
245             }
246 
247             companyIdCookie.setPath(StringPool.SLASH);
248 
249             Cookie idCookie = new Cookie(
250                 CookieKeys.ID,
251                 UserLocalServiceUtil.encryptUserId(userIdString));
252 
253             if (Validator.isNotNull(domain)) {
254                 idCookie.setDomain(domain);
255             }
256 
257             idCookie.setPath(StringPool.SLASH);
258 
259             Cookie passwordCookie = new Cookie(
260                 CookieKeys.PASSWORD,
261                 Encryptor.encrypt(company.getKeyObj(), password));
262 
263             if (Validator.isNotNull(domain)) {
264                 passwordCookie.setDomain(domain);
265             }
266 
267             passwordCookie.setPath(StringPool.SLASH);
268 
269             Cookie rememberMeCookie = new Cookie(
270                 CookieKeys.REMEMBER_ME, Boolean.TRUE.toString());
271 
272             if (Validator.isNotNull(domain)) {
273                 rememberMeCookie.setDomain(domain);
274             }
275 
276             rememberMeCookie.setPath(StringPool.SLASH);
277 
278             int loginMaxAge = PropsValues.COMPANY_SECURITY_AUTO_LOGIN_MAX_AGE;
279 
280             if (PropsValues.SESSION_DISABLED) {
281                 rememberMe = true;
282             }
283 
284             if (rememberMe) {
285                 companyIdCookie.setMaxAge(loginMaxAge);
286                 idCookie.setMaxAge(loginMaxAge);
287                 passwordCookie.setMaxAge(loginMaxAge);
288                 rememberMeCookie.setMaxAge(loginMaxAge);
289             }
290             else {
291 
292                 // This was explicitly changed from 0 to -1 so that the cookie
293                 // lasts as long as the browser. This allows an external servlet
294                 // wrapped in AutoLoginFilter to work throughout the client
295                 // connection. The cookies ARE removed on an actual logout, so
296                 // there is no security issue. See LEP-4678 and LEP-5177.
297 
298                 companyIdCookie.setMaxAge(-1);
299                 idCookie.setMaxAge(-1);
300                 passwordCookie.setMaxAge(-1);
301                 rememberMeCookie.setMaxAge(0);
302             }
303 
304             Cookie loginCookie = new Cookie(CookieKeys.LOGIN, login);
305 
306             if (Validator.isNotNull(domain)) {
307                 loginCookie.setDomain(domain);
308             }
309 
310             loginCookie.setMaxAge(loginMaxAge);
311             loginCookie.setPath(StringPool.SLASH);
312 
313             Cookie screenNameCookie = new Cookie(
314                 CookieKeys.SCREEN_NAME,
315                 Encryptor.encrypt(company.getKeyObj(), user.getScreenName()));
316 
317             if (Validator.isNotNull(domain)) {
318                 screenNameCookie.setDomain(domain);
319             }
320 
321             screenNameCookie.setMaxAge(loginMaxAge);
322             screenNameCookie.setPath(StringPool.SLASH);
323 
324             boolean secure = request.isSecure();
325 
326             if (secure) {
327                 Boolean httpsInitial = (Boolean)session.getAttribute(
328                     WebKeys.HTTPS_INITIAL);
329 
330                 if ((httpsInitial == null) || !httpsInitial.booleanValue()) {
331                     secure = false;
332                 }
333             }
334 
335             CookieKeys.addCookie(request, response, companyIdCookie, secure);
336             CookieKeys.addCookie(request, response, idCookie, secure);
337             CookieKeys.addCookie(request, response, passwordCookie, secure);
338             CookieKeys.addCookie(request, response, rememberMeCookie, secure);
339             CookieKeys.addCookie(request, response, loginCookie, secure);
340             CookieKeys.addCookie(request, response, screenNameCookie, secure);
341         }
342         else {
343             throw new AuthException();
344         }
345     }
346 
347     public static void sendPassword(ActionRequest actionRequest)
348         throws Exception {
349 
350         String toAddress = ParamUtil.getString(actionRequest, "emailAddress");
351 
352         sendPassword(actionRequest, null, null, toAddress, null, null);
353     }
354 
355     public static void sendPassword(
356             ActionRequest actionRequest, String fromName, String fromAddress,
357             String toAddress, String subject, String body)
358         throws Exception {
359 
360         HttpServletRequest request = PortalUtil.getHttpServletRequest(
361             actionRequest);
362 
363         ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(
364             WebKeys.THEME_DISPLAY);
365 
366         Company company = themeDisplay.getCompany();
367 
368         if (!company.isSendPassword()) {
369             return;
370         }
371 
372         String remoteAddr = request.getRemoteAddr();
373         String remoteHost = request.getRemoteHost();
374         String userAgent = request.getHeader(HttpHeaders.USER_AGENT);
375 
376         UserLocalServiceUtil.sendPassword(
377             company.getCompanyId(), toAddress, remoteAddr, remoteHost,
378             userAgent, fromName, fromAddress, subject, body);
379 
380         SessionMessages.add(actionRequest, "request_processed", toAddress);
381     }
382 
383     private static Log _log = LogFactoryUtil.getLog(LoginUtil.class);
384 
385 }