Multi tenant rails app with devise -
i'm trying build multi tenanted app in which different banks separated subdomain. part working fine. there 1 more level of multitenancy bank products.
- each bank has multiple products
- a devise user can belong on product
- this means have register twice 2 products of same bank though under same subdomain(client requirement can't change)
- because of can have same email address 2 products. uniqueness scoped product_id
- so have select product while signing in , signing up
this how i'm trying implement above solution
around_filter :scope_current_bank, :scope_current_product before_filter :authenticate_user! helper_method :current_bank, :current_product def current_bank @current_bank = bank.find_by_subdomain!(request.subdomains.first) end def current_product if user_signed_in? @current_product = current_bank.products.find_by_id(params[:product_id]) else @current_product = current_user.product end end def scope_current_bank bank.current_id = current_bank.id yield ensure bank.current_id = nil end def scope_current_product product.current_id = (current_product.id rescue nil) yield ensure product.current_id = nil end
now problem while user sigining in, scope_current_product method calls user_signed_in?, fails because product_id nil. enters else block after expect call authenticate_user! before_filter not happen authentication done. message saying authentication failed.
is way call authenticate_user again?
although not direct answer, give ideas:
authorization
perhaps should @ - is there difference between authentication , authorization? - there's good railscast this
i think issue comes down idea need authenticate user once (login / logout), should authorize user work different resources
code
a devise user can belong on product
- recommend this:
#app/models/product_user.rb class productuser < activerecord::base belongs_to :product belongs_to :user end #app/models/product.rb class product < activerecord::base has_many :product_users has_many :users, through: :product_users end #app/models/user.rb class user < activerecord::base has_many :product_users has_many :products, through: :product_users end
this typical has_many :through association:
@user.products @product.users
cancan
it means can use cancan this:
class ability include cancan::ability def initialize(user) user ||= user.new # guest user (not logged in) if user can :manage, product, users.exists?(user.id) else can :read, :all end end end
this allows control products user can edit / access. code needs tweaked, hope shows value of authorization on trying multiple authentications
Comments
Post a Comment