[英]How can I make sure Users belong to a particular model using Authlogic?
I'm using Authlogic to perform authentication for my Rails app. 我正在使用Authlogic对我的Rails应用执行身份验证。 My users log in to a subdomain which is stored as part of a Client model.
我的用户登录到子域,该子域作为客户端模型的一部分存储。 Users belong_to clients and Clients authenticate_many UserSessions.
用户属于客户端,客户端属于authenticate_many UserSessions。 Logging in works fine;
登录工作正常; the problem I'm having is that users are able to log in to any subdomain whether or not they belong to that subdomain's client.
我遇到的问题是,无论用户是否属于该子域的客户端,他们都可以登录到任何子域。 Here's my code:
这是我的代码:
Application Controller: 应用控制器:
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 controller: 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
Client model: 客户模型:
class Client < ActiveRecord::Base
authenticates_many :user_sessions, :find_options => { :limit => 1 }
has_many :users, :uniq => true
end
User and UserSession models: 用户和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
I'm running Rails 3 on Mac os X with the latest version of Authlogic installed. 我在安装了最新版本Authlogic的Mac OS X上运行Rails 3。 Any help would be much appreciated!
任何帮助将非常感激!
You will need to add a custom validation. 您将需要添加自定义验证。
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
Remember to set the current_client attribute accessor in the UserSessions controller as this will not otherwise be available in the model. 记住要在UserSessions控制器中设置current_client属性访问器,否则在模型中将不可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.