Amiga500
Amiga500

Reputation: 6141

Rails Session Management

I am trying to implement remember me option for login based on the code that I inherited.

I have following:

def login 
if request.post?
  if params[:remember_me]
    # this is where user checked the remember me box
    cookies[:login] = { :value => "XJ12", :expires => Time.now + 120}
  end

    session_user = User.authenticate(params[:user][:email], params[:user][:password])   
    if session_user

      session[:user] = session_user.id
      @user=User.find(session[:user])
      @user.update_attributes(:last_login_time => Time.now(),:is_logged => true)
      @user.save
      flash[:message]  = "Login successful."
      redirect_to "/admin"
    else
      flash[:warning] = "Your email or password is incorrect. Please re-enter."
    end
  end
end

end

No matter what I do, the cookie is automatically set (EXPIRES: session). I would like to make if user did not select remember me option, that I set cookie for 10 mins. If he selected remember me, then I will set it for much longer time. Can I get some guidance as what to do?

Upvotes: 1

Views: 1814

Answers (1)

Intrepidd
Intrepidd

Reputation: 20938

Firstly, Time.now + 120 is only 2 minutes from now, you should set it to a later value.

Then, here can be your flow :

  1. When trying to get the user, check if a cookie is set (I recommend you creating a unique random string for each user, since the cookies can be modified client side)
  2. If a cookie is set, log the corresponding user
  3. If not, try the basic log from session
  4. When connecting, register the cookie if the user has checked the box

Upvotes: 2

Related Questions