Although the login function was available up to the last time, there remains a defect that it is not possible to know which user is logged in in the current state, and the list page can be accessed without logging in. Deal with it
--current_room method. Add a helper method to show the currently logged in user
app/helpers/sessions_helper.rb
#If there is a logged-in user, substitute the user
def current_room
if session[:room_id]
@current_room ||= Room.find_by(id: session[:room_id])
end
end
--This time, there is nothing in common on the pages, so it is unnecessary, but if necessary, define a helper method to determine whether you are logged in.
app/helpers/sessions_helper.rb
#Determine if you are logged in
def logged_in?
!current_room.nil?
end
--Write the logout method in two places.
app/helpers/sessions_helper.rb
def log_out
session.delete(:room_id)
@current_room = nil
end
app/controllers/sessions_controller.rb
def destroy
log_out
redirect_to login_path
end
--After that, add a link for displaying the logged-in user and logging out as shown below.
Login controlled page
~
<div class="header-title">
<div class="header-title">Reception list:
<%= current_room.name %>
<%= link_to "Logout", logout_path, method: :delete %>
</div>
</div>
~
--Lastly, I want to control login before accessing the list screen, so define it in the private method.
app/controllers/receptions_controller.rb
class ReceptionsController < ApplicationController
before_action :logged_in_room, only: [:index]
~
private
def logged_in_room
unless logged_in?
flash[:alert] = "login is needed"
redirect_to login_path
end
end
~
Recommended Posts