KickJava   Java API By Example, From Geeks To Geeks.

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


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.blojsom.authorization.AuthorizationException;
36 import org.blojsom.authorization.AuthorizationProvider;
37 import org.blojsom.blog.Blog;
38 import org.blojsom.blog.Entry;
39 import org.blojsom.plugin.Plugin;
40 import org.blojsom.plugin.PluginException;
41 import org.blojsom.plugin.permission.PermissionChecker;
42 import org.blojsom.util.BlojsomConstants;
43 import org.blojsom.util.BlojsomUtils;
44 import org.blojsom.util.resources.ResourceManager;
45
46 import javax.servlet.ServletConfig JavaDoc;
47 import javax.servlet.http.HttpServletRequest JavaDoc;
48 import javax.servlet.http.HttpServletResponse JavaDoc;
49 import javax.servlet.http.HttpSession JavaDoc;
50 import java.io.IOException JavaDoc;
51 import java.util.HashMap JavaDoc;
52 import java.util.Locale JavaDoc;
53 import java.util.Map JavaDoc;
54
55 /**
56  * BaseAdminPlugin
57  *
58  * @author David Czarnecki
59  * @version $Id: BaseAdminPlugin.java,v 1.3 2006/04/17 16:04:12 czarneckid Exp $
60  * @since blojsom 3.0
61  */

