UserSession.java
Upload User: gdxydsw
Upload Date: 2019-01-29
Package Size: 16721k
Code Size: 11k
Category:

Java Develop

Development Platform:

Java

  1. /*
  2.  * Copyright (c) JForum Team
  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. import java.awt.image.BufferedImage;
  45. import java.io.Serializable;
  46. import java.util.Date;
  47. import net.jforum.ControllerUtils;
  48. import net.jforum.JForumExecutionContext;
  49. import net.jforum.SessionFacade;
  50. import net.jforum.repository.SecurityRepository;
  51. import net.jforum.security.PermissionControl;
  52. import net.jforum.security.SecurityConstants;
  53. import net.jforum.util.Captcha;
  54. import net.jforum.util.I18n;
  55. import net.jforum.util.preferences.ConfigKeys;
  56. import net.jforum.util.preferences.SystemGlobals;
  57. import com.octo.captcha.image.ImageCaptcha;
  58. /**
  59.  * Stores information about user's session.
  60.  * 
  61.  * @author Rafael Steil
  62.  * @version $Id: UserSession.java,v 1.37 2007/09/10 01:17:20 rafaelsteil Exp $
  63.  */
  64. public class UserSession implements Serializable
  65. {
  66. static final long serialVersionUID = 0;
  67. private long sessionTime;
  68. private int userId;
  69. private int privateMessages;
  70. private Date startTime;
  71. private Date lastVisit;
  72. private String sessionId;
  73. private String username;
  74. private String lang;
  75. private String ip;
  76. private boolean autoLogin;
  77. private ImageCaptcha imageCaptcha = null;
  78. public UserSession() {}
  79. public UserSession(UserSession us)
  80. {
  81. if (us.getStartTime() != null) {
  82. this.startTime = new Date(us.getStartTime().getTime());
  83. }
  84. if (us.getLastVisit() != null) {
  85. this.lastVisit = new Date(us.getLastVisit().getTime());
  86. }
  87. this.sessionTime = us.getSessionTime();
  88. this.userId = us.getUserId();
  89. this.sessionId = us.getSessionId();
  90. this.username = us.getUsername();
  91. this.autoLogin = us.getAutoLogin();
  92. this.lang = us.getLang();
  93. this.privateMessages = us.getPrivateMessages();
  94. this.imageCaptcha = us.imageCaptcha;
  95. this.ip = us.getIp();
  96. }
  97. public Date sessionLastUpdate()
  98. {
  99. return new Date(this.startTime.getTime() + this.sessionTime);
  100. }
  101. public void setIp(String ip)
  102. {
  103. this.ip = ip;
  104. }
  105. public String getIp()
  106. {
  107. return this.ip;
  108. }
  109. /**
  110.  * Set session's start time.
  111.  * 
  112.  * @param startTime  Start time in miliseconds
  113.  */
  114. public void setStartTime(Date startTime)
  115. {
  116. this.startTime = startTime;
  117. }
  118. /**
  119.  * @return Returns the privateMessages.
  120.  */
  121. public int getPrivateMessages()
  122. {
  123. return this.privateMessages;
  124. }
  125. /**
  126.  * @param privateMessages The privateMessages to set.
  127.  */
  128. public void setPrivateMessages(int privateMessages)
  129. {
  130. this.privateMessages = privateMessages;
  131. }
  132. /**
  133.  * Set session last visit time.
  134.  * 
  135.  * @param lastVisit Time in miliseconds
  136.  */
  137. public void setLastVisit(Date lastVisit)
  138. {
  139. this.lastVisit = lastVisit;
  140. }
  141. /**
  142.  * Set user's id
  143.  * 
  144.  * @param userId The user id
  145.  */
  146. public void setUserId(int userId)
  147. {
  148. this.userId = userId;
  149. }
  150. /**
  151.  * Set user's name
  152.  * 
  153.  * @param username The username
  154.  */
  155. public void setUsername(String username)
  156. {
  157. this.username = username;
  158. }
  159. public void setSessionId(String sessionId)
  160. {
  161. this.sessionId = sessionId;
  162. }
  163. public void setSessionTime(long sessionTime)
  164. {
  165. this.sessionTime = sessionTime;
  166. }
  167. public void setLang(String lang)
  168. {
  169. this.lang = lang;
  170. }
  171. /**
  172.  * Update the session time.
  173.  */
  174. public void updateSessionTime()
  175. {
  176. this.sessionTime = System.currentTimeMillis() - this.startTime.getTime();
  177. }
  178. /**
  179.  * Enable or disable auto-login.
  180.  * 
  181.  * @param autoLogin  <code>true</code> or <code>false</code> to represent auto-login status
  182.  */
  183. public void setAutoLogin(boolean autoLogin)
  184. {
  185. this.autoLogin = autoLogin;
  186. }
  187. /**
  188.  * Gets user's session start time
  189.  * 
  190.  * @return Start time in miliseconds
  191.  */
  192. public Date getStartTime()
  193. {
  194. return this.startTime;
  195. }
  196. public String getLang()
  197. {
  198. return this.lang;
  199. }
  200. /**
  201.  * Gets user's last visit time
  202.  * 
  203.  * @return Time in miliseconds
  204.  */
  205. public Date getLastVisit()
  206. {
  207. //return new GregorianCalendar(2007, 6, 28, 15, 15, 19).getTime();
  208. return this.lastVisit;
  209. }
  210. /**
  211.  * Gets the session time.
  212.  * 
  213.  * @return The session time
  214.  */
  215. public long getSessionTime()
  216. {
  217. return this.sessionTime;
  218. }
  219. /**
  220.  * Gets user's id
  221.  * 
  222.  * @return The user id
  223.  */
  224. public int getUserId()
  225. {
  226. return this.userId;
  227. }
  228. /**
  229.  * Gets the username
  230.  * 
  231.  * @return The username
  232.  */
  233. public String getUsername()
  234. {
  235. if (this.username == null && this.userId == SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID)) {
  236. this.username = I18n.getMessage("Guest");
  237. }
  238. return this.username;
  239. }
  240. /**
  241.  * Gets auto-login status
  242.  * 
  243.  * @return <code>true</code> if auto-login is enabled, or <code>false</code> if disabled.
  244.  */
  245. public boolean getAutoLogin()
  246. {
  247. return this.autoLogin;
  248. }
  249. /**
  250.  * Gets the session id related to this user session
  251.  * 
  252.  * @return A string with the session id
  253.  */
  254. public String getSessionId()
  255. {
  256. return this.sessionId;
  257. }
  258. /**
  259.  * Checks if the user is an administrator
  260.  * 
  261.  * @return <code>true</code> if the user is an administrator
  262.  */
  263. public boolean isAdmin()
  264. {
  265. return SecurityRepository.canAccess(this.userId, SecurityConstants.PERM_ADMINISTRATION);
  266. }
  267. /**
  268.  * Checks if the user is a moderator
  269.  * 
  270.  * @return <code>true</code> if the user has moderations rights
  271.  */
  272. public boolean isModerator()
  273. {
  274. return SecurityRepository.canAccess(this.userId, SecurityConstants.PERM_MODERATION);
  275. }
  276. /**
  277.  * Checks if the user can moderate a forum
  278.  * 
  279.  * @param forumId the forum's id to check for moderation rights
  280.  * @return <code>true</code> if the user has moderations rights
  281.  */
  282. public boolean isModerator(int forumId)
  283. {
  284. PermissionControl pc = SecurityRepository.get(this.userId);
  285. return (pc.canAccess(SecurityConstants.PERM_MODERATION))
  286. && (pc.canAccess(SecurityConstants.PERM_MODERATION_FORUMS, 
  287. Integer.toString(forumId)));
  288. }
  289. /**
  290.  * Makes the user's session "anoymous" - eg, the user. This method sets the session's start and
  291.  * last visit time to the current datetime, the user id to the return of a call to
  292.  * <code>SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID)</code> and finally sets
  293.  * session attribute named "logged" to "0" will be considered a non-authenticated / anonymous
  294.  * user
  295.  */
  296. public void makeAnonymous()
  297. {
  298. this.registerBasicInfo();
  299. ControllerUtils.addCookie(SystemGlobals.getValue(ConfigKeys.COOKIE_AUTO_LOGIN), null);
  300. ControllerUtils.addCookie(SystemGlobals.getValue(ConfigKeys.COOKIE_NAME_DATA),
  301. SystemGlobals.getValue(ConfigKeys.ANONYMOUS_USER_ID));
  302. SessionFacade.makeUnlogged();
  303. }
  304. /**
  305.  * Sets the startup and last visit time to now, as well set the
  306.  * user id to Anonymous. This method is usually called when the
  307.  * user hits the forum for the first time. 
  308.  */
  309. public void registerBasicInfo()
  310. {
  311. this.setStartTime(new Date(System.currentTimeMillis()));
  312. this.setLastVisit(new Date(System.currentTimeMillis()));
  313. this.setUserId(SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID));
  314. }
  315. /**
  316.  * Sets a new user session information using information from an <code>User</code> instance.
  317.  * This method sets the user id, username, the number of private messages, the session's start
  318.  * time ( set to the current date and time ) and the language.
  319.  * 
  320.  * @param user The <code>User</code> instance to get data from
  321.  */
  322. public void dataToUser(User user)
  323. {
  324. this.setUserId(user.getId());
  325. this.setUsername(user.getUsername());
  326. this.setPrivateMessages(user.getPrivateMessagesCount());
  327. this.setStartTime(new Date(System.currentTimeMillis()));
  328. this.setLang(user.getLang());
  329. }
  330. /**
  331.  * Get the captcha image to challenge the user
  332.  * 
  333.  * @return BufferedImage the captcha image to challenge the user
  334.  */
  335. public BufferedImage getCaptchaImage()
  336. {
  337. if (this.imageCaptcha == null) {
  338. return null;
  339. }
  340. return (BufferedImage)this.imageCaptcha.getChallenge();
  341. }
  342. /**
  343.  * Validate the captcha response of user
  344.  * 
  345.  * @param userResponse String the captcha response from user
  346.  * @return boolean true if the answer is valid, otherwise return false
  347.  */
  348. public boolean validateCaptchaResponse(String userResponse)
  349. {
  350. if ((SystemGlobals.getBoolValue(ConfigKeys.CAPTCHA_REGISTRATION) 
  351. || SystemGlobals.getBoolValue(ConfigKeys.CAPTCHA_POSTS))
  352. && this.imageCaptcha != null) {
  353. if (SystemGlobals.getBoolValue(ConfigKeys.CAPTCHA_IGNORE_CASE)) {
  354. userResponse = userResponse.toLowerCase();
  355. }
  356. boolean result =  this.imageCaptcha.validateResponse(userResponse).booleanValue();
  357. this.destroyCaptcha();
  358. return result;
  359. }
  360. return true;
  361. }
  362. /**
  363.  * create a new image captcha
  364.  * 
  365.  */
  366. public void createNewCaptcha()
  367. {
  368. this.destroyCaptcha();
  369. this.imageCaptcha = Captcha.getInstance().getNextImageCaptcha();
  370. }
  371. /**
  372.  * Destroy the current captcha validation is done
  373.  * 
  374.  */
  375. public void destroyCaptcha()
  376. {
  377. this.imageCaptcha = null;
  378. }
  379. /**
  380.      * @deprecated use JForumExecutionContext.getForumContext().isBot() instead
  381.      *
  382.      *
  383.  * Checks if it's a bot
  384.  * @return <code>true</code> if this user session is from any robot
  385.  */
  386. public boolean isBot()
  387. {
  388. //        return Boolean.TRUE.equals(JForumExecutionContext.getRequest().getAttribute(ConfigKeys.IS_BOT));
  389.         return JForumExecutionContext.getForumContext().isBot();
  390.     }
  391. /**
  392.  * @see java.lang.Object#equals(java.lang.Object)
  393.  */
  394. public boolean equals(Object o)
  395. {
  396. if (!(o instanceof UserSession)) {
  397. return false;
  398. }
  399. return this.sessionId.equals(((UserSession)o).getSessionId());
  400. }
  401. /**
  402.  * @see java.lang.Object#hashCode()
  403.  */
  404. public int hashCode()
  405. {
  406. return this.sessionId.hashCode();
  407. }
  408. }