How to load Rails Session from session_id? - ruby-on-rails

I am using MyApp::Application.config.session_store :active_record_store in my application to store Sessions in the database. It all works fine. However, I'd like to be able to load a specific Session when passed the session_id. This is the value that the server stores as a cookie on the client side.
My Rails application has a client that can't use cookies, so it has to pass me the session_id in a parameter. I'd like to use a before_action or some sort of filter to take that parameter and use it to load the session in my Controllers instead of the app loading a null session due to the lack of proper cookies.
Is there some way I can do this? I don't want to turn off the cookie method altogether because my web client uses cookies, it's just my mobile client that can't.
edit:
if I declare class Session < ActiveRecord::Base and then do Session.find_by_session_id('whatever') I do get a Session ActiveRecord object, but I'm not sure how to make this into a usable session in the normal Rails sense.

Just do request.session_options[:id] = "whatever you want" in a before_action filter and Rails will use that session_id to load the Session when you access it (thanks to lazy loading).

Related

Are session variables in 'session' or 'user_session' in Rails with Devise?

I want to store a non-critical non-confidential piece of information in the user's session in a Ruby on Rails app. The user model is set up with Devise. How do I do this? Various guides give conflicting and incomplete information about it. session[:foo]? user_session[:foo]? Do I need to set something up to be able to use whichever it is - e.g. get a gem, config something, or insert any lines before setting the session variable?
To provide context - the user may be creating multiple new items back-to-back, so it would be nice if the new form remembered and pre-selected the category based on what they selected previously. If there's a better way to do this, I'm open to suggestions. I'm new to all this. Thank you!!
Are session variables in 'session' or 'user_session' in Rails?
The simple answer is the session variables is named session.
A session usually consists of a hash of values and a session id, usually a 32-character string, to identify the hash. Every cookie sent to the client's browser includes the session id. And the other way round: the browser will send it to the server on every request from the client. In Rails you can save and retrieve values using the session method:
session[:cat_id] = cat_id
Category.find(session[:cat_id])
You can read this Rails Guide about session.
ActionDispatch::Session::CookieStore
The default Rails session object is accessible via the session helper method. It gives you an access to some chunks of data and is bound to a cookie value stored in your browser.
The user_session helper is provided by the Devise gem. It gives you additional security by restricting access to specific session data while user is authenticated on a server.

How session works in Rails

I Learn about session in rails. Most of the reference says that, the following is the way to create a session.
Example:
session[:id]=user.id
Session is a global hash. My doubt is, if session is a global hash, then If more than one user try's to login, then the session variable gets
overwrite or not ? Because, there will be only one global hash. So, if millions of user gets login, then how the same "session[:id]" hold
all the users sessions. Is it possible to store more than one value in a single variable. And also how to delete a session for a particular
user. So, how session is handled in rails?
session is not a global hash. It's a method that returns a new hash in the context of each request. How that hash is created depends on the underlying session store.
Let's take a look at 2 typical session stores.
Encrypted cookie store
This is the default session store of Rails applications. Rails serializes then encrypts the whole session hashes into cookies, and stores those cookies on the clients (e.g. browsers). Each time a request hits Rails app, Rails decrypts then deserializes that session cookie to a hash. That hash is what the method session returns.
Redis session store
This session store is not shipped with Rails. It's a separate gem.
With this session store, Rails serializes the session, gives it an ID (called session ID), and stores the ID-hash pair into Redis. Rails then set the session ID to cookie and send that cookie to the client. Each time a request hits Rails app, Rails retrieves the session ID from the cookie, gets the serialized session associated with that session ID from Redis, and deserializes that into a hash. That hash is what the method session returns.
Most applications need to keep track of certain state of a particular
user. This could be the contents of a shopping basket or the user id
of the currently logged in user...Rails will create a new session automatically if a new user
accesses the application. It will load an existing session if the user
has already used the application.
A session usually consists of a hash of values and a session id,
usually a 32-character string, to identify the hash. Every cookie sent
to the client's browser includes the session id. And the other way
round: the browser will send it to the server on every request from
the client.
http://guides.rubyonrails.org/security.html
In other words, each unique user has their own session hash. "Global" means that the session hash can be accessed inside any action/method.
As 7stud stated, all sessions are created on a user by user basis. Since HTTP is a "stateless" protocol, you would potentially need someone to enter their login information everytime they wanted to look at a new page or even refresh the existing one. This is where sessions comes in. In Rails, each session is assigned a unique session id (a 32 character string of random hex numbers) when it's created and a cookie containing this id is then sent to the client's browser. From that point on, every request from the browser sends the session id back to the server thus maintaining continuity. Normal guidelines to follow are you should only keep track of the bare minimum in a session such as info to determine the current user (like a primary key etc.).

