Reputation: 1745
I am using Devise-1.5.4 with Rails 3.0.20. Here are the facts that I am aware of:
current_user
, authenticate_user!
to validate a user.authenticate!
, which itself calls serialize_from_cookie
, that uses remember_token
to authenticate the user.I am a bit confused about the usage of session_id.
remember_token
)? How does devise validate the current_user?Upvotes: 5
Views: 2447
Reputation: 1326
The session cookie, as the name suggests, is valid for the current browser session only, i.e. it is not available if the browser is quit and reopened (unless you do something like restore session in which case browser restores the cookies from the previous session).
Remember cookie for extending the login period beyond the current session.
Devise uses warden and the way it works is :
1) Devise registers several strategies with warden - viz : Session key based auth, auth from params, auth from remember token etc.
2) When the request comes in warden runs each of those strategies
3) If any one strategy succeeds in authenticating the request warden sets the "user" (which you get via current_user helper method later) and stops running subsequent strategies
4) If none of the strategies succeed it is declared that no user is currently logged in (and current_user would return nil)
So in your case, if the session_id is set (i.e. the key warden.user.user.key
is set to a valid user id) the session based authentication strategy succeeds and the user is considered logged in. If that session is not available then warden moves on to next strategy and subsequently arrives at the "auth from remember_token" strategy. This strategy checks for the existence of a remember cookie. If presents, gets the token from that cookie, verifies if it is still valid and not expired. If so then it sets the "user" and user is considered logged in.
If the token has expired again the user is considered as not logged in.
If while logging in user does not select remember_me then the remember token is not set in the remember cookie. In such a case if the user closes his browser and opens it again (without restoring the previous session) then user is no longer logged into your system.
Reading through Warden documentation and warden code would be very helpful to understand this whole flow. You can put in debug print/log lines in the warden code and run your app to understand how all of this is working.
Upvotes: 8