KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > jforum > entities > UserSession


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  * This file creation date: 30/12/2003 / 21:40:54
40  * The JForum Project
41  * http://www.jforum.net
42  */

43 package net.jforum.entities;
44
45 import java.awt.image.BufferedImage JavaDoc;
46 import java.io.Serializable JavaDoc;
47 import java.util.Date JavaDoc;
48
49 import net.jforum.JForumExecutionContext;
50 import net.jforum.SessionFacade;
51 import net.jforum.repository.SecurityRepository;
52 import net.jforum.security.PermissionControl;
53 import net.jforum.security.SecurityConstants;
54 import net.jforum.util.Captcha;
55 import net.jforum.util.I18n;
56 import net.jforum.util.preferences.ConfigKeys;
57 import net.jforum.util.preferences.SystemGlobals;
58
59 import com.octo.captcha.image.ImageCaptcha;
60
61 /**
62  * Stores information about user's session.
63  *
64  * @author Rafael Steil
65  * @version $Id: UserSession.java,v 1.26 2006/01/29 15:07:08 rafaelsteil Exp $
66  */

67 public class UserSession implements Serializable JavaDoc
68 {
69     static final long serialVersionUID = 0;
70     
71     private long sessionTime;
72     
73     private int userId;
74     private int privateMessages;
75     
76     private Date JavaDoc startTime;
77     private Date JavaDoc lastVisit;
78     
79     private String JavaDoc sessionId;
80     private String JavaDoc username;
81     private String JavaDoc lang;
82     private String JavaDoc ip;
83     
84     private boolean autoLogin;
85     
86     private ImageCaptcha imageCaptcha = null;
87
88     public UserSession() {}
89
90     public UserSession(UserSession us)
91     {
92         if (us.getStartTime() != null) {
93             this.startTime = new Date JavaDoc(us.getStartTime().getTime());
94         }
95
96         if (us.getLastVisit() != null) {
97             this.lastVisit = new Date JavaDoc(us.getLastVisit().getTime());
98         }
99         
100         this.sessionTime = us.getSessionTime();
101         this.userId = us.getUserId();
102         this.sessionId = us.getSessionId();
103         this.username = us.getUsername();
104         this.autoLogin = us.getAutoLogin();
105         this.lang = us.getLang();
106         this.privateMessages = us.getPrivateMessages();
107         this.imageCaptcha = us.imageCaptcha;
108         this.ip = us.getIp();
109     }
110     
111     public Date JavaDoc sessionLastUpdate()
112     {
113         return new Date JavaDoc(this.startTime.getTime() + this.sessionTime);
114     }
115     
116     public void setIp(String JavaDoc ip)
117     {
118         this.ip = ip;
119     }
120     
121     public String JavaDoc getIp()
122     {
123         return this.ip;
124     }
125
126     /**
127      * Set session's start time.
128      *
129      * @param startTime Start time in miliseconds
130      */

131     public void setStartTime(Date JavaDoc startTime)
132     {
133         this.startTime = startTime;
134     }
135
136     /**
137      * @return Returns the privateMessages.
138      */

139     public int getPrivateMessages()
140     {
141         return this.privateMessages;
142     }
143
144     /**
145      * @param privateMessages The privateMessages to set.
146      */

147     public void setPrivateMessages(int privateMessages)
148     {
149         this.privateMessages = privateMessages;
150     }
151
152     /**
153      * Set session last visit time.
154      *
155      * @param lastVisit Time in miliseconds
156      */

157     public void setLastVisit(Date JavaDoc lastVisit)
158     {
159         this.lastVisit = lastVisit;
160     }
161
162     /**
163      * Set user's id
164      *
165      * @param userId The user id
166      */

167     public void setUserId(int userId)
168     {
169         this.userId = userId;
170     }
171
172     /**
173      * Set user's name
174      *
175      * @param username The username
176      */

177     public void setUsername(String JavaDoc username)
178     {
179         this.username = username;
180     }
181
182     public void setSessionId(String JavaDoc sessionId)
183     {
184         this.sessionId = sessionId;
185     }
186
187     public void setSessionTime(long sessionTime)
188     {
189         this.sessionTime = sessionTime;
190     }
191
192     public void setLang(String JavaDoc lang)
193     {
194         this.lang = lang;
195     }
196
197     /**
198      * Update the session time.
199      */

200     public void updateSessionTime()
201     {
202         this.sessionTime = System.currentTimeMillis() - this.startTime.getTime();
203     }
204
205     /**
206      * Enable or disable auto-login.
207      *
208      * @param autoLogin <code>true</code> or <code>false</code> to represent auto-login status
209      */

210     public void setAutoLogin(boolean autoLogin)
211     {
212         this.autoLogin = autoLogin;
213     }
214
215     /**
216      * Gets user's session start time
217      *
218      * @return Start time in miliseconds
219      */

220     public Date JavaDoc getStartTime()
221     {
222         return this.startTime;
223     }
224
225     public String JavaDoc getLang()
226     {
227         return this.lang;
228     }
229
230     /**
231      * Gets user's last visit time
232      *
233      * @return Time in miliseconds
234      */

235     public Date JavaDoc getLastVisit()
236     {
237         return this.lastVisit;
238     }
239
240     /**
241      * Gets the session time.
242      *
243      * @return The session time
244      */

245     public long getSessionTime()
246     {
247         return this.sessionTime;
248     }
249
250     /**
251      * Gets user's id
252      *
253      * @return The user id
254      */

255     public int getUserId()
256     {
257         return this.userId;
258     }
259
260     /**
261      * Gets the username
262      *
263      * @return The username
264      */

265     public String JavaDoc getUsername()
266     {
267         if (this.username == null && this.userId == SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID)) {
268             this.username = I18n.getMessage("Guest");
269         }
270         
271         return this.username;
272     }
273
274     /**
275      * Gets auto-login status
276      *
277      * @return <code>true</code> if auto-login is enabled, or <code>false</code> if disabled.
278      */

