I'm using Authlogic to perform authentication for my Rails app. 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. 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:
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 < ActiveReco开发者_运维技巧rd::Base
authenticates_many :user_sessions, :find_options => { :limit => 1 }
has_many :users, :uniq => true
end
User and UserSession models:
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. 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.
精彩评论