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.portal.security.auth;
24  
25  import com.liferay.portal.NoSuchUserException;
26  import com.liferay.portal.SystemException;
27  import com.liferay.portal.kernel.log.Log;
28  import com.liferay.portal.kernel.log.LogFactoryUtil;
29  import com.liferay.portal.kernel.util.StringPool;
30  import com.liferay.portal.kernel.util.StringUtil;
31  import com.liferay.portal.kernel.util.Validator;
32  import com.liferay.portal.model.User;
33  import com.liferay.portal.security.ldap.PortalLDAPUtil;
34  import com.liferay.portal.service.UserLocalServiceUtil;
35  import com.liferay.portal.util.PortalUtil;
36  import com.liferay.portal.util.PrefsPropsUtil;
37  import com.liferay.portal.util.PropsKeys;
38  import com.liferay.portal.util.PropsValues;
39  
40  import edu.yale.its.tp.cas.client.filter.CASFilter;
41  
42  import javax.naming.Binding;
43  import javax.naming.NamingEnumeration;
44  import javax.naming.directory.Attributes;
45  import javax.naming.directory.SearchControls;
46  import javax.naming.directory.SearchResult;
47  import javax.naming.ldap.LdapContext;
48  
49  import javax.servlet.http.HttpServletRequest;
50  import javax.servlet.http.HttpServletResponse;
51  import javax.servlet.http.HttpSession;
52  
53  /**
54   * <a href="CASAutoLogin.java.html"><b><i>View Source</i></b></a>
55   *
56   * @author Brian Wing Shun Chan
57   * @author Jorge Ferrer
58   *
59   */
60  public class CASAutoLogin implements AutoLogin {
61  
62      public String[] login(
63              HttpServletRequest request, HttpServletResponse response)
64          throws AutoLoginException {
65  
66          String[] credentials = null;
67  
68          try {
69              long companyId = PortalUtil.getCompanyId(request);
70  
71              if (!PrefsPropsUtil.getBoolean(
72                      companyId, PropsKeys.CAS_AUTH_ENABLED,
73                      PropsValues.CAS_AUTH_ENABLED)) {
74  
75                  return credentials;
76              }
77  
78              HttpSession session = request.getSession();
79  
80              String screenName = (String)session.getAttribute(
81                  CASFilter.CAS_FILTER_USER);
82  
83              if (Validator.isNull(screenName)) {
84                  return credentials;
85              }
86  
87              User user = null;
88  
89              try {
90                  user = UserLocalServiceUtil.getUserByScreenName(
91                      companyId, screenName);
92              }
93              catch (NoSuchUserException nsue) {
94                  if (PrefsPropsUtil.getBoolean(
95                          companyId, PropsKeys.CAS_IMPORT_FROM_LDAP,
96                          PropsValues.CAS_IMPORT_FROM_LDAP)) {
97  
98                      user = addUser(companyId, screenName);
99                  }
100                 else {
101                     throw nsue;
102                 }
103             }
104 
105             credentials = new String[3];
106 
107             credentials[0] = String.valueOf(user.getUserId());
108             credentials[1] = user.getPassword();
109             credentials[2] = Boolean.TRUE.toString();
110 
111             return credentials;
112         }
113         catch (Exception e) {
114             _log.error(e, e);
115         }
116 
117         return credentials;
118     }
119 
120     protected User addUser(long companyId, String screenName) throws Exception {
121         LdapContext ctx = null;
122 
123         try {
124             String baseDN = PrefsPropsUtil.getString(
125                 companyId, PropsKeys.LDAP_BASE_DN);
126 
127             ctx = PortalLDAPUtil.getContext(companyId);
128 
129             if (ctx == null) {
130                 throw new SystemException("Failed to bind to the LDAP server");
131             }
132 
133             String filter = PrefsPropsUtil.getString(
134                 companyId, PropsKeys.LDAP_AUTH_SEARCH_FILTER);
135 
136             if (_log.isDebugEnabled()) {
137                 _log.debug("Search filter before transformation " + filter);
138             }
139 
140             filter = StringUtil.replace(
141                 filter,
142                 new String[] {
143                     "@company_id@", "@email_address@", "@screen_name@"
144                 },
145                 new String[] {
146                     String.valueOf(companyId), StringPool.BLANK, screenName
147                 });
148 
149             if (_log.isDebugEnabled()) {
150                 _log.debug("Search filter after transformation " + filter);
151             }
152 
153             SearchControls cons = new SearchControls(
154                 SearchControls.SUBTREE_SCOPE, 1, 0, null, false, false);
155 
156             NamingEnumeration<SearchResult> enu = ctx.search(
157                 baseDN, filter, cons);
158 
159             if (enu.hasMoreElements()) {
160                 if (_log.isDebugEnabled()) {
161                     _log.debug("Search filter returned at least one result");
162                 }
163 
164                 Binding binding = enu.nextElement();
165 
166                 Attributes attrs = PortalLDAPUtil.getUserAttributes(
167                     companyId, ctx,
168                     PortalLDAPUtil.getNameInNamespace(companyId, binding));
169 
170                 return PortalLDAPUtil.importLDAPUser(
171                     companyId, ctx, attrs, StringPool.BLANK, true);
172             }
173             else {
174                 throw new NoSuchUserException(
175                     "User " + screenName + " was not found in the LDAP server");
176             }
177         }
178         catch (Exception e) {
179             _log.error("Problem accessing LDAP server ", e);
180 
181             throw new SystemException(
182                 "Problem accessing LDAP server " + e.getMessage());
183         }
184         finally {
185             if (ctx != null) {
186                 ctx.close();
187             }
188         }
189     }
190 
191     private static Log _log = LogFactoryUtil.getLog(CASAutoLogin.class);
192 
193 }