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.
- 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.
- 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.
- 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.
- 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!
