restful-authenticationを使ってみる


今はgitらしい。
technoweenie's restful-authentication at master - GitHub

インストール

ruby script/plugin install git://github.com/technoweenie/restful-authentication.git
ruby script/generate authenticated user sessions
rake db:migrate

設定

application_controller、sessions_controller/users_controller
コメントに記載されてるように、application_controllerへ移行。(sessions_controller/users_controllerはコメント)

  # Be sure to include AuthenticationSystem in Application Controller instead
  include AuthenticatedSystem


各controller
ログイン時に操作可能とするコンテンツにはcontrollerで下記を追加。

before_filter :login_required
とか
before_filter :login_required, :except => [:index, :show]

ソースをチラ見

パスワードのhash化ってどうやってんのかなぁと。
vendor/plugins/restful-authentication/lib/authentication/by_password.rb

    module ModelClassMethods
      # This provides a modest increased defense against a dictionary attack if
      # your db were ever compromised, but will invalidate existing passwords.
      # See the README and the file config/initializers/site_keys.rb
      #
      # It may not be obvious, but if you set REST_AUTH_SITE_KEY to nil and
      # REST_AUTH_DIGEST_STRETCHES to 1 you'll have backwards compatibility with
      # older versions of restful-authentication.
      def password_digest(password, salt)
        digest = REST_AUTH_SITE_KEY
        REST_AUTH_DIGEST_STRETCHES.times do
          digest = secure_digest(digest, salt, password, REST_AUTH_SITE_KEY)
        end
        digest
      end      
    end # class methods
    module ModelInstanceMethods
      
      # Encrypts the password with the user salt
      def encrypt(password)
        self.class.password_digest(password, salt)
      end


vendor/plugins/restful-authentication/lib/authentication.rb

  module ModelClassMethods
    def secure_digest(*args)
      Digest::SHA1.hexdigest(args.flatten.join('--'))
    end


REST_AUTH_SITE_KEY、REST_AUTH_DIGEST_STRETCHES(デフォルト10)は
config/initializers/site_keys.rb
で定義されている。


なるほど10回やってるのか。


ちなみにsaltは
vendor/plugins/restful-authentication/lib/authentication/by_password.rb

      def encrypt_password
        return if password.blank?
        self.salt = self.class.make_token if new_record?
        self.crypted_password = encrypt(password)
      end

vendor/plugins/restful-authentication/lib/authentication.rb

    def make_token
      secure_digest(Time.now, (1..10).map{ rand.to_s })
    end


digest(初回はREST_AUTH_SITE_KEY), salt, password, REST_AUTH_SITE_KEY
を"--"でくっつけてhashにしてを10回繰り返すと。