KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > dspace > eperson > AccountManager


1 /*
2  * AccountManager.java
3  *
4  * Version: $Revision: 1.12 $
5  *
6  * Date: $Date: 2005/04/20 14:23:24 $
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 package org.dspace.eperson;
41
42 import java.io.IOException JavaDoc;
43 import java.sql.SQLException JavaDoc;
44 import java.sql.Timestamp JavaDoc;
45 import java.util.Calendar JavaDoc;
46
47 import javax.mail.MessagingException JavaDoc;
48
49 import org.apache.log4j.Logger;
50 import org.dspace.authorize.AuthorizeException;
51 import org.dspace.core.ConfigurationManager;
52 import org.dspace.core.Context;
53 import org.dspace.core.Email;
54 import org.dspace.core.Utils;
55 import org.dspace.storage.rdbms.DatabaseManager;
56 import org.dspace.storage.rdbms.TableRow;
57
58 /**
59  * Methods for handling registration by email and forgotten passwords. When
60  * someone registers as a user, or forgets their password, the
61  * sendRegistrationInfo or sendForgotPasswordInfo methods can be used to send an
62  * email to the user. The email contains a special token, a long string which is
63  * randomly generated and thus hard to guess. When the user presents the token
64  * back to the system, the AccountManager can use the token to determine the
65  * identity of the eperson.
66  *
67  * *NEW* now ignores expiration dates so that tokens never expire
68  *
69  * @author Peter Breton
70  * @version $Revision: 1.12 $
71  */

