Devise - single sign in form for multiple users

倾然丶 夕夏残阳落幕 提交于 2019-12-01 05:37:55
Bryce

Don't worry, you're not stuck.

I think your best option is to override Devise's session controller and alter the 'new' and 'create' methods for a session.

So in your own "sessions_controller.rb", you will have something like this:

class SessionsController < Devise::SessionsController
  # GET /resource/sign_in
  def new
    resource = build_resource(nil, :unsafe => true)
    clean_up_passwords(resource)
    respond_with(resource, serialize_options(resource))
  end

  # POST /resource/sign_in
  def create
    resource = warden.authenticate!(auth_options)
    set_flash_message(:notice, :signed_in) if is_navigational_format?
    sign_in(resource_name, resource)
    respond_with resource, :location => after_sign_in_path_for(resource)
  end
end

And in your routes, you would use something like (depending on what you named your user models):

devise_for :users, :controllers => {
    :sessions => 'sessions'
}


devise_for :businesses, :controllers => {
    :sessions => 'sessions'
}

The above session controller is not customized at all. I don't know your code, so I can't really help there. But the basic steps are:

  1. Inspect the auth_options and resource_name variables to understand how they are storing data.
  2. Add your conditional logic to alter those variables if the resource isn't found in the Users table.

Devise is great, and Roles are great, but sometimes having one User model, or even using STI, don't make sense. I'm writing a longer post on this exact issue soon, since I dealt with it in a recent project.

I recently came up with this total hack to make this work. My advice is to strongly consider a single user model with a role, but this works -- at least with the current version of Devise.

https://gist.github.com/jeremyw/5319386

If you monkeypatch or otherwise override default behavior like this, make sure you have a good test suite in case you ever want to try to upgrade Devise.

ob1

Consider using only the User model and use CanCan and Rolify to address the unique needs of each type of user. It might mean starting over with some of your code, but it may be easier to maintain in the long run.

Don't just take my word for it. Here's a related question with good responses.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!