-
Acts as Authenticatedを使ってみた 2007-08-15 00:00:00
Acts as Authenticatedを使ってみました。Railsに認証機能を備えることができるpluginです。今まではLoginEngineとかLoginGeneraterとかいろいろあったと思うけど、Acts as Authenticatedはシンプルで使いやすくて簡単。
1.インストール
script/plugin install http://svn.techno-weenie.net/projects/plugins/acts_as_authenticated
2.コントローラ、ビュー、モデル、テーブルの作成script/generate authenticated user account rake db:migrate
基本的にはこれだけです。めちゃ簡単。/account/signupにアクセスすれば、サインアップ画面が表示されると思います。文章は適宜日本語に変えましょう。
さらに、よくあるようなメールを使ったサインアップもできます。
3.メール関係のモデル等を作成
script/generate authenticated_mailer user
4.observerの設定。
Acts as Authenticatedではobserverでuserテーブルを監視していて、createのときにそれをフックしてメールを送信するような仕組みになっているようです。
ただしObserverメソッドはRails2.0でなくなってしまうようなので、かわりにconfig/environment.rbのRails::Initializer.runブロック内に以下の文を追加しましょう。Rails::Initializer.run do |config| config.active_record.observers = :user_observer end
5.userモデルへのカラム追加
migrationを使用して、usersテーブルに以下のふたつのカラムを追加します。add_column :users, :activation_code, :string, :limit => 40 add_column :users, :activated_at, :datetime
rake db:migrateを忘れずに。
6.userモデルの修正
Userモデルに以下の修正を実施します。class User < ActiveRecord::Base before_create :make_activation_code # Authenticates a user by their login name and unencrypted password. Returns the user or nil. def self.authenticate(login, password) # hide records with a nil activated_at u = find :first, :conditions => ['login = ? and activated_at IS NOT NULL', login] u && u.authenticated?(password) ? u : nil end # Activates the user in the database. def activate @activated = true update_attributes(:activated_at => Time.now, :activation_code => nil) end # Returns true if the user has just been activated. def recently_activated? @activated end protected # If you're going to use activation, uncomment this too def make_activation_code self.activation_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join ) end end
7.コントローラの修正
account_controllerの修正です。def activate @user = User.find_by_activation_code(params[:id]) if @user and @user.activate self.current_user = @user redirect_back_or_default(:controller => '/account', :action => 'index') flash[:notice] = "Your account has been activated." end end
これで完了。ためしてみてください。とても簡単だなあ。

コメント(
リンク元(225)