Table of contents
1.
Introduction
2.
Cookies
3.
Session 
4.
Need of session
5.
Flashes 
6.
Basic Principles
7.
Authentication
7.1.
Basic and Digest Authentication
8.
Devise 
9.
Frequently Asked Questions
9.1.
Describe the naming structure used in Rails.
9.2.
What does "Yield" mean in Ruby on Rails?
9.3.
Please explain the distinction between false and nil in Ruby.
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

Sessions, cookies and Authentication in Ruby on Rails

Author Shivani Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Before going into this topic, let us first discuss what is actually ruby on rails. Ruby programmers created the web application development framework known as Rails. It is intended to make web application programming simpler by assuming that all developers have the prerequisites for getting started. Compared to many other languages and frameworks, it enables you to write less code while doing more. Additionally, seasoned Rails developers claim that it increases the enjoyment of creating web applications.

Software with an opinion is Rails. It assumes that there is an "optimal" way to complete a task, and it is intended to promote that approach while, in some situations, discouraging others.

Have you ever wondered how a web application can learn so much about a person just by using it? Like how frequently they visit the site, where they are located, what their login is, or even when to slap them with a paywall since they have used up all of the free content available to them? Along with all the requests, a local file called a cookie that contains user information is transmitted. Unfortunately, despite being small, these cookies are not sweet.

All of this is due to cookies. a miraculous little data token that Lou Montulli created in 1994 and changed the internet. 

A cookie is a transient local file that stores information about a user and retains that information until it is manually erased, expires, or the session has finished. In order to serialize these files into key-value pairs (hashes) and store them in a session, Ruby on Rails parses cookies.

Cookies

When a user visits a website, a web server sends cookies to the user's web browser.

They are essentially one or more pieces of data stored as text strings on a user's computer. When a user accesses a website, the web server sends data to the browser via a cookie, which the computer stores locally. Your browser sends the cookie back to the server each time you ask for another page from it. In addition to any information you have voluntarily provided, including your name, location, or interests, these files frequently include details about your previous visits to the website.

Cookie storage is constant on the client. They have a size restriction of approximately 4 kilobytes and allow user interaction. In other words, a user can view, edit, and delete cookies from their computer.

Web applications are now significantly more dynamic thanks to the use of cookies. Basic cookies are not the greatest method for transmitting sensitive information between the client and web server, though, as the data is saved as plain text and is open to user intervention.

Rails provide access to a particular hash called cookies, where each key-value combination is saved as a separate cookie on the user's browser, allowing you to operate with cookies. You may access your browser's developer tools and view a cookie on the user's browser that has a key of hair-color and a value of blonde if you saved cookies[:hair-color] = "blonde". Utilizing cookies, remove it. delete(:hair-color).

The browser will send all of the cookies with each new request to your server, and you may access them in your controllers and views just like any other hash. Additionally, you can specify when they expire by using syntax like cookies[:name] = "cookies YUM", expires: Time.now + 3600".

Session 

When a user is logged in, a specific type of cookie called a session is used to store data about the user. On the server side, access to this information might be made later. The key distinction between a session and a cookie is that the former store's specific information about the user, while the latter collectively stores data from all your browsers. When a person closes their browser, the session ends.

Sessions, for instance, enable users to log in just once and stay logged in for subsequent requests. They enable secure cookie-based client-server communication for web applications powered by Rails. Consider how much of the data sent in cookies is accessible to the user. This is acceptable for some data, but sensitive data like credit card numbers, usernames, and passwords shouldn't be shared so openly.

Similar to how the aforementioned cookies hash is accessed, Rails provides access to the session hash. In your views or controllers, use the session variable as follows:

# app/controllers/users_controller.rb
 …
# Set a session value 
session[:current_user_id] = user.id 
# Access a session value 
some_other_variable_value = session[:other_variable_key] 
# Reset a session key 
session[:key_to_be_reset] = nil # Reset the entire session 
reset_session 
...

Need of session

Sessions enable user tracking and state persistence because HTTP is stateless. Consider sessions as trackers; they keep track of a user's logged-in status so that they are not required to check in or provide authentication each time a request is made to the application. They assist in maintaining the user's data across requests so that it is not lost while the user is browsing a website. A user-specific memory cookie called Session keeps track of the user's information and preferences.

A fresh session is instantly started when a new user accesses the application. The application will load a session that matches the current user's id if the user already exists. A hash of values and a session id often make up a session. Cookies are exchanged back and forth between the client's browser and the program. A unique session hash belonging to that user is located in a cookie and may be found using the session id.

You can set a session to the current user with the below:

session[:user_id] = @current_user.id

OR retrieve a specific user’s session:

User.find(session[:user_id])

Flashes 

Flash is a unique hash (a method that behaves like a hash) that lasts only between requests. It can be compared to a session hash that, once opened, self-destructs. For the user to receive success and failure messages after submitting forms, it is frequently used to transfer messages from the controller to the view.

How do you deliver that success message if you want to pop up "Thanks for signing up!" on the user's browser after performing the #create action (which typically utilizes redirect to take the user to a completely new page when successful)? Because the redirect forced the browser to send a fresh HTTP request, you cannot use an instance variable.

