Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When doing a manual sign_in for the user in Devise, how can you set remember me to yes?

In Devise, I'm signing in my user like this:

sign_in_and_redirect(:user, user)

In the default sign in page, there's a checkbox that the user can select so that they don't have to sign in again when they return to the site. But when you do the sign in with the sign_in_and_redirect(:user, user) line, I can't work out how to set that parameter to yes. Does anyone know how? Thanks for reading.

like image 929
ben Avatar asked Nov 09 '10 08:11

ben


People also ask

How does devise manage sessions?

Devise stores some information in the database ( last_sign_in_at , last_sign_in_ip , etc.), but relies on cookies to simulate stateful session consistency overtime. The cookie has a "TTL" or time to live, and that cookie is written to the browser when "remember me" is checked.

How does devise Rememberable work?

Rememberable manages generating and clearing token for remembering the user from a saved cookie. Rememberable also has utility methods for dealing with serializing the user into the cookie and back from the cookie, trying to lookup the record based on the saved information.


2 Answers

Did some testing. Presenting the findings for others.

The simplest solution, assuming the user object has the rememberable module defined on the devise declarable, is to set remember_me to true on the user before sign in and redirect:

@user.remember_me = true
sign_in_and_redirect(@user, :event => :authentication)
like image 129
Kieran Pilkington Avatar answered Nov 05 '22 07:11

Kieran Pilkington


current_user.remember_me!

https://github.com/plataformatec/devise/blob/master/lib/devise/models/rememberable.rb#L54

Note that this only updates the remember_created_at value of the user record. But for this to work correctly, a validation token also needs to be stored in the Devise cookie. To achieve both these things, follow Dmytrii's advise and user the remember_me <USER> controller method instead:

include Devise::Controllers::Rememberable
...
remember_me <USER_OBJECT>
like image 22
shingara Avatar answered Nov 05 '22 07:11

shingara