PageRenderTime 69ms CodeModel.GetById 42ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/apps/portal-security-sso/portal-security-sso-opensso-impl/src/main/java/com/liferay/portal/security/sso/opensso/internal/auto/login/OpenSSOAutoLogin.java

https://github.com/danielreuther/liferay-portal
Java | 342 lines | 243 code | 62 blank | 37 comment | 26 complexity | 68f3f9ec20ea3dbd8ffe73cf1f4d7f99 MD5 | raw file
  1. /**
  2. * Copyright (c) 2000-present 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. package com.liferay.portal.security.sso.opensso.internal.auto.login;
  15. import com.liferay.petra.string.StringBundler;
  16. import com.liferay.petra.string.StringPool;
  17. import com.liferay.portal.kernel.exception.ContactNameException;
  18. import com.liferay.portal.kernel.exception.PortalException;
  19. import com.liferay.portal.kernel.exception.SystemException;
  20. import com.liferay.portal.kernel.exception.UserEmailAddressException;
  21. import com.liferay.portal.kernel.log.Log;
  22. import com.liferay.portal.kernel.log.LogFactoryUtil;
  23. import com.liferay.portal.kernel.model.Company;
  24. import com.liferay.portal.kernel.model.CompanyConstants;
  25. import com.liferay.portal.kernel.model.User;
  26. import com.liferay.portal.kernel.module.configuration.ConfigurationProvider;
  27. import com.liferay.portal.kernel.security.auth.ScreenNameGenerator;
  28. import com.liferay.portal.kernel.security.auto.login.AutoLogin;
  29. import com.liferay.portal.kernel.security.auto.login.BaseAutoLogin;
  30. import com.liferay.portal.kernel.security.sso.OpenSSO;
  31. import com.liferay.portal.kernel.service.CompanyLocalService;
  32. import com.liferay.portal.kernel.service.ServiceContext;
  33. import com.liferay.portal.kernel.service.UserLocalService;
  34. import com.liferay.portal.kernel.settings.CompanyServiceSettingsLocator;
  35. import com.liferay.portal.kernel.theme.ThemeDisplay;
  36. import com.liferay.portal.kernel.util.LocaleUtil;
  37. import com.liferay.portal.kernel.util.ParamUtil;
  38. import com.liferay.portal.kernel.util.Portal;
  39. import com.liferay.portal.kernel.util.PrefsPropsUtil;
  40. import com.liferay.portal.kernel.util.PropsKeys;
  41. import com.liferay.portal.kernel.util.Validator;
  42. import com.liferay.portal.kernel.util.WebKeys;
  43. import com.liferay.portal.security.exportimport.UserImporter;
  44. import com.liferay.portal.security.sso.opensso.configuration.OpenSSOConfiguration;
  45. import com.liferay.portal.security.sso.opensso.constants.OpenSSOConstants;
  46. import com.liferay.portal.security.sso.opensso.constants.OpenSSOWebKeys;
  47. import com.liferay.portal.security.sso.opensso.exception.StrangersNotAllowedException;
  48. import com.liferay.portal.util.PropsValues;
  49. import java.util.Calendar;
  50. import java.util.Locale;
  51. import java.util.Map;
  52. import javax.servlet.http.HttpServletRequest;
  53. import javax.servlet.http.HttpServletResponse;
  54. import org.osgi.service.component.annotations.Component;
  55. import org.osgi.service.component.annotations.Reference;
  56. /**
  57. * Participates in every unauthenticated HTTP request to Liferay Portal.
  58. *
  59. * <p>
  60. * This class queries the OpenSSO server for the name of the OpenSSO token
  61. * cookie and any additional cookies. These are then extracted from the HTTP
  62. * request and forwarded to the OpenSSO server to validate the user's
  63. * authentication status.
  64. * </p>
  65. *
  66. * <p>
  67. * If the cookies are validated, another request is made to the OpenSSO server
  68. * to retrieve all the user's attributes. These are mapped to Liferay Portal
  69. * user attributes using the configured mappings. If Import from LDAP is
  70. * enabled, then the user is imported and logged in. Otherwise a new user is
  71. * created and logged in.
  72. * </p>
  73. *
  74. * @author Brian Wing Shun Chan
  75. * @author Prashant Dighe
  76. */
  77. @Component(
  78. configurationPid = "com.liferay.portal.security.sso.opensso.configuration.OpenSSOConfiguration",
  79. immediate = true, service = AutoLogin.class
  80. )
  81. public class OpenSSOAutoLogin extends BaseAutoLogin {
  82. @Override
  83. protected String[] doLogin(
  84. HttpServletRequest httpServletRequest,
  85. HttpServletResponse httpServletResponse)
  86. throws Exception {
  87. long companyId = _portal.getCompanyId(httpServletRequest);
  88. OpenSSOConfiguration openSSOConfiguration = _getOpenSSOConfiguration(
  89. companyId);
  90. if (!openSSOConfiguration.enabled() ||
  91. !_openSSO.isAuthenticated(
  92. httpServletRequest, openSSOConfiguration.serviceURL())) {
  93. return null;
  94. }
  95. Map<String, String> nameValues = _openSSO.getAttributes(
  96. httpServletRequest, openSSOConfiguration.serviceURL());
  97. String openSSOScreenName = nameValues.get(
  98. openSSOConfiguration.screenNameAttr());
  99. String emailAddress = nameValues.get(
  100. openSSOConfiguration.emailAddressAttr());
  101. String firstName = nameValues.get(openSSOConfiguration.firstNameAttr());
  102. String lastName = nameValues.get(openSSOConfiguration.lastNameAttr());
  103. if (_log.isDebugEnabled()) {
  104. _log.debug(
  105. StringBundler.concat(
  106. "Validating user information for ", firstName, " ",
  107. lastName, " with screen name ", openSSOScreenName,
  108. " and email address ", emailAddress));
  109. }
  110. User user = null;
  111. String screenName = openSSOScreenName;
  112. if (PrefsPropsUtil.getBoolean(
  113. companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
  114. user = _userLocalService.fetchUserByEmailAddress(
  115. companyId, emailAddress);
  116. if (user != null) {
  117. screenName = _screenNameGenerator.generate(
  118. companyId, user.getUserId(), emailAddress);
  119. }
  120. }
  121. if (openSSOConfiguration.importFromLDAP()) {
  122. try {
  123. String authType = PrefsPropsUtil.getString(
  124. companyId, PropsKeys.COMPANY_SECURITY_AUTH_TYPE,
  125. PropsValues.COMPANY_SECURITY_AUTH_TYPE);
  126. if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
  127. user = _userImporter.importUser(
  128. companyId, StringPool.BLANK, screenName);
  129. }
  130. else {
  131. user = _userImporter.importUser(
  132. companyId, emailAddress, StringPool.BLANK);
  133. }
  134. }
  135. catch (SystemException systemException) {
  136. // LPS-52675
  137. if (_log.isDebugEnabled()) {
  138. _log.debug(systemException);
  139. }
  140. }
  141. }
  142. else {
  143. if (Validator.isNull(emailAddress)) {
  144. return doHandleException(
  145. httpServletRequest, httpServletResponse,
  146. new Exception("Email address is null"));
  147. }
  148. }
  149. if (user == null) {
  150. user = _userLocalService.fetchUserByScreenName(
  151. companyId, screenName);
  152. }
  153. if (user == null) {
  154. ThemeDisplay themeDisplay =
  155. (ThemeDisplay)httpServletRequest.getAttribute(
  156. WebKeys.THEME_DISPLAY);
  157. Locale locale = LocaleUtil.getDefault();
  158. if (themeDisplay != null) {
  159. // ThemeDisplay should never be null, but some users complain of
  160. // this error. Cause is unknown.
  161. locale = themeDisplay.getLocale();
  162. }
  163. try {
  164. _checkAddUser(companyId, emailAddress);
  165. if (_log.isDebugEnabled()) {
  166. _log.debug("Adding user " + screenName);
  167. }
  168. user = _addUser(
  169. companyId, firstName, lastName, emailAddress, screenName,
  170. locale);
  171. }
  172. catch (PortalException portalException) {
  173. if (_log.isDebugEnabled()) {
  174. _log.debug(
  175. StringBundler.concat(
  176. "Failed to import OpenSSO user '",
  177. openSSOScreenName, "': ",
  178. portalException.getMessage()),
  179. portalException);
  180. }
  181. if (portalException instanceof ContactNameException) {
  182. httpServletRequest.setAttribute(
  183. OpenSSOWebKeys.OPEN_SSO_ERROR,
  184. ContactNameException.class.getSimpleName());
  185. }
  186. else {
  187. Class<?> clazz = portalException.getClass();
  188. httpServletRequest.setAttribute(
  189. OpenSSOWebKeys.OPEN_SSO_ERROR, clazz.getSimpleName());
  190. }
  191. httpServletRequest.setAttribute(
  192. OpenSSOWebKeys.OPEN_SSO_SUBJECT_SCREEN_NAME,
  193. openSSOScreenName);
  194. return null;
  195. }
  196. }
  197. String currentURL = _portal.getCurrentURL(httpServletRequest);
  198. if (currentURL.contains("/portal/login")) {
  199. String redirect = ParamUtil.getString(
  200. httpServletRequest, "redirect");
  201. if (Validator.isNotNull(redirect)) {
  202. redirect = _portal.escapeRedirect(redirect);
  203. }
  204. else {
  205. redirect = _portal.getPathMain();
  206. }
  207. httpServletRequest.setAttribute(
  208. AutoLogin.AUTO_LOGIN_REDIRECT, redirect);
  209. }
  210. String[] credentials = new String[3];
  211. credentials[0] = String.valueOf(user.getUserId());
  212. credentials[1] = user.getPassword();
  213. credentials[2] = Boolean.TRUE.toString();
  214. return credentials;
  215. }
  216. private User _addUser(
  217. long companyId, String firstName, String lastName,
  218. String emailAddress, String screenName, Locale locale)
  219. throws PortalException {
  220. long creatorUserId = 0;
  221. boolean autoPassword = true;
  222. String password1 = null;
  223. String password2 = null;
  224. boolean autoScreenName = false;
  225. String middleName = StringPool.BLANK;
  226. long prefixId = 0;
  227. long suffixId = 0;
  228. boolean male = true;
  229. int birthdayMonth = Calendar.JANUARY;
  230. int birthdayDay = 1;
  231. int birthdayYear = 1970;
  232. String jobTitle = StringPool.BLANK;
  233. long[] groupIds = null;
  234. long[] organizationIds = null;
  235. long[] roleIds = null;
  236. long[] userGroupIds = null;
  237. boolean sendEmail = false;
  238. return _userLocalService.addUser(
  239. creatorUserId, companyId, autoPassword, password1, password2,
  240. autoScreenName, screenName, emailAddress, locale, firstName,
  241. middleName, lastName, prefixId, suffixId, male, birthdayMonth,
  242. birthdayDay, birthdayYear, jobTitle, groupIds, organizationIds,
  243. roleIds, userGroupIds, sendEmail, new ServiceContext());
  244. }
  245. private void _checkAddUser(long companyId, String emailAddress)
  246. throws PortalException {
  247. Company company = _companyLocalService.getCompany(companyId);
  248. if (!company.isStrangers()) {
  249. throw new StrangersNotAllowedException(companyId);
  250. }
  251. if (!company.isStrangersWithMx() &&
  252. company.hasCompanyMx(emailAddress)) {
  253. throw new UserEmailAddressException.MustNotUseCompanyMx(
  254. emailAddress);
  255. }
  256. }
  257. private OpenSSOConfiguration _getOpenSSOConfiguration(long companyId)
  258. throws Exception {
  259. return _configurationProvider.getConfiguration(
  260. OpenSSOConfiguration.class,
  261. new CompanyServiceSettingsLocator(
  262. companyId, OpenSSOConstants.SERVICE_NAME));
  263. }
  264. private static final Log _log = LogFactoryUtil.getLog(
  265. OpenSSOAutoLogin.class);
  266. @Reference
  267. private CompanyLocalService _companyLocalService;
  268. @Reference
  269. private ConfigurationProvider _configurationProvider;
  270. @Reference
  271. private OpenSSO _openSSO;
  272. @Reference
  273. private Portal _portal;
  274. @Reference
  275. private ScreenNameGenerator _screenNameGenerator;
  276. @Reference
  277. private UserImporter _userImporter;
  278. @Reference
  279. private UserLocalService _userLocalService;
  280. }