11 月 18 2008
[rails] ユーザーのパスワード忘れ処理を簡単に生成してくれるプラグインforgot_password ( with Restful-authentication)
はじめに
Railsとrestful-authenticationの組み合わせで、パスワード忘れの機能を実装するにあたって、いろいろと参考になるものを探していたところ、簡単に機能を実装できるプラグインがあったので紹介。
forgot_passwordプラグイン
http://github.com/greenisus/forgot_password/tree/master
restful-authenticationを使う事前提で、script/generate forgot_passwordというジェネレータでちゃちゃっとパスワードを忘れた人用のページを作ってくれます。実際にやってみます。
準備
まずはプロジェクトのインストールから
% cd forgot_password_sample/
つづいてプラグインのインストール。gitコマンドが必要です。
% script/plugin install git://github.com/greenisus/forgot_password.git
そして、認証とパスワード忘れのジェネレーターを実行。
% script/generate forgot_password forgot_password user
forgot_passwordプラグインによって、以下のファイルが追加・編集されている
- 追加ファイル
- db/migrate/xxxxxxxxxxxxxx_create_forgot_passwords.rb
- app/models/forgot_password.rb
- app/models/forgot_password_mailer.rb
- app/controllers/forgot_passwords_controller.rb
- 修正ファイル
- config/routes.rb
修正
アクティベーション用のルートを設定。config/routes.rbに追加
forgot_passwordのバグなのか、パスワード用のモデル名にpassword以外を使うと、メール送信の行が2行、それも片方は存在しないクラス名で作られています。
app/controllers/forgot_passwords_controller.rbを修正して、使わない方の行をコメントアウトしておきます。
#PasswordMailer.deliver_reset_password(@user)
ForgotPasswordMailer.deliver_reset_password(@user)
確認
パスワード忘れを表すテーブルが追加されました。
def self.up
create_table "forgot_passwords" do |t|
t.integer :user_id
t.string :reset_code
t.datetime :expiration_date
t.timestamps
end
end
def self.down
drop_table "forgot_passwords"
end
end
パスワードの再設定を申請する名前付きルートとパスワードを再設定するルートが追加されています。
map.forgot_password '/forgot_password', :controller => 'forgot_passwords', :action => 'new'
map.change_password '/change_password/:reset_code', :controller => 'forgot_passwords', :action => 'reset'
map.resources :forgot_passwords
map.logout '/logout', :controller => 'sessions', :action => 'destroy'
map.login '/login', :controller => 'sessions', :action => 'new'
map.register '/register', :controller => 'users', :action => 'create'
map.signup '/signup', :controller => 'users', :action => 'new'
map.activate '/activate/:activation_code', :controller => 'users', :action => 'activate', :activation_code => nil
サーバを起動
% script/serve
サーバを起動して確認。
通常のrestful-autenticationのノリでユーザーを登録したあと
パスワード再設定の申請フォーム
http://localhost:3000/forgot_password
にアクセスすると、パスワードを再設定するためのメールフォームが表示されます。

登録したメールを入力してサブミットすると、パスワードをリセットするためのURLがメールで通知されました。

メールに記載されたURLを踏むと、パスワードの再設定画面が現れます。
http://localhost:3000/change_password/:reset_code

最後に
毎回同じファイルを書くのはバカバカしいのでこういったプラグインを使うのもありですね。
パスワード用のテーブルを生成しなければならないのをどう捉えるかにもよりますが、restful-authenticationで作ったモデルを全くいじらなくて良いのはコードが分離して見通しが良いです。
とりあえず自分は勉強のために、これから自分なりに実装してみようと思ってますけど。
よさそうすねー!
パスワード再設定はほぼ絶対使いますからねぇ。 role_requirementとかopen_id_authenticationとか、その他restful-authenticationのアドオンぽく使えるものをしばらく追ってみようかと