KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > jforum > ControllerUtils


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

44 package net.jforum;
45
46 import java.util.Date JavaDoc;
47 import java.util.HashMap JavaDoc;
48
49 import javax.servlet.http.Cookie JavaDoc;
50 import javax.servlet.http.HttpSession JavaDoc;
51
52 import net.jforum.dao.DataAccessDriver;
53 import net.jforum.dao.UserSessionDAO;
54 import net.jforum.entities.User;
55 import net.jforum.entities.UserSession;
56 import net.jforum.exceptions.DatabaseException;
57 import net.jforum.exceptions.ForumException;
58 import net.jforum.repository.SecurityRepository;
59 import net.jforum.security.SecurityConstants;
60 import net.jforum.sso.SSO;
61 import net.jforum.sso.SSOUtils;
62 import net.jforum.util.I18n;
63 import net.jforum.util.MD5;
64 import net.jforum.util.preferences.ConfigKeys;
65 import net.jforum.util.preferences.SystemGlobals;
66 import freemarker.template.SimpleHash;
67
68 /**
69  * Common methods used by the controller.
70  *
71  * @author Rafael Steil
72  * @version $Id: ControllerUtils.java,v 1.17 2006/01/29 15:07:00 rafaelsteil Exp $
73  */

74 public class ControllerUtils
75 {
76     /**
77      * Setup common variables used by almost all templates.
78      *
79      * @param context The context to use
80      */

81     public void prepareTemplateContext(SimpleHash context, JForumContext jforumcontext)
82     {
83         ActionServletRequest request = JForumExecutionContext.getRequest();
84         
85         context.put("karmaEnabled", SecurityRepository.canAccess(SecurityConstants.PERM_KARMA_ENABLED));
86         context.put("dateTimeFormat", SystemGlobals.getValue(ConfigKeys.DATE_TIME_FORMAT));
87         context.put("autoLoginEnabled", SystemGlobals.getBoolValue(ConfigKeys.AUTO_LOGIN_ENABLED));
88         context.put("sso", ConfigKeys.TYPE_SSO.equals(SystemGlobals.getValue(ConfigKeys.AUTHENTICATION_TYPE)));
89         context.put("contextPath", request.getContextPath());
90         context.put("serverName", request.getServerName());
91         context.put("templateName", SystemGlobals.getValue(ConfigKeys.TEMPLATE_DIR));
92         context.put("extension", SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
93         context.put("serverPort", Integer.toString(request.getServerPort()));
94         context.put("I18n", I18n.getInstance());
95         context.put("version", SystemGlobals.getValue(ConfigKeys.VERSION));
96         context.put("forumTitle", SystemGlobals.getValue(ConfigKeys.FORUM_PAGE_TITLE));
97         context.put("pageTitle", SystemGlobals.getValue(ConfigKeys.FORUM_PAGE_TITLE));
98         context.put("metaKeywords", SystemGlobals.getValue(ConfigKeys.FORUM_PAGE_METATAG_KEYWORDS));
99         context.put("metaDescription", SystemGlobals.getValue(ConfigKeys.FORUM_PAGE_METATAG_DESCRIPTION));
100         context.put("forumLink", SystemGlobals.getValue(ConfigKeys.FORUM_LINK));
101         context.put("homepageLink", SystemGlobals.getValue(ConfigKeys.HOMEPAGE_LINK));
102         context.put("encoding", SystemGlobals.getValue(ConfigKeys.ENCODING));
103         context.put("bookmarksEnabled", SecurityRepository.canAccess(SecurityConstants.PERM_BOOKMARKS_ENABLED));
104         context.put("JForumContext", jforumcontext);
105     }
106
107     /**
108      * Checks user credentials / automatic login.
109      *
110      * @param userSession The UserSession instance associated to the user's session
111      * @return <code>true</code> if auto login was enabled and the user was sucessfuly
112      * logged in.
113      * @throws DatabaseException
114      */

115     protected boolean checkAutoLogin(UserSession userSession)
116     {
117         String JavaDoc cookieName = SystemGlobals.getValue(ConfigKeys.COOKIE_NAME_DATA);
118
119         Cookie JavaDoc cookie = this.getCookieTemplate(cookieName);
120         Cookie JavaDoc hashCookie = this.getCookieTemplate(SystemGlobals.getValue(ConfigKeys.COOKIE_USER_HASH));
121         Cookie JavaDoc autoLoginCookie = this.getCookieTemplate(SystemGlobals.getValue(ConfigKeys.COOKIE_AUTO_LOGIN));
122
123         if (hashCookie != null && cookie != null
124                 && !cookie.getValue().equals(SystemGlobals.getValue(ConfigKeys.ANONYMOUS_USER_ID))
125                 && autoLoginCookie != null && "1".equals(autoLoginCookie.getValue())) {
126             String JavaDoc uid = cookie.getValue();
127             String JavaDoc uidHash = hashCookie.getValue();
128
129             String JavaDoc securityHash = SystemGlobals.getValue(ConfigKeys.USER_HASH_SEQUENCE);
130
131             if ((uid != null && !uid.equals("")) && (securityHash != null && !securityHash.equals(""))
132                     && (MD5.crypt(securityHash + uid).equals(uidHash))) {
133                 int userId = Integer.parseInt(uid);
134                 userSession.setUserId(userId);
135                 
136                 try {
137                     User user = DataAccessDriver.getInstance().newUserDAO().selectById(userId);
138     
139                     if (user == null || user.getId() != userId) {
140                         userSession.makeAnonymous();
141                         return false;
142                     }
143     
144                     this.configureUserSession(userSession, user);
145                 }
146                 catch (Exception JavaDoc e) {
147                     throw new DatabaseException(e);
148                 }
149                 
150                 return true;
151             }
152             
153             userSession.makeAnonymous();
154         }
155         
156         return false;
157     }
158
159     /**
160      * Setup optios and values for the user's session if authentication was ok.
161      *
162      * @param userSession The UserSession instance of the user
163      * @param user The User instance of the authenticated user
164      * @throws Exception
165      */

166     protected void configureUserSession(UserSession userSession, User user) throws Exception JavaDoc
167     {
168         userSession.dataToUser(user);
169
170         // As an user may come back to the forum before its
171
// last visit's session expires, we should check for
172
// existent user information and then, if found, store
173
// it to the database before getting his information back.
174
String JavaDoc sessionId = SessionFacade.isUserInSession(user.getId());
175
176         UserSession tmpUs = new UserSession();
177         if (sessionId != null) {
178             SessionFacade.storeSessionData(sessionId, JForumExecutionContext.getConnection());
179             tmpUs = SessionFacade.getUserSession(sessionId);
180             SessionFacade.remove(sessionId);
181         }
182         else {
183             UserSessionDAO sm = DataAccessDriver.getInstance().newUserSessionDAO();
184             tmpUs = sm.selectById(userSession, JForumExecutionContext.getConnection());
185         }
186
187         if (tmpUs == null) {
188             userSession.setLastVisit(new Date JavaDoc(System.currentTimeMillis()));
189         }
190         else {
191             // Update last visit and session start time
192
userSession.setLastVisit(new Date JavaDoc(tmpUs.getStartTime().getTime() + tmpUs.getSessionTime()));
193         }
194
195         // If the execution point gets here, then the user
196
// has chosen "autoLogin"
197
userSession.setAutoLogin(true);
198         SessionFacade.setAttribute("logged", "1");
199
200         I18n.load(user.getLang());
201     }
202
203     /**
204      * Checks for user authentication using some SSO implementation
205      */

206     protected void checkSSO(UserSession userSession)
207     {
208         try {
209             SSO sso = (SSO) Class.forName(SystemGlobals.getValue(ConfigKeys.SSO_IMPLEMENTATION)).newInstance();
210             String JavaDoc username = sso.authenticateUser(JForumExecutionContext.getRequest());
211
212             if (username == null || username.trim().equals("")) {
213                 userSession.makeAnonymous();
214             }
215             else {
216                 SSOUtils utils = new SSOUtils();
217
218                 if (!utils.userExists(username)) {
219                     HttpSession JavaDoc session = JForumExecutionContext.getRequest().getSession();
220
221                     String JavaDoc email = (String JavaDoc) session.getAttribute(SystemGlobals.getValue(ConfigKeys.SSO_EMAIL_ATTRIBUTE));
222                     String JavaDoc password = (String JavaDoc) session.getAttribute(SystemGlobals.getValue(ConfigKeys.SSO_PASSWORD_ATTRIBUTE));
223
224                     if (email == null) {
225                         email = SystemGlobals.getValue(ConfigKeys.SSO_DEFAULT_EMAIL);
226                     }
227
228                     if (password == null) {
229                         password = SystemGlobals.getValue(ConfigKeys.SSO_DEFAULT_PASSWORD);
230                     }
231
232                     utils.register(password, email);
233                 }
234
235                 this.configureUserSession(userSession, utils.getUser());
236             }
237         }
238         catch (Exception JavaDoc e) {
239             e.printStackTrace();
240             throw new ForumException("Error while executing SSO actions: " + e);
241         }
242     }
243
244     /**
245      * Do a refresh in the user's session. This method will update the last visit time for the
246      * current user, as well checking for authentication if the session is new or the SSO user has
247      * changed
248      *
249      * @throws Exception
250      */

251     public void refreshSession() throws Exception JavaDoc
252     {
253         UserSession userSession = SessionFacade.getUserSession();
254         ActionServletRequest request = JForumExecutionContext.getRequest();
255
256         if (userSession == null) {
257             userSession = new UserSession();
258             userSession.setSessionId(request.getSession().getId());
259             userSession.setIp(request.getRemoteAddr());
260
261             userSession.makeAnonymous();
262
263             if (!userSession.isBot()) {
264                 // Non-SSO authentications can use auto login
265
if (!ConfigKeys.TYPE_SSO.equals(SystemGlobals.getValue(ConfigKeys.AUTHENTICATION_TYPE))) {
266                     if (SystemGlobals.getBoolValue(ConfigKeys.AUTO_LOGIN_ENABLED)) {
267                         this.checkAutoLogin(userSession);
268                     }
269                 }
270                 else {
271                     this.checkSSO(userSession);
272                 }
273             }
274
275             SessionFacade.add(userSession);
276             SessionFacade.setAttribute(ConfigKeys.TOPICS_TRACKING, new HashMap JavaDoc());
277         }
278         else if (ConfigKeys.TYPE_SSO.equals(SystemGlobals.getValue(ConfigKeys.AUTHENTICATION_TYPE))) {
279             SSO sso = (SSO) Class.forName(SystemGlobals.getValue(ConfigKeys.SSO_IMPLEMENTATION)).newInstance();
280
281             // If SSO, then check if the session is valid
282
if (!sso.isSessionValid(userSession, request)) {
283                 SessionFacade.remove(userSession.getSessionId());
284                 refreshSession();
285             }
286         }
287         else {
288             SessionFacade.getUserSession().updateSessionTime();
289         }
290     }
291
292     /**
293      * Gets a cookie by its name.
294      *
295      * @param name The cookie name to retrieve
296      * @return The <code>Cookie</code> object if found, or <code>null</code> oterwhise
297      */

298     public static Cookie JavaDoc getCookie(String JavaDoc name)
299     {
300         Cookie JavaDoc[] cookies = JForumExecutionContext.getRequest().getCookies();
301
302         if (cookies != null) {
303             for (int i = 0; i < cookies.length; i++) {
304                 Cookie JavaDoc c = cookies[i];
305
306                 if (c.getName().equals(name)) {
307                     return c;
308                 }
309             }
310         }
311
312         return null;
313     }
314     
315     /**
316      * Template method to get a cookie.
317      * Useful to situations when a subclass
318      * wants to have a different way to
319      * retrieve a cookie.
320      * @param name The cookie name to retrieve
321      * @return The Cookie object if found, or null otherwise
322      * @see #getCookie(String)
323      */

324     protected Cookie JavaDoc getCookieTemplate(String JavaDoc name)
325     {
326         return ControllerUtils.getCookie(name);
327     }
328
329     /**
330      * Add or update a cookie. This method adds a cookie, serializing its value using XML.
331      *
332      * @param name The cookie name.
333      * @param value The cookie value
334      */

335     public static void addCookie(String JavaDoc name, String JavaDoc value)
336     {
337         Cookie JavaDoc cookie = new Cookie JavaDoc(name, value);
338         cookie.setMaxAge(3600 * 24 * 365);
339         cookie.setPath("/");
340
341         JForumExecutionContext.getResponse().addCookie(cookie);
342     }
343     
344     /**
345      * Template method to add a cookie.
346      * Useful to suatins when a subclass wants to add
347      * a cookie in a fashion different than the normal
348      * behaviour
349      * @param name The cookie name
350      * @param value The cookie value
351      * @see #addCookie(String, String)
352      */

353     protected void addCookieTemplate(String JavaDoc name, String JavaDoc value)
354     {
355         ControllerUtils.addCookie(name, value);
356     }
357 }
358
Popular Tags