279     public boolean getAutoLogin()
280     {
281         return this.autoLogin;
282     }
283
284     /**
285      * Gets the session id related to this user session
286      *
287      * @return A string with the session id
288      */

289     public String JavaDoc getSessionId()
290     {
291         return this.sessionId;
292     }
293
294     /**
295      * Checks if the user is an administrator
296      *
297      * @return <code>true</code> if the user is an administrator
298      */

299     public boolean isAdmin() throws Exception JavaDoc
300     {
301         return SecurityRepository.canAccess(this.userId, SecurityConstants.PERM_ADMINISTRATION);
302     }
303
304     /**
305      * Checks if the user is a moderator
306      *
307      * @return <code>true</code> if the user has moderations rights
308      */

309     public boolean isModerator() throws Exception JavaDoc
310     {
311         return SecurityRepository.canAccess(this.userId, SecurityConstants.PERM_MODERATION);
312     }
313     
314     /**
315      * Checks if the user can moderate a forum
316      *
317      * @param forumId the forum's id to check for moderation rights
318      * @return <code>true</code> if the user has moderations rights
319      */

320     public boolean isModerator(int forumId) throws Exception JavaDoc
321     {
322         PermissionControl pc = SecurityRepository.get(this.userId);
323         
324         return (pc.canAccess(SecurityConstants.PERM_MODERATION))
325             && (pc.canAccess(SecurityConstants.PERM_MODERATION_FORUMS,
326                 Integer.toString(forumId)));
327     }
328
329     /**
330      * Makes the user's session "anoymous" - eg, the user. This method sets the session's start and
331      * last visit time to the current datetime, the user id to the return of a call to
332      * <code>SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID)</code> and finally sets
333      * session attribute named "logged" to "0" will be considered a non-authenticated / anonymous
334      * user
335      */

336     public void makeAnonymous()
337     {
338         this.setStartTime(new Date JavaDoc(System.currentTimeMillis()));
339         this.setLastVisit(new Date JavaDoc(System.currentTimeMillis()));
340         this.setUserId(SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID));
341
342         SessionFacade.setAttribute("logged", "0");
343     }
344
345     /**
346      * Sets a new user session information using information from an <code>User</code> instance.
347      * This method sets the user id, username, the number of private messages, the session's start
348      * time ( set to the current date and time ) and the language.
349      *
350      * @param user The <code>User</code> instance to get data from
351      */

352     public void dataToUser(User user)
353     {
354         this.setUserId(user.getId());
355         this.setUsername(user.getUsername());
356         this.setPrivateMessages(user.getPrivateMessagesCount());
357         this.setStartTime(new Date JavaDoc(System.currentTimeMillis()));
358         this.setLang(user.getLang());
359     }
360
361     /**
362      * Get the captcha image to challenge the user
363      *
364      * @return BufferedImage the captcha image to challenge the user
365      */

366     public BufferedImage JavaDoc getCaptchaImage()
367     {
368         if (this.imageCaptcha == null) {
369             return null;
370         }
371         
372         return (BufferedImage JavaDoc)this.imageCaptcha.getChallenge();
373     }
374
375     /**
376      * Validate the captcha response of user
377      *
378      * @param anwser String the captcha response from user
379      * @return boolean true if the answer is valid, otherwise return false
380      */

381     public boolean validateCaptchaResponse(String JavaDoc userResponse)
382     {
383         if ((SystemGlobals.getBoolValue(ConfigKeys.CAPTCHA_REGISTRATION)
384                 || SystemGlobals.getBoolValue(ConfigKeys.CAPTCHA_POSTS))
385                 && this.imageCaptcha != null) {
386             boolean result = this.imageCaptcha.validateResponse(userResponse).booleanValue();
387             this.destroyCaptcha();
388             return result;
389         }
390         
391         return true;
392     }
393
394     /**
395      * create a new image captcha
396      *
397      * @return void
398      */

399     public void createNewCaptcha()
400     {
401         this.destroyCaptcha();
402         this.imageCaptcha = Captcha.getInstance().getNextImageCaptcha();
403     }
404
405     /**
406      * Destroy the current captcha validation is done
407      *
408      * @return void
409      */

410     public void destroyCaptcha()
411     {
412         this.imageCaptcha = null;
413     }
414     
415     /**
416      * Checks if it's a bot
417      * @return <code>true</code> if this user session is from any robot
418      */

419     public boolean isBot()
420     {
421         return Boolean.TRUE.equals(JForumExecutionContext.getRequest().getAttribute(ConfigKeys.IS_BOT));
422     }
423     
424     /**
425      * @see java.lang.Object#equals(java.lang.Object)
426      */

427     public boolean equals(Object JavaDoc o)
428     {
429         if (!(o instanceof UserSession)) {
430             return false;
431         }
432         
433         return this.sessionId.equals(((UserSession)o).getSessionId());
434     }
435     
436     /**
437      * @see java.lang.Object#hashCode()
438      */

439     public int hashCode()
440     {
441         return this.sessionId.hashCode();
442     }
443 }
444
Popular Tags