开发者

How to remove previous sessions in Rails, if user forget to logout and close the browser?

I store all session information in database. The user can login the system for do something. There are some restricted area required user login. If the user try to reach those area before login, the system will redirect them to login page.

Sometimes user may close the browser without logout. If this happen, next time when he try to login, the system cannot recognized the newly generate session, even the user typed in the correct username and password. The system will then force the user login again.

Would anyone know how to fix this? I tried to reset the session using reset_session before loading the login page. The problem cannot be fixed.

Session Controller

  def new
  end

  def create
    session[:current_account] = Account.authenticate(params[:email], params[:password])
    if session[:current_account]
      redirect_to :controller => "xxxxx", :action => "index"
    else
      flash[:notice] = "Please try again."
      render :action => 'new'
    end
  end

Account Model

  def self.authenticate(email, pass)
    accou开发者_开发百科nt = find_by_email(email)
    account && account.authenticated?(pass) ? account : nil
  end

  def authenticated?(pass)
    encrypted_password == Account.encrypt(pass,salt)
  end

Xxxxx Controller

  before_filter :permission_handling

  def index
  end

Application Controller

  def permission_handling
    unless logged_in?
      forced_login
    end
  end

  def logged_in?
    session[:current_account].is_a?(Account)
  end

  def forced_login
    flash[:notice] = "You haven't login yet!"
    redirect_to ( :controller => "sessions", :action => "new" )
  end

Thanks all. :)


It looks like you're storing an Account object in the session. This is not recommended: you should store just simple values, like the account id in session.

Change Model.authenticate to return account.id, and check logged_in by loading the account from the database instead of keeping it in the session.

I'm not sure if this fully addresses the problem though, but it might be significant.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