Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails and Devise - Access session data

I have a Rails app with devise integrated. I'm using the Cookie Store session. I need to store some data in the session everytime someone signs in, Eg. their user id. How can i do so with Devise?

May be there is some elegant way where i just dont need to do that and could access it with Devise itself.?

Thanks!

like image 488
Jasdeep Singh Avatar asked Mar 18 '11 04:03

Jasdeep Singh


People also ask

Where does Rails store session data?

In Rails, session object is sent back and forth inside cookies. When you set session[:user_id] = 3 inside of your controller action, the response sent from that action will have a header Set-Cookie: my-session-cookie .

What does devise store in session?

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 are sessions stored in Rails?

Rails uses ActionDispatch::Session::CookieStore as the default session storage. Learn more about other session storages in Action Controller Overview Guide. Rails CookieStore saves the session hash in a cookie on the client-side.

How does devise authentication work?

Devise is an excellent authentication system made for Rails that allows us to easily drop-in User functionality into our project. Devise only includes an email and password for registration, let's also add our own username to our User model. We also want to have a unique index on our username.


1 Answers

You can use the "session" variable inside the controllers. Something like session[:some_value] = "some_value"

Also Devise already has the user_id stored in the session.current_user helper method can be used here.

Also make sure you read this, it has details about the what to store in session or not. http://guides.rubyonrails.org/security.html

Also cookie session store is usually only 4k in size, so you can't store a lot of data in them or your app will start to error out.

like image 178
Rishav Rastogi Avatar answered Sep 21 '22 12:09

Rishav Rastogi