Warning! Before using this part you need to install the 'currentuser-services' gem. Check the process on the Resources page.

Restrict access to your application

To prevent an unauthenticated visitor to access your application, use :require_currentuser as before_action in your ApplicationController:

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :require_currentuser

This way, an unauthenticated visitor will be redirected to a sign-in page.

If you want to restrict access to a given part of your application, you can use :require_currentuser in specific controllers or actions:

# app/controllers/my_controller.rb
class MyController < ApplicationController
  before_action :require_currentuser, only: :restricted_action

  # All visitors can request this action.
  def public_action

  # Unauthenticated visitors requesting this action will be redirected to sign in page.
  def restricted_action

Identify user

To know which user is currently using your application, call the currentuser_id helper from any action or view. It returns nil if the visitor is not authenticated.

In a view:

<% # views/main/index.html.erb %>
Hello returning user, here is your id : <%= currentuser_id %>

Or in a controller action:

# controllers/main_controller.rb
class PostsController < ApplicationController

  # Retrieve all the posts owned by current user
  def index
    @posts = Post.where(owner_id: currentuser_id)

Sign in and out

The 'currentuser-services' gem provides the following url helpers, which can be used in any view or action:

# URL (HTTP GET) of a sign up form (see Registration section).

# URL (HTTP GET) of a sign in form.

# Navigating to the following URL (HTTP DELETE) cancels user authentication.
# Note that Rails session is NOT reset.

Here is a sample menu you may want to build:

<% # views/shared/_menu.html.erb %>
  <li><%= link_to 'Home', :root %></li>
  <% if currentuser_id %>
    <li><%= link_to 'Restricted action', '/my_controller/restricted_action' %></li>
    <li><%= button_to 'Sign out', currentuser_sign_out_url, method: :delete %></li>
  <% else %>
    <li><%= link_to 'Sign up', currentuser_sign_up_url %></li>
    <li><%= link_to 'Sign in', currentuser_sign_in_url %></li>
  <% end %>
Tip! Using the sign in URL is not mandatory. Provided you protect at least one of your actions with before_action :require_currentuser, a visitor reaching this action will be redirected to the sign-in form.