Login request processing is a process to hide a specific page from users who are not logged in. This article is an easy solution to how to implement login request processing.
Prepare a helper in $ rails g helper sessions
and implement current_user
and logged_in?
.
app/helpers/sessions_helper.rb
module SessionsHelper
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
def logged_in?
!!current_user
end
end
def current_user
is a method to get the currently logged in user.
@current_user ||= User.find_by(id: session[:user_id])
Is
If the current login user is assigned to @ current_user
→ Do nothing.
If the current login user is not assigned to @ current_user
→ Get the login user fromUser.find_by (...)
and assign it to @ current_user
.
def logged_in?
Returns true if the user is logged in, false if the user is not logged in.
Let's think about the controller.
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
include SessionsHelper
private
def require_user_logged_in
unless logged_in?
redirect_to login_url
end
end
end
The method written in ApplicationController
can be used in all Controllers.
Define the require_user_logged_in
method.
The require_user_logged_in
method checks the login status, does nothing if you are logged in, and forces you back to the login page if you are not logged in.
The reason I wrote include SessionsHelper
is to be able to use thelogged_in?
Method defined in Helper.
Now let's use the require_user_logged_in
method in UsersController
.
app/controllers/users_controller.rb
class UsersController < ApplicationController
before_action :require_user_logged_in, only: [:index, :show]
#Omitted below
For the index and show specified in before_action, the require_user_logged_in
method is executed as preprocessing.
For example, when a person accesses users # index, if that person logs in, they can see users # index. However, if you are not logged in, you will be taken to the login page. In this way, you can create membership-based services. that's all.
Recommended Posts