Tutorial

👋 Admin, welcome to the Lato tutorial!

How to Protect a Page

To authenticate a page and prevent public access by unauthenticated users, you can use one of the methods provided by the Lato::Sessionable concern (already included via Lato::ApplicationController):

class TutorialController < ApplicationController
  def index
    return unless authenticate_session
  end
end

To apply the rule to all actions in the controller, you can simply use before_action:

class TutorialController < ApplicationController
  before_action :authenticate_session

  def index; end
end

Notes

Just like authenticate_session, you can also use its opposite not_authenticate_session to hide a page from authenticated users.
Example:

class AuthenticationController < ApplicationController
  before_action :not_authenticate_session, only: %i[signin]
  before_action :authenticate_session, only: %i[signout]

  def signin; end

  def signout; end
end

Limiting the Number of Requests

To limit the number of requests to a page, you can use the limit_request method:

class TutorialController < ApplicationController
  before_action :authenticate_session
  before_action :limit_request, only: %i[index]

  def index; end
end

The limit_request method accepts two parameters: limit (default: 10) and time_window (default: 10.minutes).
These parameters define the maximum number of requests a user can make within a given time window.

Source code: Lato::Sessionable

Accessing the Logged-in User

The user currently logged into Lato is always accessible in all controllers and views through the @session instance of the Lato::Session model:

class TutorialController < ApplicationController
  # ...

  def index
    @user_id = @session.user_id
    @user = @session.user.first_name
  end

  # ...
end

Notes

Using @session.user_id instead of @session.user.id avoids triggering a query on the users table, improving performance!

@session.valid? lets you check whether the user is logged in or not.

Source code: Lato::Session

You are offline You are online