62 public class BaseAdminPlugin implements Plugin, PermissionedPlugin {
63
64     protected static final Log _logger = LogFactory.getLog(BaseAdminPlugin.class);
65
66     // Constants
67
protected static final String JavaDoc BLOJSOM_ADMIN_PLUGIN_AUTHENTICATED_KEY = "org.blojsom.plugin.admin.Authenticated";
68     protected static final String JavaDoc BLOJSOM_ADMIN_PLUGIN_USERNAME_KEY = "org.blojsom.plugin.admin.Username";
69     protected static final String JavaDoc BLOJSOM_ADMIN_PLUGIN_USERNAME = "BLOJSOM_ADMIN_PLUGIN_USERNAME";
70     protected static final String JavaDoc BLOJSOM_ADMIN_PLUGIN_USERNAME_PARAM = "username";
71     protected static final String JavaDoc BLOJSOM_ADMIN_PLUGIN_PASSWORD_PARAM = "password";
72     protected static final String JavaDoc ACTION_PARAM = "action";
73     protected static final String JavaDoc SUBACTION_PARAM = "subaction";
74     protected static final String JavaDoc BLOJSOM_ADMIN_PLUGIN_OPERATION_RESULT = "BLOJSOM_ADMIN_PLUGIN_OPERATION_RESULT";
75     protected static final String JavaDoc BLOJSOM_USER_AUTHENTICATED = "BLOJSOM_USER_AUTHENTICATED";
76     protected static final String JavaDoc BLOJSOM_ADMIN_MESSAGES_RESOURCE = "org.blojsom.plugin.admin.resources.messages";
77     protected static final String JavaDoc BLOJSOM_PERMISSION_CHECKER = "BLOJSOM_PERMISSION_CHECKER";
78     protected static final String JavaDoc PLUGIN_ADMIN_INHERIT_APACHE_CREDENTIALS = "plugin-admin-inherit-apache-credentials";
79
80     // Localization constants
81
protected static final String JavaDoc LOGIN_ERROR_TEXT_KEY = "login.error.text";
82
83     // Pages
84
protected static final String JavaDoc ADMIN_ADMINISTRATION_PAGE = "/org/blojsom/plugin/admin/templates/admin";
85     protected static final String JavaDoc ADMIN_LOGIN_PAGE = "/org/blojsom/plugin/admin/templates/admin-login";
86     protected static final String JavaDoc ADMIN_AJAX_RESPONSE = "/org/blojsom/plugin/admin/templates/admin-ajax-response";
87
88     // Actions
89
protected static final String JavaDoc LOGIN_ACTION = "login";
90     protected static final String JavaDoc LOGOUT_ACTION = "logout";
91     protected static final String JavaDoc PAGE_ACTION = "page";
92
93     protected ServletConfig JavaDoc _servletConfig;
94     protected AuthorizationProvider _authorizationProvider;
95     protected ResourceManager _resourceManager;
96     protected Map JavaDoc _ignoreParams;
97
98     /**
99      * Default constructor.
100      */

101     public BaseAdminPlugin() {
102     }
103
104     /**
105      * Set the {@link ServletConfig} for the fetcher to grab initialization parameters
106      *
107      * @param servletConfig {@link ServletConfig}
108      */

109     public void setServletConfig(ServletConfig JavaDoc servletConfig) {
110         _servletConfig = servletConfig;
111     }
112
113     /**
114      * Set the authorization provider for use by this plugin
115      *
116      * @param authorizationProvider {@link AuthorizationProvider}
117      */

118     public void setAuthorizationProvider(AuthorizationProvider authorizationProvider) {
119         _authorizationProvider = authorizationProvider;
120     }
121
122     /**
123      * Set the resource manager for use by this plugin
124      *
125      * @param resourceManager {@link ResourceManager}
126      */

127     public void setResourceManager(ResourceManager resourceManager) {
128         _resourceManager = resourceManager;
129     }
130
131     /**
132      * Initialize this plugin. This method only called when the plugin is instantiated.
133      *
134      * @throws PluginException If there is an error initializing the plugin
135      */

136     public void init() throws PluginException {
137         _ignoreParams = new HashMap JavaDoc();
138         _ignoreParams.put(BLOJSOM_ADMIN_PLUGIN_USERNAME_PARAM, BLOJSOM_ADMIN_PLUGIN_USERNAME_PARAM);
139         _ignoreParams.put(BLOJSOM_ADMIN_PLUGIN_PASSWORD_PARAM, BLOJSOM_ADMIN_PLUGIN_PASSWORD_PARAM);
140         _ignoreParams.put("submit", "submit");
141         _ignoreParams.put("reset", "reset");
142     }
143
144     /**
145      * Authenticate the user if their authentication session variable is not present
146      *
147      * @param httpServletRequest Request
148      * @param httpServletResponse Response
149      * @param context Context
150      * @param blog {@link Blog} information
151      * @return <code>true</code> if the user is authenticated, <code>false</code> otherwise
152      */

153     protected boolean authenticateUser(HttpServletRequest JavaDoc httpServletRequest, HttpServletResponse JavaDoc httpServletResponse, Map JavaDoc context, Blog blog) {
154         BlojsomUtils.setNoCacheControlHeaders(httpServletResponse);
155         HttpSession JavaDoc httpSession = httpServletRequest.getSession();
156         boolean logout = false;
157
158         // Check first to see if someone has requested to logout
159
String JavaDoc action = BlojsomUtils.getRequestValue(ACTION_PARAM, httpServletRequest);
160         if (action != null && LOGOUT_ACTION.equals(action)) {
161             httpSession.removeAttribute(blog.getBlogAdminURL() + "_" + BLOJSOM_ADMIN_PLUGIN_AUTHENTICATED_KEY);
162             httpSession.removeAttribute(BLOJSOM_USER_AUTHENTICATED);
163             httpSession.removeAttribute(BlojsomConstants.REDIRECT_TO_PARAM);
164             logout = true;
165         }
166
167         StringBuffer JavaDoc redirectURL = new StringBuffer JavaDoc();
168         redirectURL.append(httpServletRequest.getRequestURI());
169         if (!redirectURL.toString().endsWith("/")) {
170             redirectURL.append("/");
171         }
172         if (httpServletRequest.getParameterMap().size() > 0) {
173             redirectURL.append("?");
174             redirectURL.append(BlojsomUtils.convertRequestParams(httpServletRequest, _ignoreParams));
175         }
176
177         if (Boolean.valueOf(blog.getProperty(PLUGIN_ADMIN_INHERIT_APACHE_CREDENTIALS)).booleanValue() && !BlojsomUtils.checkNullOrBlank(httpServletRequest.getRemoteUser()))
178         {
179             String JavaDoc remoteUsername = httpServletRequest.getRemoteUser();
180             _logger.debug("Retrieved remote_user from server: " + remoteUsername);
181
182             httpSession.setAttribute(blog.getBlogAdminURL() + "_" + BLOJSOM_ADMIN_PLUGIN_AUTHENTICATED_KEY, Boolean.TRUE);
183             httpSession.setAttribute(blog.getBlogAdminURL() + "_" + BLOJSOM_ADMIN_PLUGIN_USERNAME_KEY, remoteUsername);
184             httpSession.setAttribute(BLOJSOM_ADMIN_PLUGIN_USERNAME, remoteUsername);
185             httpSession.setAttribute(BLOJSOM_USER_AUTHENTICATED, Boolean.TRUE);
186             _logger.debug("Passed remote_user authentication for username: " + remoteUsername);
187         }
188
189         // Otherwise, check for the authenticated key and if not authenticated, look for a "username" and "password" parameter
190
if (httpSession.getAttribute(blog.getBlogAdminURL() + "_" + BLOJSOM_ADMIN_PLUGIN_AUTHENTICATED_KEY) == null) {
191             String JavaDoc username = httpServletRequest.getParameter(BLOJSOM_ADMIN_PLUGIN_USERNAME_PARAM);
192             String JavaDoc password = httpServletRequest.getParameter(BLOJSOM_ADMIN_PLUGIN_PASSWORD_PARAM);
193
194             if (username == null || password == null || "".equals(username) || "".equals(password)) {
195                 _logger.debug("No username/password provided or username/password was empty");
196                 _logger.debug("Setting redirect_to attribute to: " + redirectURL.toString());
197                 if (!logout) {
198                     httpServletRequest.getSession().setAttribute(BlojsomConstants.REDIRECT_TO_PARAM, redirectURL.toString());
199                 }
200
201                 return false;
202             }
203
204             // Check the username and password against the blog authorization
205
try {
206                 _authorizationProvider.authorize(blog, null, username, password);
207                 httpSession.setAttribute(blog.getBlogAdminURL() + "_" + BLOJSOM_ADMIN_PLUGIN_AUTHENTICATED_KEY, Boolean.TRUE);
208                 httpSession.setAttribute(blog.getBlogAdminURL() + "_" + BLOJSOM_ADMIN_PLUGIN_USERNAME_KEY, username);
209                 httpSession.setAttribute(BLOJSOM_ADMIN_PLUGIN_USERNAME, username);
210                 httpSession.setAttribute(BLOJSOM_USER_AUTHENTICATED, Boolean.TRUE);
211                 _logger.debug("Passed authentication for username: " + username);
212
213                 return true;
214             } catch (AuthorizationException e) {
215                 _logger.debug("Failed authentication for username: " + username);
216                 addOperationResultMessage(context, formatAdminResource(LOGIN_ERROR_TEXT_KEY, LOGIN_ERROR_TEXT_KEY, blog.getBlogAdministrationLocale(), new Object JavaDoc[]{username}));
217                 _logger.debug("Setting redirect_to attribute to: " + redirectURL.toString());
218                 if (!logout) {
219                     httpServletRequest.getSession().setAttribute(BlojsomConstants.REDIRECT_TO_PARAM, redirectURL.toString());
220                 }
221
222                 return false;
223             }
224         } else {
225             context.put(BLOJSOM_PERMISSION_CHECKER, new PermissionChecker(blog, _authorizationProvider, context));
226
227             return ((Boolean JavaDoc) httpSession.getAttribute(blog.getBlogAdminURL() + "_" + BLOJSOM_ADMIN_PLUGIN_AUTHENTICATED_KEY)).booleanValue();
228         }
229     }
230
231     /**
232      * Retrieve the current authorized username for this session
233      *
234      * @param httpServletRequest Request
235      * @param blog {@link Blog}
236      * @return Authorized username for this session or <code>null</code> if no user is currently authorized
237      */

238     protected String JavaDoc getUsernameFromSession(HttpServletRequest JavaDoc httpServletRequest, Blog blog) {
239         return (String JavaDoc) httpServletRequest.getSession().getAttribute(blog.getBlogAdminURL() + "_" + BLOJSOM_ADMIN_PLUGIN_USERNAME_KEY);
240     }
241
242     /**
243      * Check the permission for a given username and permission
244      *
245      * @param blog {@link Blog} information
246      * @param permissionContext {@link java.util.Map} containing context information for checking permission
247      * @param username Username
248      * @param permission Permission
249      * @return <code>true</code> if the username has the required permission, <code>false</code> otherwise
250      */

251     public boolean checkPermission(Blog blog, Map JavaDoc permissionContext, String JavaDoc username, String JavaDoc permission) {
252         try {
253             _authorizationProvider.checkPermission(blog, permissionContext, username, permission);
254         } catch (AuthorizationException e) {
255             _logger.error(e);
256             return false;
257         }
258
259         return true;
260     }
261
262     /**
263      * Adds a message to the context under the <code>BLOJSOM_ADMIN_PLUGIN_OPERATION_RESULT</code> key
264      *
265      * @param context Context
266      * @param message Message to add
267      */

268     protected void addOperationResultMessage(Map JavaDoc context, String JavaDoc message) {
269         context.put(BLOJSOM_ADMIN_PLUGIN_OPERATION_RESULT, message);
270     }
271
272     /**
273      * Retrieve a resource from the administration resource bundle
274      *
275      * @param resourceID ID of resource to retrieve
276      * @param fallbackText Text to use as fallback if resource ID is not found
277      * @param locale {@link Locale} to use when retrieving resource
278      * @return Text from administration resource bundle given by <code>resourceID</code> or <code>fallbackText</code> if the resource ID is not found
279      */

280     protected String JavaDoc getAdminResource(String JavaDoc resourceID, String JavaDoc fallbackText, Locale JavaDoc locale) {
281         return _resourceManager.getString(resourceID, BLOJSOM_ADMIN_MESSAGES_RESOURCE, fallbackText, locale);
282     }
283
284     /**
285      * Retrieve a resource from the administration resource bundle and pass it through the {@link ResourceManager#format(String, Object[])} method
286      *
287      * @param resourceID ID of resource to retrieve
288      * @param fallbackText Text to use as fallback if resource ID is not found
289      * @param locale {@link Locale} to use when retrieving resource
290      * @param arguments Arguments for {@link ResourceManager#format(String, Object[])}
291      * @return Text from administration resource bundle given by <code>resourceID</code> formatted appropriately or <code>fallbackText</code> if the resource ID could not be formatted
292      */

293     protected String JavaDoc formatAdminResource(String JavaDoc resourceID, String JavaDoc fallbackText, Locale JavaDoc locale, Object JavaDoc[] arguments) {
294         String JavaDoc resourceText = getAdminResource(resourceID, fallbackText, locale);
295
296         String JavaDoc formattedText = _resourceManager.format(resourceText, arguments);
297         if (formattedText == null) {
298             formattedText = fallbackText;
299         }
300
301         return formattedText;
302     }
303
304     /**
305      * Process the blog entries
306      *
307      * @param httpServletRequest Request
308      * @param httpServletResponse Response
309      * @param blog {@link Blog} instance
310      * @param context Context
311      * @param entries Blog entries retrieved for the particular request
312      * @return Modified set of blog entries
313      * @throws PluginException If there is an error processing the blog entries
314      */

315     public Entry[] process(HttpServletRequest JavaDoc httpServletRequest, HttpServletResponse JavaDoc httpServletResponse, Blog blog, Map JavaDoc context, Entry[] entries) throws PluginException {
316         if (!authenticateUser(httpServletRequest, httpServletResponse, context, blog)) {
317             httpServletRequest.setAttribute(BlojsomConstants.PAGE_PARAM, ADMIN_LOGIN_PAGE);
318         } else {
319             String JavaDoc page = BlojsomUtils.getRequestValue(BlojsomConstants.PAGE_PARAM, httpServletRequest);
320             if (!BlojsomUtils.checkNullOrBlank(page)) {
321                 httpServletRequest.setAttribute(BlojsomConstants.PAGE_PARAM, page);
322             } else {
323                 httpServletRequest.setAttribute(BlojsomConstants.PAGE_PARAM, ADMIN_ADMINISTRATION_PAGE);
324             }
325
326             if (httpServletRequest.getSession().getAttribute(BlojsomConstants.REDIRECT_TO_PARAM) != null) {
327                 String JavaDoc redirectURL = (String JavaDoc) httpServletRequest.getSession().getAttribute(BlojsomConstants.REDIRECT_TO_PARAM);
328
329                 try {
330                     httpServletRequest.getSession().removeAttribute(BlojsomConstants.REDIRECT_TO_PARAM);
331                     httpServletResponse.sendRedirect(redirectURL);
332                 } catch (IOException JavaDoc e) {
333                     _logger.error(e);
334                 }
335             }
336         }
337
338         return entries;
339     }
340
341     /**
342      * Perform any cleanup for the plugin. Called after {@link #process}.
343      *
344      * @throws PluginException If there is an error performing cleanup for this plugin
345      */

346     public void cleanup() throws PluginException {
347     }
348
349     /**
350      * Called when BlojsomServlet is taken out of service
351      *
352      * @throws PluginException If there is an error in finalizing this plugin
353      */

354     public void destroy() throws PluginException {
355     }
356 }
357
Popular Tags