72 public class AccountManager
73 {
74     /** log4j log */
75     private static Logger log = Logger.getLogger(AccountManager.class);
76
77     /** Protected Constructor */
78     protected AccountManager()
79     {
80     }
81
82     /**
83      * Email registration info to the given email address.
84      *
85      * Potential error conditions: Cannot create registration data in database
86      * (throws SQLException) Error sending email (throws MessagingException)
87      * Error reading email template (throws IOException) Authorization error
88      * (throws AuthorizeException)
89      *
90      * @param context
91      * DSpace context
92      * @param email
93      * Email address to send the registration email to
94      */

95     public static void sendRegistrationInfo(Context context, String JavaDoc email)
96             throws SQLException JavaDoc, IOException JavaDoc, MessagingException JavaDoc,
97             AuthorizeException
98     {
99         sendInfo(context, email, true, true);
100     }
101
102     /**
103      * Email forgot password info to the given email address.
104      *
105      * Potential error conditions: No EPerson with that email (returns null)
106      * Cannot create registration data in database (throws SQLException) Error
107      * sending email (throws MessagingException) Error reading email template
108      * (throws IOException) Authorization error (throws AuthorizeException)
109      *
110      * @param context
111      * DSpace context
112      * @param email
113      * Email address to send the forgot-password email to
114      */

115     public static void sendForgotPasswordInfo(Context context, String JavaDoc email)
116             throws SQLException JavaDoc, IOException JavaDoc, MessagingException JavaDoc,
117             AuthorizeException
118     {
119         sendInfo(context, email, false, true);
120     }
121
122     /**
123      * <p>
124      * Return the EPerson corresponding to token, where token was emailed to the
125      * person by either the sendRegistrationInfo or sendForgotPasswordInfo
126      * methods.
127      * </p>
128      *
129      * <p>
130      * If the token is not found return null.
131      * </p>
132      *
133      * @param context
134      * DSpace context
135      * @param token
136      * Account token
137      * @return The EPerson corresponding to token, or null.
138      * @exception SQLException
139      * If the token or eperson cannot be retrieved from the
140      * database.
141      */

142     public static EPerson getEPerson(Context context, String JavaDoc token)
143             throws SQLException JavaDoc, AuthorizeException
144     {
145         String JavaDoc email = getEmail(context, token);
146
147         if (email == null)
148         {
149             return null;
150         }
151
152         EPerson ep = EPerson.findByEmail(context, email);
153
154         return ep;
155     }
156
157     /**
158      * Return the e-mail address referred to by a token, or null if email
159      * address can't be found ignores expiration of token
160      *
161      * @param context
162      * DSpace context
163      * @param token
164      * Account token
165      * @return The email address corresponding to token, or null.
166      */

167     public static String JavaDoc getEmail(Context context, String JavaDoc token)
168             throws SQLException JavaDoc
169     {
170         TableRow rd = DatabaseManager.findByUnique(context, "RegistrationData",
171                 "token", token);
172
173         if (rd == null)
174         {
175             return null;
176         }
177
178         /*
179          * ignore the expiration date on tokens Date expires =
180          * rd.getDateColumn("expires"); if (expires != null) { if ((new
181          * java.util.Date()).after(expires)) return null; }
182          */

183         return rd.getStringColumn("email");
184     }
185
186     /**
187      * Delete token.
188      *
189      * @param context
190      * DSpace context
191      * @param token
192      * The token to delete
193      * @exception SQLException
194      * If a database error occurs
195      */

196     public static void deleteToken(Context context, String JavaDoc token)
197             throws SQLException JavaDoc
198     {
199         DatabaseManager.deleteByValue(context, "RegistrationData", "token",
200                 token);
201     }
202
203     /*
204      * THIS IS AN INTERNAL METHOD. THE SEND PARAMETER ALLOWS IT TO BE USED FOR
205      * TESTING PURPOSES.
206      *
207      * Send an info to the EPerson with the given email address. If isRegister
208      * is TRUE, this is registration email; otherwise, it is forgot-password
209      * email. If send is TRUE, the email is sent; otherwise it is skipped.
210      *
211      * Potential error conditions: No EPerson with that email (returns null)
212      * Cannot create registration data in database (throws SQLException) Error
213      * sending email (throws MessagingException) Error reading email template
214      * (throws IOException) Authorization error (throws AuthorizeException)
215      *
216      * @param context DSpace context @param email Email address to send the
217      * forgot-password email to @param isRegister If true, this is for
218      * registration; otherwise, it is for forgot-password @param send If true,
219      * send email; otherwise do not send any email
220      */

221     protected static TableRow sendInfo(Context context, String JavaDoc email,
222             boolean isRegister, boolean send) throws SQLException JavaDoc, IOException JavaDoc,
223             MessagingException JavaDoc, AuthorizeException
224     {
225         // See if a registration token already exists for this user
226
TableRow rd = DatabaseManager.findByUnique(context, "registrationdata",
227                 "email", email);
228
229         // If it already exists, just re-issue it
230
if (rd == null)
231         {
232             rd = DatabaseManager.create(context, "RegistrationData");
233             rd.setColumn("token", Utils.generateHexKey());
234
235             // don't set expiration date any more
236
// rd.setColumn("expires", getDefaultExpirationDate());
237
rd.setColumn("email", email);
238             DatabaseManager.update(context, rd);
239
240             // This is a potential problem -- if we create the callback
241
// and then crash, registration will get SNAFU-ed.
242
// So FIRST leave some breadcrumbs
243
if (log.isDebugEnabled())
244             {
245                 log.debug("Created callback "
246                         + rd.getIntColumn("registrationdata_id")
247                         + " with token " + rd.getStringColumn("token")
248                         + " with email \"" + email + "\"");
249             }
250         }
251
252         if (send)
253         {
254             sendEmail(email, isRegister, rd);
255         }
256
257         return rd;
258     }
259
260     /**
261      * Send a DSpace message to the given email address.
262      *
263      * If isRegister is <code>true</code>, this is registration email;
264      * otherwise, it is a forgot-password email.
265      *
266      * @param email
267      * The email address to mail to
268      * @param isRegister
269      * If true, this is registration email; otherwise it is
270      * forgot-password email.
271      * @param rd
272      * The RDBMS row representing the registration data.
273      * @exception MessagingException
274      * If an error occurs while sending email
275      * @exception IOException
276      * If an error occurs while reading the email template.
277      */

278     private static void sendEmail(String JavaDoc email, boolean isRegister, TableRow rd)
279             throws MessagingException JavaDoc, IOException JavaDoc
280     {
281         String JavaDoc base = ConfigurationManager.getProperty("dspace.url");
282
283         // Note change from "key=" to "token="
284
String JavaDoc specialLink = new StringBuffer JavaDoc().append(base).append(
285                 base.endsWith("/") ? "" : "/").append(
286                 isRegister ? "register" : "forgot").append("?")
287                 .append("token=").append(rd.getStringColumn("token"))
288                 .toString();
289
290         Email bean = ConfigurationManager.getEmail(isRegister ? "register"
291                 : "change_password");
292         bean.addRecipient(email);
293         bean.addArgument(specialLink);
294         bean.send();
295
296         // Breadcrumbs
297
if (log.isInfoEnabled())
298         {
299             log.info("Sent " + (isRegister ? "registration" : "account")
300                     + " information to " + email);
301         }
302     }
303
304     /**
305      * Return the date on which registrations expire.
306      *
307      * @return - The date on which registrations expire
308      */

309     private static Timestamp JavaDoc getDefaultExpirationDate()
310     {
311         Calendar JavaDoc calendar = Calendar.getInstance();
312
313         calendar.setTime(new java.util.Date JavaDoc());
314
315         // Add 1 year from today
316
calendar.add(Calendar.WEEK_OF_YEAR, 52);
317
318         return new java.sql.Timestamp JavaDoc(calendar.getTime().getTime());
319     }
320 }
321
Popular Tags