KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > dspace > app > webui > servlet > LDAPServlet


1 /*
2  * LDAPServlet.java
3  *
4  * Version: $Revision: 1.3 $
5  *
6  * Date: $Date: 2005/10/17 03:35:45 $
7  *
8  * Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
9  * Institute of Technology. All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions are
13  * met:
14  *
15  * - Redistributions of source code must retain the above copyright
16  * notice, this list of conditions and the following disclaimer.
17  *
18  * - Redistributions in binary form must reproduce the above copyright
19  * notice, this list of conditions and the following disclaimer in the
20  * documentation and/or other materials provided with the distribution.
21  *
22  * - Neither the name of the Hewlett-Packard Company nor the name of the
23  * Massachusetts Institute of Technology nor the names of their
24  * contributors may be used to endorse or promote products derived from
25  * this software without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
33  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
34  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
35  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
36  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
37  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
38  * DAMAGE.
39  */

40
41 package org.dspace.app.webui.servlet;
42
43 import java.io.IOException JavaDoc;
44 import java.sql.SQLException JavaDoc;
45 import javax.servlet.ServletException JavaDoc;
46 import javax.servlet.http.HttpServlet JavaDoc;
47 import javax.servlet.http.HttpServletRequest JavaDoc;
48 import javax.servlet.http.HttpServletResponse JavaDoc;
49
50 import org.apache.log4j.Logger;
51
52 import org.dspace.app.webui.util.Authenticate;
53 import org.dspace.app.webui.util.JSPManager;
54 import org.dspace.authorize.AuthorizeException;
55 import org.dspace.core.ConfigurationManager;
56 import org.dspace.core.Context;
57 import org.dspace.core.LogManager;
58 import org.dspace.eperson.EPerson;
59 import org.dspace.eperson.AuthenticationManager;
60 import java.util.Hashtable JavaDoc;
61
62 import javax.naming.directory.*;
63 import javax.naming.*;
64
65
66 /**
67  * LDAP username and password authentication servlet. Displays the
68  * login form <code>/login/ldap.jsp</code> on a GET,
69  * otherwise process the parameters as an ldap username and password.
70  *
71  * @author John Finlay (Brigham Young University)
72  * @version $Revision: 1.3 $
73  */