To see the flash messages, the view code must still be written. Writing a quick view helper that will pin any available flash message(s) to the top of the browser is a frequent practice. Additionally, you may add a class to the message to create custom CSS, such as turning success messages green and error messages red.

# app/views/layouts/application.html.erb
... 
<% flash. each do |name, message| %>
<div class="<%= name %>"><%= message %></div> 
<% end %>

Basic Principles

You must take a few extra steps if you want user logins. It's important to note that there are already well-proven solutions available that you may utilize in your projects; therefore, you should never develop your own authentication system. Devise is one among them, which we will examine later. But knowing a few fundamentals is helpful.

  1. We don't keep passwords in the database as plain text. That invites difficulty from the get-go. An encrypted "password digest" version of the password will be kept instead.
  2. Instead of immediately comparing a user's submitted password with a plaintext version of that password, the login form actually converts the submitted password into a digest form.
  3. A password string can be easily converted into a digest, but it is more challenging to decrypt the digest and obtain the original password. The best method for breaking a large number of digests is just to create a massive list of potential passwords, convert them to digests, and then check to see whether those digests match the digest you're trying to break.
  4. You need a mechanism to remember your user for more than just the duration of the browser session if you want to "remember" them (you've probably seen the "remember me" checkbox on login forms plenty of times). For an encrypted remember token (or whatever you want to call it), you'll need to add a new column to your Users table.

Authentication

Rails support authentication in several different methods. The most popular of these techniques use cookies, which are files kept in the user's browser. Authorization is used to ensure that a person making a request to the server is a legitimate user who is logged in and has the necessary permissions to do so.

There are many moving pieces in the field of authentication, making it seem like a rather complex subject. However, at its core, utilizing browser cookies in one way or another, you're verifying that the person making a request is truly a signed-in user with the necessary rights.

You should now have a better understanding of how intricate login procedures can get, but you should also have a clearer understanding of the websites you've visited many times. You'll soon be integrating Auth into your applications because it isn't difficult to do.

Cookies save data in HTTP headers, which are then kept in a user's browser as plain text. Users can easily manage and set these cookies, raising serious security issues owing to possible data breaches.

The session technique is utilized in its place since it operates like a hash, concealing data in serialized key/value pairs that are set in:

config/secrets.yml


Then, this information is hidden away as a huge string contained in a single enormous cookie called:

_YOUR_RAILS_APP_NAME_session


Rails use the sign method, which accepts a message and a key and returns a signature in string form as seen below, to create a signature to prevent tampering with those cookies.

# sign(message: string, key: string) -> signature: string
def sign(message, key):
  # Here the cookie data is cryptographically signed, making it tamper-proof
  return signature
end

Basic and Digest Authentication

HTTP Basic authentication can be used if you want a very informal and unsafe method of authenticating users. It entails passing login and password (unencrypted) across the network in response to a straightforward form. You can restrict access to specific controllers without it by using the #http_basic_authenticate function to accomplish this.

Use HTTP Digest Authentication for an authentication mechanism that is somewhat more secure than HTTP. It depends on a #before action calling a method that executes #authenticate_or_request_with_http_digest, which accepts a block and ought to return the "right" password that ought to have been supplied.

Both have the drawback of hard-coding user names and passwords into your controller (or somewhere else), making them only band-aid fixes.

Devise 

The device is a gem that was created to manage all of this for you. Overall, it's superior to developing your own auth because they've addressed many edge circumstances and security gaps that you might not consider. For communicating with APIs like OAuth, Devise enables you to communicate with more sophisticated authentication mechanisms.

Create a variety of sign-in and sign-up forms for you, along with tools to make them more easily implementable. It consists of ten modules (and you can choose which ones you want to use). To drop their files into your application, you install the devise gem and launch the installation. In order to add their additional fields to your Users table, you'll also need to do a database migration. Configuration consists of your use cases only.

Frequently Asked Questions

Describe the naming structure used in Rails.

All letters are lowercase, and words are separated by underscores when specifying variables.

Module and Class: Each word in modules and classes begins with an uppercase letter, uses mixed case, and lacks an underscore.

The table in a database: All database table names must be plural and contain lowercase letters and underscores between words. 

Model: It is represented by an unbroken MixedCase and the table name is always singular.

Controller: OrdersController would be the controller for the order table because controller class names are always written in the plural.

What does "Yield" mean in Ruby on Rails?

When a Ruby method receives a code block, it calls it by using the "Yield" keyword.

Please explain the distinction between false and nil in Ruby.

In Ruby, Nil is an object of NilClass that denotes the lack of a value, whereas false is an object of the FalseClass to represent a boolean value. Its object id is 4.

Conclusion

To conclude this blog, firstly, we discussed what the need for cookies, sessions, and authentication is. We also discussed the concepts of flashes here. We discussed the basic principles of knowing when to log in anywhere. We saw basic and digest authentication. Last but not least, we discussed devices.  For more content about ruby on rails and how to do projects with them, kindly refer to all our here. We also have courses on how to master ruby on rails; kindly check them out here, and for more information, go through our course here. The major differences between ruby and ruby on rails are discussed here.  For all other information regarding ruby on rails, visit our page here.

For more content, Refer to our guided paths on Coding Ninjas Studio to upskill yourself.

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

 

Live masterclass