<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xml:lang="en-US">
  <title>BigBinary Blog: Rails 8</title>
  <subtitle>Deep technical writing on Ruby on Rails, performance, scaling, monitoring and engineering.</subtitle>
  <link rel="self" type="application/atom+xml" href="https://www.bigbinary.com/blog/categories/rails-8/feed.xml"/>
  <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/categories/rails-8"/>
  <id>https://www.bigbinary.com/blog/categories/rails-8</id>
  <updated>2024-08-09T00:00:00.000Z</updated>
  <author>
    <name>BigBinary</name>
    <uri>https://www.bigbinary.com/</uri>
  </author>
  <icon>https://www.bigbinary.com/favicon.ico</icon>
  <logo>https://www.bigbinary.com/images/bigbinary_square_big_logo.png</logo>
  <rights>Copyright 2024 Big Binary LLC</rights>
  <generator uri="https://nextjs.org">Next.js</generator>
  <entry>
      <title type="text"><![CDATA[Rails 8 introduces a basic authentication generator]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-8-introduces-a-basic-authentication-generator"/>
      <link rel="enclosure" type="image/jpeg" href="https://www.bigbinary.com/blog/images/social_preview_images/rails_basic_authentication_generator.jpg"/>
      <id>https://www.bigbinary.com/blog/rails-8-introduces-a-basic-authentication-generator</id>
      <published>2024-08-09T00:00:00.000Z</published>
      <updated>2024-08-09T00:00:00.000Z</updated>
      <author>
        <name>Jaimy Simon</name>
        <uri>https://www.bigbinary.com/blog/authors/jaimysimon</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 8"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/rails_basic_authentication_generator.jpg" width="1200" height="627"/>
      <summary type="text"><![CDATA[Rails 8.0 adds a generator that streamlines the process of adding basic authentication to Rails applications]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-8-introduces-a-basic-authentication-generator"><![CDATA[<p>DHH recently posted the following in an issue titled
<a href="https://github.com/rails/rails/issues/50446">Add basic authentication generator</a>.</p>
<blockquote>
<p>Rails now include all the key building blocks needed to do basic
authentication, but many new developers are still uncertain of how to put them
together, so they end up leaning on all-in-one gems that hide the mechanics.</p>
</blockquote>
<p>To address this, Rails 8 has introduced a generator that simplifies the addition
of basic authentication to Rails applications. In this blog post, we'll explore
the components included in this authentication scaffold.</p>
<h2>Adding authentication to your Rails application</h2>
<p>To set up a basic authentication system in your Rails application, execute the
following code.</p>
<pre><code class="language-bash">bin/rails generate authentication
</code></pre>
<p>This command generates a set of essential files that provide a foundational
start for implementing authentication, including support for database-tracked
sessions and password reset functionality. Here is the
<a href="https://gist.github.com/neerajsingh0101/55593d0ba2d6b24fb3fd728aa94c3fb3">gist</a>
of the generated scaffold.</p>
<p>Let’s examine the components created by the authentication generator.</p>
<h3>Models &amp; migrations</h3>
<p>To lay the groundwork for handling user accounts and session management, the
models
<a href="https://gist.github.com/neerajsingh0101/55593d0ba2d6b24fb3fd728aa94c3fb3#file-user-rb"><code>User</code></a>,
<a href="https://gist.github.com/neerajsingh0101/55593d0ba2d6b24fb3fd728aa94c3fb3#file-current-rb"><code>Current</code></a>
and
<a href="https://gist.github.com/neerajsingh0101/55593d0ba2d6b24fb3fd728aa94c3fb3#file-session-rb"><code>Session</code></a>
are set up along with their corresponding migrations. This setup includes:</p>
<ul>
<li>
<p><a href="https://gist.github.com/neerajsingh0101/55593d0ba2d6b24fb3fd728aa94c3fb3#file-xxxxxxx_create_users-rb"><code>CreateUsers</code></a>
migration: It creates a <code>users</code> table, with a uniquely indexed <code>email_address</code>
field and <code>password_digest</code> for storing the securely hashed passwords using
<a href="https://api.rubyonrails.org/v5.2/classes/ActiveModel/SecurePassword/ClassMethods.html#method-i-has_secure_password"><code>has_secure_password</code></a>.</p>
</li>
<li>
<p><a href="https://gist.github.com/jaimysimon/c0cf64cd0c6e5ab8adb470acf90db38e#file-xxxxxxx_create_sessions-rb"><code>CreateSessions</code></a>
migration: It sets up the <code>sessions</code> table, which includes a unique <code>token</code>
field, along with <code>ip_address</code> and <code>user_agent</code> fields to record the user's
device and network details. The <code>Session</code> model uses
<a href="https://api.rubyonrails.org/v7.1.3.4/classes/ActiveRecord/SecureToken/ClassMethods.html"><code>has_secure_token</code></a>
to generate unique session tokens.</p>
</li>
<li>
<p>The <code>Current</code> model manages per-request state and provides access to the
current user's information through a delegated <code>user</code> method.</p>
</li>
<li>
<p>Additionally, the <a href="https://github.com/bcrypt-ruby/bcrypt-ruby">bcrypt</a> gem is
added to the Gemfile. If this gem is not present, it is added; if it is
commented, it is uncommented, and then <code>bundle install</code> is run to install the
gem.</p>
</li>
</ul>
<h3>Authentication concern</h3>
<p>The core authentication logic and session management are encapsulated in the
<a href="https://gist.github.com/neerajsingh0101/55593d0ba2d6b24fb3fd728aa94c3fb3#file-authentication-rb"><code>Authentication</code></a>
concern.</p>
<ul>
<li>
<p><code>require_authentication</code>: This is a <code>before_action</code> callback which attempts to
restore an existing session with <code>resume_session</code>. If no session is found, it
redirects the user to the login page using <code>request_authentication</code>.</p>
</li>
<li>
<p><code>resume_session</code>: Retrieves a session using a signed token from the cookie via
the <code>find_session_by_cookie</code> method. Sets it as the current session, and saves
the token in a permanent, HTTP-only cookie using the <code>set_current_session</code>
method.</p>
</li>
<li>
<p><code>authenticated?</code>: A helper method that checks if the current user has an
active session.</p>
</li>
<li>
<p><code>allow_unauthenticated_access</code>: This class method allows specific actions to
bypass the <code>require_authentication</code> callback.</p>
</li>
<li>
<p><code>after_authentication_url</code>: Returns the URL to redirect to after
authentication.</p>
</li>
<li>
<p><code>start_new_session_for(user)</code>: Creates a new session for the given user with
details of the user's device and IP address and then sets the current session.</p>
</li>
<li>
<p><code>terminate_session</code>: Destroys the current session and removes the session
token from cookies.</p>
</li>
</ul>
<h3>Managing sessions</h3>
<p>The
<a href="https://gist.github.com/jaimysimon/c0cf64cd0c6e5ab8adb470acf90db38e#file-sessions_controller-rb"><code>SessionsController</code></a>
handles user session management and includes the following actions:</p>
<ul>
<li>
<p><code>new</code>: Renders a login form for the user credentials. The
<a href="https://gist.github.com/jaimysimon/c0cf64cd0c6e5ab8adb470acf90db38e#file-sessions_new-html-erb"><code>new.html.erb</code></a>
file includes fields for email and password, displays flash messages for
success and errors, and provides a link for password recovery.</p>
</li>
<li>
<p><code>create</code>: Authenticates the user with the provided credentials. On success, it
creates a new session and redirects to the <code>after_authentication_url</code>; on
failure, it redirects to the login form with an error message.</p>
</li>
<li>
<p><code>destroy</code>: Terminates the user’s session and redirects to the login form.</p>
</li>
</ul>
<p>Combining all of this, a basic authentication flow would look like this.</p>
<br />
<p><img src="https://www.bigbinary.com/blog/images/images_used_in_blog/2024/rails-8-introduces-a-basic-authentication-generator/user-authentication.png" alt="Flow of a basic authentication system"></p>
<br />
<h3>Password reset functionality</h3>
<p>The basic password reset functionality includes initiating a password reset
request, dispatching reset instructions via email, and updating the password.
The
<a href="https://gist.github.com/jaimysimon/c0cf64cd0c6e5ab8adb470acf90db38e#file-passwords_controller-rb"><code>PasswordsController</code></a>
manages these actions as follows:</p>
<ul>
<li>
<p><code>new</code>: Displays the form to request a password reset using the
<a href="https://gist.github.com/jaimysimon/c0cf64cd0c6e5ab8adb470acf90db38e#file-passwords_new-html-erb"><code>new.html.erb</code></a>
template.</p>
</li>
<li>
<p><code>create</code>: Handles the reset request, sends a reset email via the
<a href="https://gist.github.com/jaimysimon/c0cf64cd0c6e5ab8adb470acf90db38e#file-passwords_mailer-rb"><code>PasswordMailer</code></a>
if the user exists, and redirects with a notice. This email contains a link to
the password reset page, which includes a <code>password_reset_token</code> as a
parameter. The <code>password_reset_token</code> is part of the
<a href="https://github.com/rails/rails/pull/52483">newly added configuration</a> to
<code>has_secure_password</code>. It has a default expiration period of 15 minutes.</p>
</li>
<li>
<p><code>edit</code>: Renders the
<a href="https://gist.github.com/jaimysimon/c0cf64cd0c6e5ab8adb470acf90db38e#file-edit-html-erb"><code>edit.html.erb</code></a>
template to set a new password.</p>
</li>
<li>
<p><code>update</code>: Updates the user's password, redirects on success, or shows an alert
on failure.</p>
</li>
<li>
<p><code>set_user_by_token</code>: It is the <code>before_action</code> callback for the <code>edit</code> and
<code>update</code> actions which retrieve the user based on the <code>password_reset_token</code>
provided in the request parameters, ensuring proper identification of the
user.</p>
<p>Putting these together, the flow of resetting the password would be as
follows:</p>
</li>
</ul>
<br />
<p><img src="https://www.bigbinary.com/blog/images/images_used_in_blog/2024/rails-8-introduces-a-basic-authentication-generator/password-reset.png" alt="Flow of password reset"></p>
<br />
<h2>Current limitations and considerations</h2>
<p>The current authentication generator supports email-password login for existing
users but does not handle new account creation. Future updates may incorporate
user account creation and other customizations.</p>
<p>Please check out the following pull requests for more details:</p>
<ul>
<li>https://github.com/rails/rails/pull/52328</li>
<li>https://github.com/rails/rails/pull/52472</li>
<li>https://github.com/rails/rails/pull/52483</li>
</ul>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 8 introduces a built-in rate limiting API]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-8-rate-limiting-api"/>
      <link rel="enclosure" type="image/jpeg" href="https://www.bigbinary.com/blog/images/social_preview_images/rails_introduces_a_built_in_rate_limiting_api.jpg"/>
      <id>https://www.bigbinary.com/blog/rails-8-rate-limiting-api</id>
      <published>2024-02-13T00:00:00.000Z</published>
      <updated>2024-02-13T00:00:00.000Z</updated>
      <author>
        <name>Yedhin Kizhakkethara</name>
        <uri>https://www.bigbinary.com/blog/authors/yedhink</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 8"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/rails_introduces_a_built_in_rate_limiting_api.jpg" width="1200" height="627"/>
      <summary type="text"><![CDATA[Rails 8.0 adds rate limiting to ActionController which uses Active Support cache by default]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-8-rate-limiting-api"><![CDATA[<p>In the dynamic world of web development, managing the flow of requests is
crucial for maintaining a responsive and reliable application. Rate limiting is
a powerful technique that acts as the traffic cop for your API, ensuring fair
access to resources and preventing potential chaos. In a nutshell, rate limiting
is the practice of controlling the rate of requests a user, device, or
application can make within a set timeframe.</p>
<p>In this blog post, we'll delve into the concept of rate limiting, exploring its
significance and implementation in Rails 8.0.</p>
<h2>The Need for Rate Limiting</h2>
<p>It's crucial in ensuring the following:</p>
<ul>
<li>Security Shield: Guards against Denial-of-Service (DoS) attacks, thwarting
malicious attempts to flood your app and crash it.</li>
<li>Resource Balance: Prevents resource abuse by capping heavy users, ensuring
fair resource distribution and maintaining optimal app performance.</li>
<li>Brute-Force Defender: Stalls hackers attempting password guesses or exploiting
vulnerabilities through relentless, repeated attempts.</li>
</ul>
<h2>How Rack::Attack Paved the Way</h2>
<p>In the pre-Rails 8.0 era, the go-to solution for rate limiting was the
<a href="https://github.com/rack/rack-attack"><code>rack-attack</code></a> gem. This gem allowed
developers to set up rate-limiting rules by adding custom code in the
<code>rack_attack.rb</code> file. While effective, this approach required manual
intervention for each endpoint and could become cumbersome in a growing
application. This external dependency brought its own set of challenges, such as
the need for custom code and constant vigilance over rate-limited endpoints.</p>
<h2>Rails 8.0: Native Rate Limiting</h2>
<p>Rails 8.0 brings a native rate-limiting feature to the Action Controller,
streamlining the process and eliminating the need for external gems. Developers
can now set rate limits directly within their controllers using the <code>rate_limit</code>
method.</p>
<p>Let's take a look at the usage:</p>
<h3>Define Limits</h3>
<p>Utilize the <code>rate_limit</code> method within your controller actions, specifying the
maximum allowed requests and the corresponding timeframe. The <code>rate_limit</code>
method accepts the following parameters:</p>
<ul>
<li><code>to</code>: The maximum number of requests allowed, beyond which the rate limiting
error will be raised, that is with a <strong>429 Too Many Requests</strong> response.</li>
<li><code>within</code>: The maximum number of requests allowed in a given time window.</li>
<li><code>only</code>: Which all controller actions ought to be rate limited.</li>
<li><code>except</code>: Which all controller actions to be omitted from rate limiting.</li>
</ul>
<p>An example:</p>
<pre><code class="language-rb">class SignupController &lt; ApplicationController
  rate_limit to: 4, within: 1.minute, only: :create

  def create
    # ...
  end
end
</code></pre>
<h3>Granular Control</h3>
<p>Target specific actions or employ custom logic for nuanced control. For
instance, you can limit requests based on domain instead of IP address.</p>
<pre><code class="language-rb">rate_limit to: 4, within: 1.minute, by: -&gt; { request.domain }, only: :create
</code></pre>
<h3>Tailored Responses</h3>
<p>By default, rate-limited requests receive a <code>429 Too Many Requests</code> error.
However, you can personalize the response for a more informative user
experience.</p>
<pre><code class="language-rb">rate_limit to: 4, within: 1.minute, with: -&gt; { redirect_to(ip_restrictions_controller_url), alert: &quot;Signup Attempts failed four times. Please try again later.&quot; }, only: :create
</code></pre>
<h2>Custom Cache Stores</h2>
<p>The Rails 8.0 rate-limiting implementation at the moment allows us to make use a
wide range of backends as its store.</p>
<p>It includes:</p>
<ul>
<li>Memcached</li>
<li>Redis (including alternative Redis clients like Dalli)</li>
<li>Database-backed stores</li>
<li>File-based stores</li>
</ul>
<p>The Rate Limiting API seamlessly integrates with Rails' caching mechanisms,
leveraging
<a href="https://api.rubyonrails.org/classes/ActiveSupport/Cache.html"><code>ActiveSupport::Cache</code></a>
stores. Developers can specify custom cache stores if they require separate
handling for rate limits compared to other cache data. This integration ensures
efficient storage and retrieval of rate limit data, optimizing performance. An
example:</p>
<pre><code class="language-rb">class SignupController &lt; ApplicationController
  RATE_LIMIT_STORE = ActiveSupport::Cache::RedisCacheStore.new(url: ENV[&quot;REDIS_URL&quot;])
  rate_limit to: 8, within: 2.minutes, store: RATE_LIMIT_STORE
end
</code></pre>
<h2>What to look forward to</h2>
<p>At the moment the built-in rate limiting feature is limited in its
extensibility. There are cases where this feature cannot be used as a direct
replacement for logic that's based on <code>rack-attack</code> gem. A good example is a
scenario where we might want to use an exponential backoff based rate limiting
algorithm, which can be implemented using <code>rack-attack</code> gem but not with the
built-in Rails feature at the moment.</p>
<p>Right now, we are constrained to stick to the default cache counter algorithm
that Rails comes shipped with. In the future, we can expect a more generic limiter
interface, allowing users to explore advanced rate-limiting algorithms such as
exponential backoff, leaky bucket, or token bucket, etc. This change would open
the door for developers to swap the implementation based on their specific
requirements.</p>
<p>Please check out the following pull requests for more details:</p>
<ul>
<li>https://github.com/rails/rails/pull/50490</li>
<li>https://github.com/rails/rails/pull/50781</li>
</ul>
]]></content>
    </entry>
</feed>