はじめに
認証機能を実装するなら、Rails プラグインの restful_authentication を使うと簡単。
以下、作業メモ。
インストール
GitHub からプラグインをダウンロードする。
vendor/plugins ディレクトリに移動して次のコマンドを実行。
git clone git://github.com/technoweenie/restful-authentication.git restful_authentication
あらかじめ Git をインストールする必要あり。
ちなみに script/plugin ではインストールできなかった。
認証用のコンポーネント一式を生成
次のコマンドを実行。
ruby script/generate authenticated user sessions
user はユーザー情報を扱うモデルの名前。sessions はセッションを管理するコントローラの名前。コントローラの名前は複数形で指定すること。これでモデルやコントローラが生成される。
一緒にマイグレーション用ファイルが作られているので、
rake db:migrate
を実行してデータベースを作っておく。
認証用のヘルパーメソッドを全てのコントローラから使えるようにする
生成された UsersController を見てみる。
class UsersController < ApplicationController # ↓は ApplicationController に書く include AuthenticatedSystem end
AuthenticatedSystem はこのクラスではなく、ApplicationController に記述する。よって削除。
ApplicationController を開いて
class ApplicationController < ActionController::Base # 新しく追加 include AuthenticatedSystem end
の1行を追加。
ログインしないとコントローラのアクションを呼び出せないようにする
コントローラに次の1行を追加する。
class ItemsController < ApplicationController # 1行追加する before_filter :login_required
これで、ログインしていない状態でコントローラのアクションを呼び出そうとすると、ログインページに飛ぶようになる。