【问题标题】:How can I make sure Users belong to a particular model using Authlogic?如何使用 Authlogic 确保用户属于特定模型?
【发布时间】:2010-12-31 09:28:12
【问题描述】:

我正在使用 Authlogic 为我的 Rails 应用程序执行身份验证。我的用户登录到作为客户端模型的一部分存储的子域。用户属于_to clients 和 Clients 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

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

【问题讨论】:

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


    【解决方案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 属性访问器,否则模型中将无法使用它。

    【讨论】:

    • 谢谢!我知道它必须是这样的。
    猜你喜欢
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 2013-06-24
    相关资源
    最近更新 更多