LoginSignup
0

More than 1 year has passed since last update.

Railsでログイン機能をシンプルに名前とパスワードだけで実装する(3)

Last updated at Posted at 2020-09-24

Railsでログイン機能をシンプルに名前とパスワードだけで実装する(2)の続き

概要

前回まででログイン機能はできたものの、現在の状態ではどのユーザーがログインしているか分からず、またログインしなくても一覧ページにアクセスできるという欠陥が残っている。それに対処していく

手順

current_roomメソッド。現在のログインしているユーザーを表示するヘルパーメソッドを追加する

/app/helpers/sessions_helper.rb

  # ログインしているユーザーがいたら、ユーザーを代入する
  def current_room
    if session[:room_id]
      @current_room ||= Room.find_by(id: session[:room_id])
    end
  end

今回はページに共通した部分がないので、不要ですが、必要ならログインしているかどうかを判断するヘルパーメソッドを定義します。

app/helpers/sessions_helper.rb

  # ログインしているかどうか判断する
  def logged_in?
    !current_room.nil?
  end

ログアウトメソッドを 2か所に書きます。

/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

あとは以下のようにログインユーザーの表示とログアウト用リンクを追加します。

/ログイン制御したページ.html

~
 <div class="header-title">
    <div class="header-title">受付一覧: 
    <%= current_room.name %>
    <%= link_to "Logout", logout_path, method: :delete %>
    </div>
 </div>
~

最後に一覧画面へアクセスする前にログイン制御したいので、プライベートメソッド内に定義します。

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] = "ログインが必要です"
        redirect_to login_path
      end
    end
~

これで一覧ページへのログイン機能が簡単にですが完成しました。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
0