1   /**
2    * Copyright (c) 2000-2007 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.PortalException;
27  import com.liferay.portal.SystemException;
28  import com.liferay.portal.kernel.util.StringPool;
29  import com.liferay.portal.kernel.util.StringUtil;
30  import com.liferay.portal.model.User;
31  import com.liferay.portal.security.ldap.PortalLDAPUtil;
32  import com.liferay.portal.service.UserLocalServiceUtil;
33  import com.liferay.portal.util.PortalUtil;
34  import com.liferay.portal.util.PrefsPropsUtil;
35  import com.liferay.portal.util.PropsUtil;
36  import com.liferay.util.PwdGenerator;
37  import com.liferay.util.ldap.LDAPUtil;
38  
39  import edu.yale.its.tp.cas.client.filter.CASFilter;
40  
41  import java.util.Properties;
42  
43  import javax.naming.Binding;
44  import javax.naming.Context;
45  import javax.naming.NamingEnumeration;
46  import javax.naming.directory.Attribute;
47  import javax.naming.directory.Attributes;
48  import javax.naming.directory.SearchControls;
49  import javax.naming.ldap.InitialLdapContext;
50  import javax.naming.ldap.LdapContext;
51  
52  import javax.servlet.http.HttpServletRequest;
53  import javax.servlet.http.HttpServletResponse;
54  import javax.servlet.http.HttpSession;
55  
56  import org.apache.commons.logging.Log;
57  import org.apache.commons.logging.LogFactory;
58  
59  /**
60   * <a href="CASAutoLogin.java.html"><b><i>View Source</i></b></a>
61   *
62   * @author Brian Wing Shun Chan
63   * @author Jorge Ferrer
64   *
65   */
66  public class CASAutoLogin implements AutoLogin {
67  
68      public String[] login(HttpServletRequest req, HttpServletResponse res)
69          throws AutoLoginException {
70  
71          try {
72              String[] credentials = null;
73  
74              long companyId = PortalUtil.getCompanyId(req);
75  
76              if (!PrefsPropsUtil.getBoolean(
77                      companyId, PropsUtil.CAS_AUTH_ENABLED)) {
78  
79                  return credentials;
80              }
81  
82              HttpSession ses = req.getSession();
83  
84              String screenName =
85                  (String)ses.getAttribute(CASFilter.CAS_FILTER_USER);
86  
87              if (screenName != null) {
88                  User user = null;
89  
90                  try {
91                      user = UserLocalServiceUtil.getUserByScreenName(
92                          companyId, screenName);
93                  }
94                  catch (NoSuchUserException nsue) {
95                      if (PrefsPropsUtil.getBoolean(
96                              companyId, PropsUtil.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 
112             return credentials;
113         }
114         catch (Exception e) {
115             throw new AutoLoginException(e);
116         }
117     }
118 
119     protected User addUser(long companyId, String screenName)
120         throws PortalException, SystemException {
121 
122         try {
123             Properties env = new Properties();
124 
125             String baseProviderURL = PrefsPropsUtil.getString(
126                 companyId, PropsUtil.LDAP_BASE_PROVIDER_URL);
127 
128             String baseDN = PrefsPropsUtil.getString(
129                 companyId, PropsUtil.LDAP_BASE_DN);
130 
131             env.put(
132                 Context.INITIAL_CONTEXT_FACTORY,
133                 PrefsPropsUtil.getString(
134                     companyId, PropsUtil.LDAP_FACTORY_INITIAL));
135             env.put(
136                 Context.PROVIDER_URL,
137                 LDAPUtil.getFullProviderURL(baseProviderURL, baseDN));
138             env.put(
139                 Context.SECURITY_PRINCIPAL,
140                 PrefsPropsUtil.getString(
141                     companyId, PropsUtil.LDAP_SECURITY_PRINCIPAL));
142             env.put(
143                 Context.SECURITY_CREDENTIALS,
144                 PrefsPropsUtil.getString(
145                     companyId, PropsUtil.LDAP_SECURITY_CREDENTIALS));
146 
147             LdapContext ctx = null;
148 
149             try {
150                 ctx = new InitialLdapContext(env, null);
151             }
152             catch (Exception e) {
153                 if (_log.isDebugEnabled()) {
154                     _log.debug("Failed to bind to the LDAP server", e);
155                 }
156 
157                 throw new SystemException(e);
158             }
159 
160             String filter = PrefsPropsUtil.getString(
161                 companyId, PropsUtil.LDAP_AUTH_SEARCH_FILTER);
162 
163             if (_log.isDebugEnabled()) {
164                 _log.debug("Search filter before transformation " + filter);
165             }
166 
167             filter = StringUtil.replace(
168                 filter,
169                 new String[] {
170                     "@company_id@", "@email_address@", "@screen_name@"
171                 },
172                 new String[] {
173                     String.valueOf(companyId), StringPool.BLANK, screenName
174                 });
175 
176             if (_log.isDebugEnabled()) {
177                 _log.debug("Search filter after transformation " + filter);
178             }
179 
180             SearchControls cons = new SearchControls(
181                 SearchControls.SUBTREE_SCOPE, 1, 0, null, false, false);
182 
183             NamingEnumeration enu = ctx.search(StringPool.BLANK, filter, cons);
184 
185             if (enu.hasMore()) {
186                 if (_log.isDebugEnabled()) {
187                     _log.debug("Search filter returned at least one result");
188                 }
189 
190                 Binding binding = (Binding)enu.next();
191 
192                 Attributes attrs = ctx.getAttributes(binding.getName());
193 
194                 Attribute emailAddressAttr = attrs.get("mail");
195 
196                 String emailAddress = StringPool.BLANK;
197 
198                 if (emailAddressAttr != null) {
199                     emailAddress = emailAddressAttr.get().toString();
200                 }
201 
202                 return PortalLDAPUtil.importLDAPUser(
203                     companyId, ctx, attrs, emailAddress, screenName,
204                     PwdGenerator.getPassword(), true);
205             }
206             else {
207                 throw new NoSuchUserException(
208                     "User " + screenName + " was not found in the LDAP server");
209             }
210         }
211         catch (Exception e) {
212             _log.error("Problem accessing LDAP server ", e);
213 
214             throw new SystemException(
215                 "Problem accessign LDAP server " + e.getMessage());
216         }
217     }
218 
219     private static Log _log = LogFactory.getLog(CASAutoLogin.class);
220 
221 }