设计 - 多个用户的单点登录表单 [英] Devise - single sign in form for multiple users

查看:17
本文介绍了设计 - 多个用户的单点登录表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have two Devise models, User and Business; I would like both to be able to sign in using a single sign in form. I am using backbone js and I have a customized view so the view is not a concern. An ajax request is used for the login, it works for users as expected but not for businesses.

I have searched google and come across a few solutions that mention using STI to solve this, but the project is very much done and I can't make such a change now. I was thinking along the lines of overriding the Devise sessions controller and:

  1. Check if the given email address is a User, then authenticate the user using Warden.
  2. If no user with that email is found then authenticate with the Business model using Warden.

I can't figure out how to change the code to achieve the above, I don't know how warden works and which params I need to tweak to achieve the above, what functions need to be called. Can anyone point me in the right direction or provide an example of how should I move forward with this.

Thanks.

解决方案

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.

这篇关于设计 - 多个用户的单点登录表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