私はRailsを初めて使用し、Lynda.comのチュートリアルに従ってRails 3でアプリを開発しています。このチュートリアルでは、KevinSkoglundがSHA1ダイジェストを使用してユーザーを認証する方法を示しました。私は自分のアプリでそれを使用しましたが、今度はいくつかの承認を入れる必要があります。周りを検索したところ、CanCanがRailsでの承認に適したものの1つであることがわかりました。ただし、CanCanは、ほとんどの場合、カスタム認証ではなく、DeviseまたはAuthlogic認証を使用して実装されているようです。
- 私のようにカスタム認証を使用すれば、CanCanを使用できるかどうかを知りたかったのです。そうですか、CanCanを機能させるにはどうすればよいですか?
- CanCanには「create_user」が必要なようですが、どこでどのように作成するかわかりません。
- 私が考えたもう1つの方法は、すべてのページにカスタムチェックを入れてユーザーの役割をチェックし、許可されていない場合はエラーページにリダイレクトすることですが、これはこの問題に取り組むための悪い方法のようです...これに対するあなたの見解お願いします。
- 追加情報が必要な場合はお知らせください。Ruby1.9.3とRails3.2.1を使用しています。
以下は、現在の認証を設定する方法です。どんな助けでも大歓迎です。
access_controller.rb
class AccessController < ApplicationController
before_filter :confirm_logged_in, :except => [:login, :attempt_login, :logout]
def attempt_login
authorized_user = User.authenticate(params[:username], params[:password])
if authorized_user
session[:user_id] = authorized_user.id
flash[:notice] = "You are logged in"
redirect_to(:controller => 'orders', :action => 'list')
else
flash[:notice] = "Invalid Username/password combination"
redirect_to(:action => 'login')
end
end
def logout
session[:user_id] = nil
flash[:notice] = "You have been logged out"
redirect_to(:action => 'login')
end
end
user.rb(ユーザーモデル)
require 'digest/sha1'
class User < ActiveRecord::Base
has_one :profile
has_many :user_roles
has_many :roles, :through => :user_roles
attr_accessor :password
attr_protected :hashed_password, :salt
def self.authenticate(username="", password="")
user = User.find_by_username(username)
if user && user.password_match(password)
return user
else
return false
end
end
def password_match(password="")
hashed_password == User.hash_with_salt(password, salt)
end
validates_length_of :password, :within => 4..25, :on => :create
before_save :create_hashed_password
after_save :clear_password
def self.make_salt(username="")
Digest::SHA1.hexdigest("Use #{username} with #{Time.now} to make salt")
end
def self.hash_with_salt(password="", salt="")
Digest::SHA1.hexdigest("Put #{salt} on the #{password}" )
end
private
def create_hashed_password
unless password.blank?
self.salt = User.make_salt(username) if salt.blank?
self.hashed_password = User.hash_with_salt(password, salt)
end
end
def clear_password
self.password = nil
end
end
ApplicationController.rb
class ApplicationController < ActionController::Base
protect_from_forgery
private
def confirm_logged_in
unless session[:user_id]
flash[:notice] = "Please Log In"
redirect_to(:controller => 'access', :action => 'login')
return false
else
return true
end
end
end