Home > RubyOnRails > restful-authentication プラグインを使ってログインアプリケーション作る(1)

restful-authentication プラグインを使ってログインアプリケーション作る(1)

数回に分けてログインアプリケーションを一通り作るためのまとめを書いてみます。

Project の作成

今回は何でもいいので、とりあえず todo を作成してみます。

rails todo

Plugin Install

必要なプラグインをあらかじめインストールしておきます。

restful-authentication

ruby script/plugin install git://github.com/technoweenie/restful-authentication.git

aasm

gem sources -a http://gems.github.com
gem install rubyist-aasm

forgot_password

ruby script/plugin install git://github.com/greenisus/forgot_password.git

Generate

sessions_controller と user モデルを作成します。

ruby script/generate authenticated user sessions --include-activation --aasm

passwords_controller と password モデルを作成します。

ruby script/generate forgot_password password user

その他修正箇所

このままでは動作しないので、aasm 関係を読み込むように修正します。

vendor/plugins/restful-authentication/init.rb

require File.dirname(__FILE__) + '/lib/authentication'
require File.dirname(__FILE__) + '/lib/authentication/by_password'
require File.dirname(__FILE__) + '/lib/authentication/by_cookie_token'
+require 'aasm'
+require File.dirname(__FILE__) + '/lib/authorization/aasm_roles'

アクティベーション用の route を追加。
config/routes.rb

(省略)
  map.activate '/activate/:activation_code', :controller => 'users', :action => 'activate'
(省略)

メールの設定をします。

config/environment.rb

(省略)
Rails::Initializer.run do |config|
(省略)
  config.active_record.observers = :user_observer

  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    :address => 'SMTP サーバ',
    :port => 587, # or 25
    :domain => 'ドメイン',
    :authentication => :login,
    :user_name => 'SMTP AUTH ユーザーID',
    :password => 'SMTP AUTH パスワード'
  }
end

$ADMIN_EMAIL = '管理者のメールアドレス'
$SERVICE_URL = 'http://localhost:3000'

メールアドレスと URL を設定します。

app/models/user_mailer.rb

class UserMailer < ActionMailer::Base
  def signup_notification(user)
    setup_email(user)
    @subject    += 'Please activate your new account'

    @body[:url]  = "#{$SERVICE_URL}/activate/#{user.activation_code}"

  end

  def activation(user)
    setup_email(user)
    @subject    += 'Your account has been activated!'
    @body[:url]  = "#{$SERVICE_URL}"
  end

  protected
    def setup_email(user)
      @recipients  = "#{user.email}"
      @from        = $ADMIN_EMAIL
      @subject     = "[YOURSITE] "
      @sent_on     = Time.now
      @body[:user] = user
    end
end

app/models/password_mailer.rb

class PasswordMailer < ActionMailer::Base

  def forgot_password(password)
    setup_email(password.user)
    @subject    += 'You have requested to change your password'
    @body[:url]  = "#{$SERVICE_URL}/change_password/#{password.reset_code}"
  end

  def reset_password(user)
    setup_email(user)
    @subject    += 'Your password has been reset.'
  end

  protected
    def setup_email(user)
      @recipients  = "#{user.email}"
      @from        = $ADMIN_EMAIL
      @subject     = "[YOURSITE] "
      @sent_on     = Time.now
      @body[:user] = user
    end
end

今回はすべてのコントローラのアクションを認証対象とするため、

application.rb で AuthenticatedSystem を読み込み、login_required を設定します。

app/controllers/application.rb

class ApplicationController < ActionController::Base

(省略)
  include AuthenticatedSystem

  before_filter :login_required

end

認証が必要ないアクションは except に指定します。

app/controllers/users_controller.rb

class UsersController < ApplicationController
  before_filter :login_required, :except => [ :new,
                                              :create,
                                              :activate,
                                              :suspend,
                                              :unsuspend,
                                              :destroy,
                                              :purge,
                                            ]

(省略)

end

sessions_controller は認証が必要ないため、skip_before_filter を設定します。

app/controllers/sessions_controller.rb

class SessionsController < ApplicationController
  skip_before_filter :login_required

(省略)

end

起動準備

config/database.yml を設定して下さい。

todo scaffold を作成。

ruby script/generate scaffold todo name:string

app/views/layouts/todo.html.erb を application.html.erb に変更します。

データベースとテーブルの作成。

rake db:create

rake db:migrate

ここまで設定することで、httpd を起動すると以下の動作確認することができます。

  • ユーザー登録
  • ログイン
  • ログアウト
  • パスワードリセット
  • アクティベーション(メール、パスワードリセット)

httpd は以下のコマンドで起動できます。

ruby script/server

動作確認のための URL は以下の通り。

# 会員登録
htt://localhost:3000/signup
# ログイン
htt://localhost:3000/login
# ログアウト
htt://localhost:3000/logout
# todo 一覧
htt://localhost:3000/todos

次回はこの todo にメールアドレス変更機能を追加し、日本語化してみます。

参考

aasmとは何か?acts_as_state_machineとの違いは?

Comments:1

bolo_bob 09-05-27 (水) 9:42

>app/controllers/users_controller.rb
>・
>・(省略)
>・
>:purge,
>]
“purge”の後ろに”,”があってsignupの編集画面にアクセスできませんでした。
おそらくコレが原因かと思います、ご確認いただけると幸いです。

Comment Form
Remember personal info

Trackbacks:5

Trackback URL for this entry
http://blog.imishin.com/2008/09/14/rails-with-restful-authentication-on/trackback/
Listed below are links to weblogs that reference
restful-authentication プラグインを使ってログインアプリケーション作る(1) from imishin.com
pingback from restful-authentication プラグインを使ってログインアプリケーション作る(2) - imishin.com 08-10-07 (火) 11:10

[...] 前回の続きです。 [...]

trackback from cuspos diary 09-03-12 (木) 0:13

restful authentication memo

restful authenticationで http://blog.imishin.com/2008/09/14/rails-with-restful-authentication-on/ が非常に参考になる。 でrake db:migrateするところでこける。 `load_missing_constant’: uninitialized constant Authorization::AasmRol…

pingback from ゾウ科マンモス属Zo-i種» Blog Archive » restful-authenticationを使ってみる:参考リンク集編 09-06-30 (火) 8:26

[...] インアプリケーション作る(1) – imishin.com http://blog.imishin.com/2008/09/14/rails-with-restful-authentication-on/ [...]

pingback from ゾウ科マンモス属Zo-i種» Blog Archive » restful-authenticationの練習 09-07-19 (日) 17:28

[...] インアプリケーション作る(1) – imishin.com http://blog.imishin.com/2008/09/14/rails-with-restful-authentication-on/ [...]

pingback from Ruby on Rails覚えるだ restful-authenticationのアクティベーション « Software Cosmology 09-11-16 (月) 16:24

[...] 参照リンク http://blog.imishin.com/2008/09/14/rails-with-restful-authentication-on/ http://avnetlabs.com/rails/restful-authentication-with-rails-2 [...]

Home > RubyOnRails > restful-authentication プラグインを使ってログインアプリケーション作る(1)

Calendar
« 2008 年 9月 »
M T W T F S S
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30          
ページ
ブログパーツ

Return to page top