74 public class LDAPServlet extends DSpaceServlet
75 {
76     /** log4j logger */
77     private static Logger log = Logger.getLogger(LDAPServlet.class);
78
79     /** ldap email result */
80     private String JavaDoc ldapEmail;
81
82     /** ldap name result */
83     private String JavaDoc ldapGivenName;
84     private String JavaDoc ldapSurname;
85     private String JavaDoc ldapPhone;
86
87     protected void doDSGet(Context context,
88         HttpServletRequest JavaDoc request,
89         HttpServletResponse JavaDoc response)
90         throws ServletException JavaDoc, IOException JavaDoc, SQLException JavaDoc, AuthorizeException
91     {
92         // check if ldap is enables and forward to the correct login form
93
boolean ldap_enabled = ConfigurationManager.getBooleanProperty("ldap.enable");
94         if (ldap_enabled)
95             JSPManager.showJSP(request, response, "/login/ldap.jsp");
96         else
97             JSPManager.showJSP(request, response, "/login/password.jsp");
98     }
99     
100     
101     protected void doDSPost(Context context,
102         HttpServletRequest JavaDoc request,
103         HttpServletResponse JavaDoc response)
104         throws ServletException JavaDoc, IOException JavaDoc, SQLException JavaDoc, AuthorizeException
105     {
106         // Process the POSTed email and password
107
String JavaDoc netid = request.getParameter("login_netid");
108         String JavaDoc password = request.getParameter("login_password");
109         
110         // Locate the eperson
111
EPerson eperson = EPerson.findByNetid(context, netid.toLowerCase());
112         EPerson eperson2 = EPerson.findByEmail(context, netid.toLowerCase());
113         boolean loggedIn = false;
114
115         // make sure ldap values are null with every request
116
ldapGivenName = null;
117         ldapSurname = null;
118         ldapEmail = null;
119         ldapPhone = null;
120
121         // if they entered a netid that matches an eperson
122
if (eperson != null && eperson.canLogIn())
123         {
124             // e-mail address corresponds to active account
125
if (eperson.getRequireCertificate())
126             {
127                 // they must use a certificate
128
JSPManager.showJSP(request,
129                     response,
130                     "/error/require-certificate.jsp");
131                 return;
132             }
133             else
134             {
135                 if (ldapAuthenticate(netid, password, context))
136                 {
137                     // Logged in OK.
138
Authenticate.loggedIn(context, request, eperson);
139
140                     log.info(LogManager
141                         .getHeader(context, "login", "type=ldap"));
142
143                     // resume previous request
144
Authenticate.resumeInterruptedRequest(request, response);
145                     return;
146                 }
147                 else
148                 {
149                    JSPManager.showJSP(request, response, "/login/ldap-incorrect.jsp");
150                    return;
151                 }
152             }
153         }
154         // if they entered an email address that matches an eperson
155
else if (eperson2 != null && eperson2.canLogIn())
156         {
157             // e-mail address corresponds to active account
158
if (eperson2.getRequireCertificate())
159             {
160                 // they must use a certificate
161
JSPManager.showJSP(request,
162                     response,
163                     "/error/require-certificate.jsp");
164                 return;
165             }
166             else
167             {
168                 if (eperson2.checkPassword(password))
169                 {
170                     // Logged in OK.
171
Authenticate.loggedIn(context, request, eperson2);
172
173                     log.info(LogManager
174                         .getHeader(context, "login", "type=password"));
175
176                     // resume previous request
177
Authenticate.resumeInterruptedRequest(request, response);
178                     return;
179                 }
180                 else
181                 {
182                    JSPManager.showJSP(request, response, "/login/ldap-incorrect.jsp");
183                    return;
184                 }
185             }
186         }
187         // the user does not already exist so try and authenticate them with ldap and create an eperson for them
188
else {
189             if (ldapAuthenticate(netid, password, context))
190             {
191                 if (ConfigurationManager.getBooleanProperty("webui.ldap.autoregister"))
192                 {
193                     // Register the new user automatically
194
log.info(LogManager.getHeader(context,
195                                     "autoregister", "netid=" + netid));
196
197                     if ((ldapEmail!=null)&&(!ldapEmail.equals("")))
198                     {
199                         eperson = EPerson.findByEmail(context, ldapEmail);
200                         if (eperson!=null)
201                         {
202                             log.info(LogManager.getHeader(context,
203                                     "failed_autoregister", "type=ldap_but_already_email"));
204                             JSPManager.showJSP(request, response,
205                                     "/register/already-registered.jsp");
206                             return;
207                         }
208                     }
209                     // TEMPORARILY turn off authorisation
210
context.setIgnoreAuthorization(true);
211                     eperson = EPerson.create(context);
212                     if ((ldapEmail!=null)&&(!ldapEmail.equals(""))) eperson.setEmail(ldapEmail);
213                     else eperson.setEmail(netid);
214                     if ((ldapGivenName!=null)&&(!ldapGivenName.equals(""))) eperson.setFirstName(ldapGivenName);
215                     if ((ldapSurname!=null)&&(!ldapSurname.equals(""))) eperson.setLastName(ldapSurname);
216                     if ((ldapPhone!=null)&&(!ldapPhone.equals(""))) eperson.setMetadata("phone", ldapPhone);
217                     eperson.setNetid(netid);
218                     eperson.setCanLogIn(true);
219                     AuthenticationManager.initEPerson(context, request, eperson);
220                     eperson.update();
221                     context.commit();
222                     context.setIgnoreAuthorization(false);
223
224                     Authenticate.loggedIn(context, request, eperson);
225                     log.info(LogManager.getHeader(context, "login",
226                                 "type=ldap-login"));
227                     Authenticate.resumeInterruptedRequest(request, response);
228                     return;
229                 }
230                 else
231                 {
232                     // No auto-registration for valid certs
233
log.info(LogManager.getHeader(context,
234                                     "failed_login", "type=ldap_but_no_record"));
235                     JSPManager.showJSP(request, response,
236                                     "/login/not-in-records.jsp");
237                     return;
238                 }
239             }
240         }
241
242
243         // If we reach here, supplied email/password was duff.
244
log.info(LogManager.getHeader(context,
245             "failed_login",
246             "netid=" + netid));
247         JSPManager.showJSP(request, response, "/login/ldap-incorrect.jsp");
248     }
249
250     /**
251      * contact the ldap server and attempt to authenticate
252      */

253     protected boolean ldapAuthenticate(String JavaDoc netid, String JavaDoc password, Context context)
254     {
255         //--------- START LDAP AUTH SECTION -------------
256
if (!password.equals(""))
257         {
258             String JavaDoc ldap_provider_url = ConfigurationManager.getProperty("ldap.provider_url");
259             String JavaDoc ldap_id_field = ConfigurationManager.getProperty("ldap.id_field");
260             String JavaDoc ldap_search_context = ConfigurationManager.getProperty("ldap.search_context");
261             String JavaDoc ldap_object_context = ConfigurationManager.getProperty("ldap.object_context");
262
263             // Set up environment for creating initial context
264
Hashtable JavaDoc env = new Hashtable JavaDoc(11);
265             env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
266             env.put(javax.naming.Context.PROVIDER_URL, ldap_provider_url);
267
268             // Authenticate
269
env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "simple");
270             env.put(javax.naming.Context.SECURITY_PRINCIPAL, ldap_id_field+"="+netid+","+ldap_object_context);
271             env.put(javax.naming.Context.SECURITY_CREDENTIALS, password);
272             
273             try
274             {
275                 // Create initial context
276
DirContext ctx = new InitialDirContext(env);
277
278                 String JavaDoc ldap_email_field = ConfigurationManager.getProperty("ldap.email_field");
279                 String JavaDoc ldap_givenname_field = ConfigurationManager.getProperty("ldap.givenname_field");
280                 String JavaDoc ldap_surname_field = ConfigurationManager.getProperty("ldap.surname_field");
281                 String JavaDoc ldap_phone_field = ConfigurationManager.getProperty("ldap.phone_field");
282
283                 Attributes matchAttrs = new BasicAttributes(true);
284                 matchAttrs.put(new BasicAttribute(ldap_id_field, netid));
285
286                 String JavaDoc attlist[] = {ldap_email_field, ldap_givenname_field, ldap_surname_field, ldap_phone_field};
287
288                 // look up attributes
289
try
290                 {
291                     NamingEnumeration answer = ctx.search(ldap_search_context, matchAttrs, attlist);
292                     while(answer.hasMore()) {
293                         SearchResult sr = (SearchResult)answer.next();
294                         Attributes atts = sr.getAttributes();
295                         Attribute att;
296                         
297                         if (attlist[0]!=null)
298                         {
299                             att = atts.get(attlist[0]);
300                             if (att != null) ldapEmail = (String JavaDoc)att.get();
301                         }
302                         
303                         if (attlist[1]!=null)
304                         {
305                             att = atts.get(attlist[1]);
306                             if (att != null) ldapGivenName = (String JavaDoc)att.get();
307                         }
308                         
309                         if (attlist[2]!=null)
310                         {
311                             att = atts.get(attlist[2]);
312                             if (att != null) ldapSurname = (String JavaDoc)att.get();
313                         }
314
315                         if (attlist[3]!=null)
316                         {
317                             att = atts.get(attlist[3]);
318                             if (att != null) ldapPhone = (String JavaDoc)att.get();
319                         }
320                     }
321                 }
322                 catch (NamingException e)
323                 {
324                     // if the lookup fails go ahead and create a new record for them because the authentication
325
// succeeded
326
log.warn(LogManager.getHeader(context,
327                                     "ldap_attribute_lookup", "type=failed_search "+e));
328                     return true;
329                 }
330                 // Close the context when we're done
331
ctx.close();
332             }
333             catch (NamingException e)
334             {
335                 log.warn(LogManager.getHeader(context,
336                                     "ldap_authentication", "type=failed_auth "+e));
337                 return false;
338             }
339         }
340         else
341         {
342             return false;
343         }
344         //--------- END LDAP AUTH SECTION -------------
345

346         return true;
347     }
348 }
349
Popular Tags