001
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
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 Map<String, UserTracker> sessionUsers = LiveUsers.getSessionUsers(
224 company.getCompanyId());
225
226 List<UserTracker> userTrackers = new ArrayList<UserTracker>(
227 sessionUsers.values());
228
229 for (UserTracker userTracker : userTrackers) {
230 if (userId != userTracker.getUserId()) {
231 continue;
232 }
233
234 JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
235
236 ClusterNode clusterNode =
237 ClusterExecutorUtil.getLocalClusterNode();
238
239 if (clusterNode != null) {
240 jsonObject.put(
241 "clusterNodeId", clusterNode.getClusterNodeId());
242 }
243
244 jsonObject.put("command", "signOut");
245
246 long companyId = CompanyLocalServiceUtil.getCompanyIdByUserId(
247 userId);
248
249 jsonObject.put("companyId", companyId);
250 jsonObject.put("sessionId", userTracker.getSessionId());
251 jsonObject.put("userId", userId);
252
253 MessageBusUtil.sendMessage(
254 DestinationNames.LIVE_USERS, jsonObject.toString());
255 }
256 }
257
258 if (PropsValues.SESSION_ENABLE_PHISHING_PROTECTION) {
259 session = renewSession(request, session);
260 }
261
262
263
264 String domain = CookieKeys.getDomain(request);
265
266 User user = UserLocalServiceUtil.getUserById(userId);
267
268 String userIdString = String.valueOf(userId);
269
270 session.setAttribute("j_username", userIdString);
271
272 if (PropsValues.PORTAL_JAAS_PLAIN_PASSWORD) {
273 session.setAttribute("j_password", password);
274 }
275 else {
276 session.setAttribute("j_password", user.getPassword());
277 }
278
279 session.setAttribute("j_remoteuser", userIdString);
280
281 if (PropsValues.SESSION_STORE_PASSWORD) {
282 session.setAttribute(WebKeys.USER_PASSWORD, password);
283 }
284
285 Cookie companyIdCookie = new Cookie(
286 CookieKeys.COMPANY_ID, String.valueOf(company.getCompanyId()));
287
288 if (Validator.isNotNull(domain)) {
289 companyIdCookie.setDomain(domain);
290 }
291
292 companyIdCookie.setPath(StringPool.SLASH);
293
294 Cookie idCookie = new Cookie(
295 CookieKeys.ID,
296 Encryptor.encrypt(company.getKeyObj(), userIdString));
297
298 if (Validator.isNotNull(domain)) {
299 idCookie.setDomain(domain);
300 }
301
302 idCookie.setPath(StringPool.SLASH);
303
304 Cookie passwordCookie = new Cookie(
305 CookieKeys.PASSWORD,
306 Encryptor.encrypt(company.getKeyObj(), password));
307
308 if (Validator.isNotNull(domain)) {
309 passwordCookie.setDomain(domain);
310 }
311
312 passwordCookie.setPath(StringPool.SLASH);
313
314 Cookie rememberMeCookie = new Cookie(
315 CookieKeys.REMEMBER_ME, Boolean.TRUE.toString());
316
317 if (Validator.isNotNull(domain)) {
318 rememberMeCookie.setDomain(domain);
319 }
320
321 rememberMeCookie.setPath(StringPool.SLASH);
322
323 int loginMaxAge = PropsValues.COMPANY_SECURITY_AUTO_LOGIN_MAX_AGE;
324
325 String userUUID = userIdString.concat(StringPool.PERIOD).concat(
326 String.valueOf(System.nanoTime()));
327
328 Cookie userUUIDCookie = new Cookie(
329 CookieKeys.USER_UUID,
330 Encryptor.encrypt(company.getKeyObj(), userUUID));
331
332 userUUIDCookie.setPath(StringPool.SLASH);
333
334 session.setAttribute(WebKeys.USER_UUID, userUUID);
335
336 if (PropsValues.SESSION_DISABLED) {
337 rememberMe = true;
338 }
339
340 if (rememberMe) {
341 companyIdCookie.setMaxAge(loginMaxAge);
342 idCookie.setMaxAge(loginMaxAge);
343 passwordCookie.setMaxAge(loginMaxAge);
344 rememberMeCookie.setMaxAge(loginMaxAge);
345 userUUIDCookie.setMaxAge(loginMaxAge);
346 }
347 else {
348
349
350
351
352
353
354
355 companyIdCookie.setMaxAge(-1);
356 idCookie.setMaxAge(-1);
357 passwordCookie.setMaxAge(-1);
358 rememberMeCookie.setMaxAge(0);
359 userUUIDCookie.setMaxAge(-1);
360 }
361
362 Cookie loginCookie = new Cookie(CookieKeys.LOGIN, login);
363
364 if (Validator.isNotNull(domain)) {
365 loginCookie.setDomain(domain);
366 }
367
368 loginCookie.setMaxAge(loginMaxAge);
369 loginCookie.setPath(StringPool.SLASH);
370
371 Cookie screenNameCookie = new Cookie(
372 CookieKeys.SCREEN_NAME,
373 Encryptor.encrypt(company.getKeyObj(), user.getScreenName()));
374
375 if (Validator.isNotNull(domain)) {
376 screenNameCookie.setDomain(domain);
377 }
378
379 screenNameCookie.setMaxAge(loginMaxAge);
380 screenNameCookie.setPath(StringPool.SLASH);
381
382 boolean secure = request.isSecure();
383
384 if (secure && !PropsValues.COMPANY_SECURITY_AUTH_REQUIRES_HTTPS &&
385 !StringUtil.equalsIgnoreCase(
386 Http.HTTPS, PropsValues.WEB_SERVER_PROTOCOL)) {
387
388 Boolean httpsInitial = (Boolean)session.getAttribute(
389 WebKeys.HTTPS_INITIAL);
390
391 if ((httpsInitial == null) || !httpsInitial.booleanValue()) {
392 secure = false;
393 }
394 }
395
396 CookieKeys.addCookie(request, response, companyIdCookie, secure);
397 CookieKeys.addCookie(request, response, idCookie, secure);
398 CookieKeys.addCookie(request, response, userUUIDCookie, secure);
399
400 if (rememberMe) {
401 CookieKeys.addCookie(request, response, loginCookie, secure);
402 CookieKeys.addCookie(request, response, passwordCookie, secure);
403 CookieKeys.addCookie(request, response, rememberMeCookie, secure);
404 CookieKeys.addCookie(request, response, screenNameCookie, secure);
405 }
406
407 AuthenticatedUserUUIDStoreUtil.register(userUUID);
408 }
409
410 public static HttpSession renewSession(
411 HttpServletRequest request, HttpSession session)
412 throws Exception {
413
414
415
416 String[] protectedAttributeNames =
417 PropsValues.SESSION_PHISHING_PROTECTED_ATTRIBUTES;
418
419 Map<String, Object> protectedAttributes = new HashMap<String, Object>();
420
421 for (String protectedAttributeName : protectedAttributeNames) {
422 Object protectedAttributeValue = session.getAttribute(
423 protectedAttributeName);
424
425 if (protectedAttributeValue == null) {
426 continue;
427 }
428
429 protectedAttributes.put(
430 protectedAttributeName, protectedAttributeValue);
431 }
432
433 try {
434 session.invalidate();
435 }
436 catch (IllegalStateException ise) {
437
438
439
440 if (_log.isWarnEnabled()) {
441 _log.warn(ise.getMessage());
442 }
443 }
444
445 session = request.getSession(true);
446
447 for (String protectedAttributeName : protectedAttributeNames) {
448 Object protectedAttributeValue = protectedAttributes.get(
449 protectedAttributeName);
450
451 if (protectedAttributeValue == null) {
452 continue;
453 }
454
455 session.setAttribute(
456 protectedAttributeName, protectedAttributeValue);
457 }
458
459 return session;
460 }
461
462 public static void sendPassword(ActionRequest actionRequest)
463 throws Exception {
464
465 String toAddress = ParamUtil.getString(actionRequest, "emailAddress");
466
467 sendPassword(actionRequest, null, null, toAddress, null, null);
468 }
469
470 public static void sendPassword(
471 ActionRequest actionRequest, String fromName, String fromAddress,
472 String toAddress, String subject, String body)
473 throws Exception {
474
475 HttpServletRequest request = PortalUtil.getHttpServletRequest(
476 actionRequest);
477
478 ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(
479 WebKeys.THEME_DISPLAY);
480
481 Company company = themeDisplay.getCompany();
482
483 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
484 return;
485 }
486
487 ServiceContext serviceContext = ServiceContextFactory.getInstance(
488 User.class.getName(), actionRequest);
489
490 UserLocalServiceUtil.sendPassword(
491 company.getCompanyId(), toAddress, fromName, fromAddress, subject,
492 body, serviceContext);
493
494 SessionMessages.add(actionRequest, "requestProcessed", toAddress);
495 }
496
497 private static Log _log = LogFactoryUtil.getLog(LoginUtil.class);
498
499 }