How does session and cookie work in Rails 4?

As I understand one of the strategies to store sessions is store it in the cookie. There is one thing I don't understand from the docs:
To prevent session hash tampering, a digest is calculated from the
session with a server-side secret and inserted into the end of the
cookie.
What does this mean? How do they prevent that, if I get a cookie from another user, and I use it in my browser, I can't pretend I am the other user? I guess I don't understand what session hash tampering means.
How do they prevent that, if I get a cookie from another user, and I
use it in my browser, I can't pretend I am the other user?
This is called session hijacking, and is covered in http://guides.rubyonrails.org/security.html#session-hijacking. The recommended way to to mitigate this is by "always forcing SSL connection in your application config file", like so:
config.force_ssl = true
The whole http://guides.rubyonrails.org/security.html is definitely worth a read, for more goodness like this.

Session misunderstanding in Ruby on Rails

I'm working under rails and, as a beginner, I am trying to understand how the session feature works.
I put my sessions under active record, but when I do this:
#request = Facebook::Request.parse_signed_request(params[:signed_request],
Settings.facebook.app_secret)
puts session
#admin = Admin.find_by_fb_userid(#request["user_id"])
session[#request["user_id"]] = #admin ? #admin : nil
My session continue to display:
{}
Thanks for your help !
How session works?
HTTP is a stateless protocol.It means that it treats each request as an independent transaction
that is unrelated to any previous request so that the communication consists of independent
pairs of requests and responses.
A stateless protocol does not require the server to retain session
information or status about each communications partner for the duration of multiple requests.
The protocol provides no means of storing a user's data between requests.
Therefore, we use Sessions, which allows us to chain multiple requests together into a conversation between client and server, so temporaly keep data.
Session is a hash, so you can add a data into session like to regular hash:
For example, to add a new order into the session can look like this:
e.g. OrdersController
def new
#order = current_user.orders.create # creates a new order for current_user
session[:order] = #order.to_params # adds order information to the session.
end
Sessions can store any kind of string data, but best served by keeping it as small as possible for both speed and security,as third party users can easily decode what information is stored in sessions.
UPDATE
by default session data are stored as cookies but Rails allows to configure session storage in database using ActiveRecordStore or inmemory storage with Redis and Redis store. Each approach has its advantages and disadvantages.
Try printing the session value instead of whole session object:
puts session[#request['user_id']]
Do this before and after setting a session. And make sure you cleanup the session before testing this in browser (clear cookies or start incognito session).
And last but not least, it a bad idea to store whole objects in session. This way you are storing way more data in the session than needed. Try storing just the object id (in your case #admin.id) and then load it whenever needed.
Ok my fault was that I was working on a facebook app I guess and for every refresh, the session is reset by the peer.
But when I continued in my process, everything instantly worked.
And even if session is a stateless protocol, it is used, through the storage that is used to keep the session active all along the session.
Like in PHP or every single language

Can Cakephp read session data from Rails?

I have a Rails's application and i saved user's session in sessions table. It's run on domain example.com
Now I'm developing a CakePHP's application run on subdomain cakephp.example.com. How can i reuse session from Rails's app? Thanks in advance.
Yes it can although I'm not sure why you would want to. Assuming you are using Cookie Store the session is simply base64 encoded.
$rails_session = base64_decode($_COOKIE['_foobar_session']);
Obviously you need to replace the cookie name. Additionally you won't be able to modify the rails session and use it in rails again because there are some security restrictions to tampering with it. You can disable them but I wouldn't suggest doing that.
Another option is to store the session in the database in which case you can access it just like you would for any data.
EDIT: After rereading your question it seems like you would want to read the session in initially like I stated above and use that to create a new session in cakephp.

Resources