LoginSignup
2
2

More than 5 years have passed since last update.

rails_wardenをcontroller以外から呼び出す

Last updated at Posted at 2015-05-05

概要

Railsで認証を行う場合、代表的なものとしてDeviseやWardenといったgemが存在する。

  • Devise
    • 登録、セッション管理のバックエンドだけではなくmodelやviewも用意されているフルスタックなgem
  • Warden
    • セッション管理のみを行う非常にシンプルなgem

APIサーバを作る場合など、viewが必要無い場合Deviseは機能が過剰である。
そういう場合はWardenを使ったほうが必要十分で良いと思う。

Wardenでは、Rails用にrails_wardenというgemが用意されている。
rails_wardenでは、wardenの認証をcontrollerから呼び出せるようにmoduleがmixinされている。

controllerをで普通に実装する場合は非常に便利であるが、json_rpcサーバーを作る場合など、別の場所で認証したい場合、自分で使えるように設定する必要がある。

色々と試行錯誤した結果、後述のように設定することで使えるようになった。

基本設定

githubに書かれている設定を行う
https://github.com/hassox/rails_warden

controller以外で認証する設定

app/processorを作り、processorから認証を行う場合、ベースクラスで以下のように設定する。

class ApplicationProessor

    # 関連moduleをmixinする
    include Warden::Mixins::Common
    include RailsWarden::Mixins::HelperMethods
    include RailsWarden::Mixins::ControllerOnlyMethods

    # controllerからenvを渡してattr_accessorにセットする
    attr_accessor :env

    def initialize(env)
        self.env = env
    end

以上の設定で、controllerと同様にwardenを呼び出す事ができる

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