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.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
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
095
096
097
098
099 long companyId = company.getCompanyId();
100
101 userId = UserLocalServiceUtil.authenticateForBasic(
102 companyId, CompanyConstants.AUTH_TYPE_EA, login, password);
103
104 if (userId > 0) {
105 return userId;
106 }
107
108 userId = UserLocalServiceUtil.authenticateForBasic(
109 companyId, CompanyConstants.AUTH_TYPE_SN, login, password);
110
111 if (userId > 0) {
112 return userId;
113 }
114
115 userId = UserLocalServiceUtil.authenticateForBasic(
116 companyId, CompanyConstants.AUTH_TYPE_ID, login, password);
117
118 if (userId <= 0) {
119 throw new AuthException();
120 }
121 }
122 else {
123 Map<String, String[]> headerMap = new HashMap<String, String[]>();
124
125 Enumeration<String> enu1 = request.getHeaderNames();
126
127 while (enu1.hasMoreElements()) {
128 String name = enu1.nextElement();
129
130 Enumeration<String> enu2 = request.getHeaders(name);
131
132 List<String> headers = new ArrayList<String>();
133
134 while (enu2.hasMoreElements()) {
135 String value = enu2.nextElement();
136
137 headers.add(value);
138 }
139
140 headerMap.put(
141 name, headers.toArray(new String[headers.size()]));
142 }
143
144 Map<String, String[]> parameterMap = request.getParameterMap();
145 Map<String, Object> resultsMap = new HashMap<String, Object>();
146
147 if (Validator.isNull(authType)) {
148 authType = company.getAuthType();
149 }
150
151 int authResult = Authenticator.FAILURE;
152
153 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
154 authResult = UserLocalServiceUtil.authenticateByEmailAddress(
155 company.getCompanyId(), login, password, headerMap,
156 parameterMap, resultsMap);
157
158 userId = MapUtil.getLong(resultsMap, "userId", userId);
159 }
160 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
161 authResult = UserLocalServiceUtil.authenticateByScreenName(
162 company.getCompanyId(), login, password, headerMap,
163 parameterMap, resultsMap);
164
165 userId = MapUtil.getLong(resultsMap, "userId", userId);
166 }
167 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
168 authResult = UserLocalServiceUtil.authenticateByUserId(
169 company.getCompanyId(), userId, password, headerMap,
170 parameterMap, resultsMap);
171 }
172
173 if (authResult != Authenticator.SUCCESS) {
174 throw new AuthException();
175 }
176 }
177
178 return userId;
179 }
180
181 public static String getEmailFromAddress(
182 PortletPreferences preferences, long companyId)
183 throws SystemException {
184
185 return PortalUtil.getEmailFromAddress(
186 preferences, companyId, PropsValues.LOGIN_EMAIL_FROM_ADDRESS);
187 }
188
189 public static String getEmailFromName(
190 PortletPreferences preferences, long companyId)
191 throws SystemException {
192
193 return PortalUtil.getEmailFromName(
194 preferences, companyId, PropsValues.LOGIN_EMAIL_FROM_NAME);
195 }
196
197 public static String getLogin(
198 HttpServletRequest request, String paramName, Company company)
199 throws SystemException {
200
201 String login = request.getParameter(paramName);
202
203 if ((login == null) || login.equals(StringPool.NULL)) {
204 login = GetterUtil.getString(
205 CookieKeys.getCookie(request, CookieKeys.LOGIN, false));
206
207 if (PropsValues.COMPANY_LOGIN_PREPOPULATE_DOMAIN &&
208 Validator.isNull(login) &&
209 company.getAuthType().equals(CompanyConstants.AUTH_TYPE_EA)) {
210
211 login = "@" + company.getMx();
212 }
213 }
214
215 return login;
216 }
217
218 public static PortletURL getLoginURL(HttpServletRequest request, long plid)
219 throws PortletModeException, WindowStateException {
220
221 PortletURL portletURL = PortletURLFactoryUtil.create(
222 request, PortletKeys.LOGIN, plid, PortletRequest.RENDER_PHASE);
223
224 portletURL.setParameter("saveLastPath", Boolean.FALSE.toString());
225 portletURL.setParameter("struts_action", "/login/login");
226 portletURL.setPortletMode(PortletMode.VIEW);
227 portletURL.setWindowState(WindowState.MAXIMIZED);
228
229 return portletURL;
230 }
231
232 public static void login(
233 HttpServletRequest request, HttpServletResponse response,
234 String login, String password, boolean rememberMe, String authType)
235 throws Exception {
236
237 CookieKeys.validateSupportCookie(request);
238
239 HttpSession session = request.getSession();
240
241 Company company = PortalUtil.getCompany(request);
242
243 long userId = getAuthenticatedUserId(
244 request, login, password, authType);
245
246 if (!PropsValues.AUTH_SIMULTANEOUS_LOGINS) {
247 Map<String, UserTracker> sessionUsers = LiveUsers.getSessionUsers(
248 company.getCompanyId());
249
250 List<UserTracker> userTrackers = new ArrayList<UserTracker>(
251 sessionUsers.values());
252
253 for (UserTracker userTracker : userTrackers) {
254 if (userId != userTracker.getUserId()) {
255 continue;
256 }
257
258 JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
259
260 ClusterNode clusterNode =
261 ClusterExecutorUtil.getLocalClusterNode();
262
263 if (clusterNode != null) {
264 jsonObject.put(
265 "clusterNodeId", clusterNode.getClusterNodeId());
266 }
267
268 jsonObject.put("command", "signOut");
269
270 long companyId = CompanyLocalServiceUtil.getCompanyIdByUserId(
271 userId);
272
273 jsonObject.put("companyId", companyId);
274 jsonObject.put("sessionId", userTracker.getSessionId());
275 jsonObject.put("userId", userId);
276
277 MessageBusUtil.sendMessage(
278 DestinationNames.LIVE_USERS, jsonObject.toString());
279 }
280 }
281
282 if (PropsValues.SESSION_ENABLE_PHISHING_PROTECTION) {
283
284
285
286 String[] protectedAttributeNames =
287 PropsValues.SESSION_PHISHING_PROTECTED_ATTRIBUTES;
288
289 Map<String, Object> protectedAttributes =
290 new HashMap<String, Object>();
291
292 for (String protectedAttributeName : protectedAttributeNames) {
293 Object protectedAttributeValue = session.getAttribute(
294 protectedAttributeName);
295
296 if (protectedAttributeValue == null) {
297 continue;
298 }
299
300 protectedAttributes.put(
301 protectedAttributeName, protectedAttributeValue);
302 }
303
304 try {
305 session.invalidate();
306 }
307 catch (IllegalStateException ise) {
308
309
310
311 if (_log.isWarnEnabled()) {
312 _log.warn(ise.getMessage());
313 }
314 }
315
316 session = request.getSession(true);
317
318 for (String protectedAttributeName : protectedAttributeNames) {
319 Object protectedAttributeValue = protectedAttributes.get(
320 protectedAttributeName);
321
322 if (protectedAttributeValue == null) {
323 continue;
324 }
325
326 session.setAttribute(
327 protectedAttributeName, protectedAttributeValue);
328 }
329 }
330
331
332
333 String domain = CookieKeys.getDomain(request);
334
335 User user = UserLocalServiceUtil.getUserById(userId);
336
337 String userIdString = String.valueOf(userId);
338
339 session.setAttribute("j_username", userIdString);
340 session.setAttribute("j_password", user.getPassword());
341 session.setAttribute("j_remoteuser", userIdString);
342
343 if (PropsValues.SESSION_STORE_PASSWORD) {
344 session.setAttribute(WebKeys.USER_PASSWORD, password);
345 }
346
347 Cookie companyIdCookie = new Cookie(
348 CookieKeys.COMPANY_ID, String.valueOf(company.getCompanyId()));
349
350 if (Validator.isNotNull(domain)) {
351 companyIdCookie.setDomain(domain);
352 }
353
354 companyIdCookie.setPath(StringPool.SLASH);
355
356 Cookie idCookie = new Cookie(
357 CookieKeys.ID,
358 Encryptor.encrypt(company.getKeyObj(), userIdString));
359
360 if (Validator.isNotNull(domain)) {
361 idCookie.setDomain(domain);
362 }
363
364 idCookie.setPath(StringPool.SLASH);
365
366 Cookie passwordCookie = new Cookie(
367 CookieKeys.PASSWORD,
368 Encryptor.encrypt(company.getKeyObj(), password));
369
370 if (Validator.isNotNull(domain)) {
371 passwordCookie.setDomain(domain);
372 }
373
374 passwordCookie.setPath(StringPool.SLASH);
375
376 Cookie rememberMeCookie = new Cookie(
377 CookieKeys.REMEMBER_ME, Boolean.TRUE.toString());
378
379 if (Validator.isNotNull(domain)) {
380 rememberMeCookie.setDomain(domain);
381 }
382
383 rememberMeCookie.setPath(StringPool.SLASH);
384
385 int loginMaxAge = PropsValues.COMPANY_SECURITY_AUTO_LOGIN_MAX_AGE;
386
387 String userUUID = userIdString.concat(StringPool.PERIOD).concat(
388 String.valueOf(System.nanoTime()));
389
390 Cookie userUUIDCookie = new Cookie(
391 CookieKeys.USER_UUID,
392 Encryptor.encrypt(company.getKeyObj(), userUUID));
393
394 userUUIDCookie.setPath(StringPool.SLASH);
395
396 session.setAttribute(WebKeys.USER_UUID, userUUID);
397
398 if (PropsValues.SESSION_DISABLED) {
399 rememberMe = true;
400 }
401
402 if (rememberMe) {
403 companyIdCookie.setMaxAge(loginMaxAge);
404 idCookie.setMaxAge(loginMaxAge);
405 passwordCookie.setMaxAge(loginMaxAge);
406 rememberMeCookie.setMaxAge(loginMaxAge);
407 userUUIDCookie.setMaxAge(loginMaxAge);
408 }
409 else {
410
411
412
413
414
415
416
417 companyIdCookie.setMaxAge(-1);
418 idCookie.setMaxAge(-1);
419 passwordCookie.setMaxAge(-1);
420 rememberMeCookie.setMaxAge(0);
421 userUUIDCookie.setMaxAge(-1);
422 }
423
424 Cookie loginCookie = new Cookie(CookieKeys.LOGIN, login);
425
426 if (Validator.isNotNull(domain)) {
427 loginCookie.setDomain(domain);
428 }
429
430 loginCookie.setMaxAge(loginMaxAge);
431 loginCookie.setPath(StringPool.SLASH);
432
433 Cookie screenNameCookie = new Cookie(
434 CookieKeys.SCREEN_NAME,
435 Encryptor.encrypt(company.getKeyObj(), user.getScreenName()));
436
437 if (Validator.isNotNull(domain)) {
438 screenNameCookie.setDomain(domain);
439 }
440
441 screenNameCookie.setMaxAge(loginMaxAge);
442 screenNameCookie.setPath(StringPool.SLASH);
443
444 boolean secure = request.isSecure();
445
446 if (secure) {
447 Boolean httpsInitial = (Boolean)session.getAttribute(
448 WebKeys.HTTPS_INITIAL);
449
450 if ((httpsInitial == null) || !httpsInitial.booleanValue()) {
451 secure = false;
452 }
453 }
454
455 CookieKeys.addCookie(request, response, companyIdCookie, secure);
456 CookieKeys.addCookie(request, response, idCookie, secure);
457 CookieKeys.addCookie(request, response, userUUIDCookie, secure);
458
459 if (rememberMe) {
460 CookieKeys.addCookie(request, response, loginCookie, secure);
461 CookieKeys.addCookie(request, response, passwordCookie, secure);
462 CookieKeys.addCookie(request, response, rememberMeCookie, secure);
463 CookieKeys.addCookie(request, response, screenNameCookie, secure);
464 }
465
466 AuthenticatedUserUUIDStoreUtil.register(userUUID);
467 }
468
469 public static void sendPassword(ActionRequest actionRequest)
470 throws Exception {
471
472 String toAddress = ParamUtil.getString(actionRequest, "emailAddress");
473
474 sendPassword(actionRequest, null, null, toAddress, null, null);
475 }
476
477 public static void sendPassword(
478 ActionRequest actionRequest, String fromName, String fromAddress,
479 String toAddress, String subject, String body)
480 throws Exception {
481
482 HttpServletRequest request = PortalUtil.getHttpServletRequest(
483 actionRequest);
484
485 ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(
486 WebKeys.THEME_DISPLAY);
487
488 Company company = themeDisplay.getCompany();
489
490 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
491 return;
492 }
493
494 ServiceContext serviceContext = ServiceContextFactory.getInstance(
495 User.class.getName(), actionRequest);
496
497 UserLocalServiceUtil.sendPassword(
498 company.getCompanyId(), toAddress, fromName, fromAddress, subject,
499 body, serviceContext);
500
501 SessionMessages.add(actionRequest, "requestProcessed", toAddress);
502 }
503
504 private static Log _log = LogFactoryUtil.getLog(LoginUtil.class);
505
506 }