LoginSignup
2
2

More than 5 years have passed since last update.

ActiveAdminでログイン認証時にパスワード以外の条件も見る

Last updated at Posted at 2017-04-02

やりたいこと

パスワード認証部分はActiveAdmin + Devise頼みで良いけど、そのユーザーが休止状態かどうかなど他のフラグも確認して、管理画面へのアクセスをコントロールしたい。

AuthorizationAdapterでやると、リダイレクトループしたりうまくいきませんでしたが、この方法でうまくいきました。環境は、以下の通り。

  • Rails 4.2.8
  • ActiveAdmin 1.0.0.pre5
  • Devise 4.2.1

ApplicationControllerにカスタム認証処理を追加

Userモデルに仮にis_alive?メソッドがあることを仮定します。これがfalseならパスワードは通っても認証させないようにする。

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  〜中略〜

  #
  # カスタム認証処理。メソッド名は任意
  #
  def custom_authenticate_user!
    # ActiveAdmin + Deviseで自動生成されたメソッドで、まず認証する。
    # メソッド名は指定したユーザーのモデル名に依存する。
    # AppUserモデルならauthenticate_app_user!となる。
    authenticate_user!

    if !current_user.is_alive?
      # Deviseでサインアウト処理してセッションを消す
      sign_out current_user
      # フラッシュにエラーを入れる
      flash[:alert] = "お前に食わせるセッションはねえ or ログイン権限がありません"
      # ログイン画面へリダイレクト
      # ログイン画面のURLを得るスマートな方法ないかな・・・
      redirect_to root_path + "admin/login"
    end
  end
end

ちょっと個人的に気持ち悪いと思うのは、authenticate_user!、sign_outメソッドは、ApplicationControllerを継承した先のAdmin::***Controllerのものであること。superクラスからサブクラスでしか宣言されてないメソッドを呼ぶことに・・・

ActiveAdminのconfigを修正

config/initializers/active_admin.rb
ActiveAdmin.setup do |config|
  〜中略〜
  # ApplicationControllerで宣言したメソッドを指定
  config.authentication_method = :custom_authenticate_user!
  〜中略〜
end

これでいけるはず。

2
2
0

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
  3. You can use dark theme
What you can do with signing up
2
2