KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > blojsom > plugin > admin > ForgottenPasswordPlugin


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

31 package org.blojsom.plugin.admin;
32
33 import org.apache.commons.logging.Log;
34 import org.apache.commons.logging.LogFactory;
35 import org.apache.commons.mail.Email;
36 import org.apache.commons.mail.EmailException;
37 import org.apache.commons.mail.HtmlEmail;
38 import org.blojsom.blog.Blog;
39 import org.blojsom.blog.Entry;
40 import org.blojsom.blog.User;
41 import org.blojsom.fetcher.Fetcher;
42 import org.blojsom.fetcher.FetcherException;
43 import org.blojsom.plugin.PluginException;
44 import org.blojsom.plugin.email.EmailConstants;
45 import org.blojsom.util.BlojsomConstants;
46 import org.blojsom.util.BlojsomUtils;
47
48 import javax.mail.Session JavaDoc;
49 import javax.naming.Context JavaDoc;
50 import javax.naming.InitialContext JavaDoc;
51 import javax.naming.NamingException JavaDoc;
52 import javax.servlet.http.HttpServletRequest JavaDoc;
53 import javax.servlet.http.HttpServletResponse JavaDoc;
54 import java.util.Date JavaDoc;
55 import java.util.Map JavaDoc;
56 import java.util.Random JavaDoc;
57
58 /**
59  * Forgotten password plugin
60  *
61  * @author David Czarnecki
62  * @since blojsom 3.0
63  * @version $Id: ForgottenPasswordPlugin.java,v 1.2 2006/04/08 22:49:42 czarneckid Exp $
64  */

