如何使用Authlogic确保用户属于特定模型?

时间:2010-12-31 09:28:12

标签: ruby-on-rails validation authentication ruby-on-rails-3 authlogic

我正在使用Authlogic为我的Rails应用程序执行身份验证。我的用户登录到子域,该子域作为客户端模型的一部分存储。用户属于客户端和客户端authenticate_many UserSessions。登录工作正常;我遇到的问题是用户能够登录到任何子域,无论他们是否属于该子域的客户端。这是我的代码:

应用程序控制器:

class ApplicationController < ActionController::Base
  helper_method :current_user_session, :current_user, :current_client

  private

  def current_user_session
    return @current_user_session if defined?(@current_user_session)
    @current_user_session = UserSession.find
  end

  def current_user
    return @current_user if defined?(@current_user)
    @current_user = current_user_session && current_user_session.user
  end

  def current_client
    subdomain = request.subdomain

    if subdomain.present? && subdomain != 'www'
      @current_client = Client.find_by_subdomain(subdomain)
    else
      @current_client = nil
    end
  end
end

UserSessions控制器:

class UserSessionsController < ApplicationController
  def new
    @user_session = current_client.user_sessions.new
  end

  def create
    params[:user_session][:client] = current_client
    @user_session = current_client.user_sessions.new(params[:user_session])
    if @user_session.save
      redirect_to dashboard_path
    else
      render :action => 'new'
    end
  end
end

客户端模型:

class Client < ActiveRecord::Base
  authenticates_many :user_sessions, :find_options => { :limit => 1 } 

  has_many :users, :uniq => true
end

User和UserSession模型:

class User < ActiveRecord::Base
  belongs_to :client

  acts_as_authentic do |c|
    c.validations_scope = :client_id
  end
end

class UserSession < Authlogic::Session::Base
end

我在Mac OS X上运行Rails 3并安装了最新版本的Authlogic。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

您需要添加自定义验证。

 class UserSession

   attr_accessor :current_client
   before_validation :check_if_user_of_client

   private
     def check_if_user_of_client
       errors.add(:base, "Not your client/subdomain etc.") unless client.eql?(current_client) # client.eql? == self.client.eql? the associated client of current_user
     end
 end

请记住在UserSessions控制器中设置current_client属性访问器,否则模型中将无法使用此访问器。