65 public class ForgottenPasswordPlugin extends BaseAdminPlugin {
66
67     private Log _logger = LogFactory.getLog(ForgottenPasswordPlugin.class);
68
69     // Localization constants
70
private static final String JavaDoc FAILED_PASSWORD_CHANGE_KEY = "failed.password.change.text";
71     private static final String JavaDoc CONSTRUCTED_PASSWORD_EMAIL_KEY = "constructed.password.email.text";
72     private static final String JavaDoc USERNAME_BLANK_KEY = "username.blank.text";
73
74     private static final String JavaDoc FORGOTTEN_USERNAME_PARAM = "forgotten-username";
75     private static final String JavaDoc FORGOTTEN_PASSWORD_PAGE = "forgotten-password";
76
77     private Fetcher _fetcher;
78     private String JavaDoc _mailServer;
79     private String JavaDoc _mailServerUsername;
80     private String JavaDoc _mailServerPassword;
81     private Session JavaDoc _session;
82
83     /**
84      * Default constructor.
85      */

86     public ForgottenPasswordPlugin() {
87     }
88
89     /**
90      * Set the {@link Fetcher}
91      *
92      * @param fetcher {@link Fetcher}
93      */

94     public void setFetcher(Fetcher fetcher) {
95         _fetcher = fetcher;
96     }
97
98     /**
99      * Initialize this plugin. This method only called when the plugin is instantiated.
100      *
101      * @throws org.blojsom.plugin.PluginException
102      * If there is an error initializing the plugin
103      */

104     public void init() throws PluginException {
105         super.init();
106
107         _mailServer = _servletConfig.getInitParameter(EmailConstants.SMTPSERVER_IP);
108
109         if (_mailServer != null) {
110             if (_mailServer.startsWith("java:comp/env")) {
111                 try {
112                     Context JavaDoc context = new InitialContext JavaDoc();
113                     _session = (Session JavaDoc) context.lookup(_mailServer);
114                 } catch (NamingException JavaDoc e) {
115                     if (_logger.isErrorEnabled()) {
116                         _logger.error(e);
117                     }
118
119                     throw new PluginException(e);
120                 }
121             } else {
122                 _mailServerUsername = _servletConfig.getInitParameter(EmailConstants.SMTPSERVER_USERNAME_IP);
123                 _mailServerPassword = _servletConfig.getInitParameter(EmailConstants.SMTPSERVER_PASSWORD_IP);
124             }
125         } else {
126             if (_logger.isErrorEnabled()) {
127                 _logger.error("Missing SMTP servername servlet initialization parameter: " + EmailConstants.SMTPSERVER_IP);
128             }
129         }
130     }
131
132     /**
133      * Setup the comment e-mail
134      *
135      * @param blog {@link Blog} information
136      * @param user {@link User}
137      * @param email Email message
138      * @throws EmailException If there is an error preparing the e-mail message
139      */

140     protected void setupEmail(Blog blog, User user, Email email) throws EmailException {
141         email.setCharset(BlojsomConstants.UTF8);
142
143         // If we have a mail session for the environment, use that
144
if (_session != null) {
145             email.setMailSession(_session);
146         } else {
147             // Otherwise, if there is a username and password for the mail server, use that
148
if (!BlojsomUtils.checkNullOrBlank(_mailServerUsername) && !BlojsomUtils.checkNullOrBlank(_mailServerPassword)) {
149                 email.setHostName(_mailServer);
150                 email.setAuthentication(_mailServerUsername, _mailServerPassword);
151             } else {
152                 email.setHostName(_mailServer);
153             }
154         }
155
156         email.setFrom(blog.getBlogOwnerEmail(), "Blojsom Forgotten Password");
157
158         String JavaDoc authorizedUserEmail = user.getUserEmail();
159         if (BlojsomUtils.checkNullOrBlank(authorizedUserEmail)) {
160             authorizedUserEmail = blog.getBlogOwnerEmail();
161         }
162
163         String JavaDoc authorizedUser = user.getUserName();
164         if (BlojsomUtils.checkNullOrBlank(authorizedUser)) {
165             authorizedUser = user.getUserLogin();
166         }
167
168         email.addTo(authorizedUserEmail, authorizedUser);
169         email.setSentDate(new Date JavaDoc());
170     }
171
172     /**
173      * Process the blog entries
174      *
175      * @param httpServletRequest Request
176      * @param httpServletResponse Response
177      * @param user {@link org.blojsom.blog.BlogUser} instance
178      * @param context Context
179      * @param entries Blog entries retrieved for the particular request
180      * @return Modified set of blog entries
181      * @throws org.blojsom.plugin.PluginException
182      * If there is an error processing the blog entries
183      */

184     public Entry[] process(HttpServletRequest JavaDoc httpServletRequest, HttpServletResponse JavaDoc httpServletResponse, Blog blog, Map JavaDoc context, Entry[] entries) throws PluginException {
185         String JavaDoc username = BlojsomUtils.getRequestValue(FORGOTTEN_USERNAME_PARAM, httpServletRequest);
186         String JavaDoc action = BlojsomUtils.getRequestValue(ACTION_PARAM, httpServletRequest);
187
188         if (!BlojsomUtils.checkNullOrBlank(username)) {
189             User user;
190
191             try {
192                 user = _fetcher.loadUser(blog, username);
193
194                 HtmlEmail email = new HtmlEmail();
195                 setupEmail(blog, user, email);
196
197                 if (blog.getUseEncryptedPasswords().booleanValue()) {
198                     // Otherwise we have to create a new password since the password is one-way encrypted with MD5
199
Random JavaDoc random = new Random JavaDoc(new Date JavaDoc().getTime() + System.currentTimeMillis());
200                     int password = random.nextInt(Integer.MAX_VALUE);
201                     String JavaDoc updatedPassword = Integer.toString(password);
202
203                     user.setUserPassword(updatedPassword);
204                     _fetcher.saveUser(blog, user);
205                 }
206
207                 String JavaDoc emailText = "Here's your password: " + user.getUserPassword();
208                 email.setHtmlMsg(emailText);
209                 email.setTextMsg(emailText);
210
211                 String JavaDoc to = user.getUserName();
212                 if (BlojsomUtils.checkNullOrBlank(to)) {
213                     to = user.getUserLogin();
214                 }
215
216                 email.setSubject("Forgotten password e-mail for " + to);
217
218                 if (_logger.isDebugEnabled()) {
219                     _logger.debug("Constructed forgotten password e-mail message for username: " + username);
220                 }
221
222                 email.send();
223
224                 addOperationResultMessage(context, formatAdminResource(CONSTRUCTED_PASSWORD_EMAIL_KEY, CONSTRUCTED_PASSWORD_EMAIL_KEY, blog.getBlogAdministrationLocale(), new Object JavaDoc[] {to}));
225                 httpServletRequest.setAttribute(BlojsomConstants.PAGE_PARAM, ADMIN_LOGIN_PAGE);
226             } catch (FetcherException e) {
227                 if (_logger.isErrorEnabled()) {
228                     _logger.error(e);
229                 }
230
231                 addOperationResultMessage(context, formatAdminResource(FAILED_PASSWORD_CHANGE_KEY, FAILED_PASSWORD_CHANGE_KEY, blog.getBlogAdministrationLocale(), new Object JavaDoc[] {username}));
232                 httpServletRequest.setAttribute(BlojsomConstants.PAGE_PARAM, ADMIN_LOGIN_PAGE);
233
234                 return entries;
235             } catch (EmailException e) {
236                 if (_logger.isErrorEnabled()) {
237                     _logger.error(e);
238                 }
239
240                 addOperationResultMessage(context, formatAdminResource(FAILED_PASSWORD_CHANGE_KEY, FAILED_PASSWORD_CHANGE_KEY, blog.getBlogAdministrationLocale(), new Object JavaDoc[] {username}));
241                 httpServletRequest.setAttribute(BlojsomConstants.PAGE_PARAM, ADMIN_LOGIN_PAGE);
242
243                 return entries;
244             }
245         } else {
246             if (BlojsomUtils.checkNullOrBlank(action)) {
247                 addOperationResultMessage(context, getAdminResource(USERNAME_BLANK_KEY, USERNAME_BLANK_KEY, blog.getBlogAdministrationLocale()));
248             }
249
250             httpServletRequest.setAttribute(BlojsomConstants.PAGE_PARAM, FORGOTTEN_PASSWORD_PAGE);
251         }
252
253         return entries;
254     }
255
256     /**
257      * Perform any cleanup for the plugin. Called after {@link #process}.
258      *
259      * @throws org.blojsom.plugin.PluginException
260      * If there is an error performing cleanup for this plugin
261      */

262     public void cleanup() throws PluginException {
263     }
264
265     /**
266      * Called when BlojsomServlet is taken out of service
267      *
268      * @throws org.blojsom.plugin.PluginException
269      * If there is an error in finalizing this plugin
270      */

271     public void destroy() throws PluginException {
272     }
273 }
Popular Tags