您好,我遇到了一个类似的问题,并找到了以下解决方案,希望能帮助下一个人。
我的情况是有两个设备模型,我用不同的方式使用omniauth,在第一个模型中,用户可以通过普通的devise注册或omniauth进行登录。在第二个模型中,艺术家只能通过常规注册表单进行注册,但我仍然需要omniauth来验证推特上的值,即已验证字段(推特资料上的小勾号,表示著名用户确实是该人)。
因此,当我发现无法拥有两个devise omniauthable模型时,我决定同时使用相同的omniauth。
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def all
if artist_signed_in? and session["devise.authorize"] == current_artist.email
session["devise.authorize"] = nil
if current_artist.artist_profile.update_from_omniauth(request.env["omniauth.auth"])
if current_artist.artist_profile.verified
flash[:notice] = "You were verified"
else
flash[:alert] = "Twitter go well but you aren't verified there"
end
redirect_to edit_artist_profile_path(current_artist.artist_profile)
else
flash[:error] = "We can't connect with #{request.env["omniauth.auth"].provider.titleize.split(" ").first}"
redirect_to edit_artist_profile_path(current_artist.artist_profile)
end
elsif !user_signed_in?
user = User.from_omniauth(request.env["omniauth.auth"])
if user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => user.provider.titleize.split(" ").first
user.user_profile.from_omniauth(request.env["omniauth.auth"])
sign_in_and_redirect user, :event => :authentication
else
session["count_errors"] = 0 if session["devise.user_attributes"] == nil
session["devise.user_attributes"] = user.attributes
redirect_to new_user_registration_url
end
else
flash[:notice] = "You are already log in #{current_user.email}"
redirect_to root_path
end
end
def after_omniauth_failure_path_for(scope)
if artist_signed_in? and session["devise.authorize"] == current_artist.email
session["devise.authorize"] = nil
edit_artist_profile_path(current_artist.artist_profile)
else
super
end
end
alias_method :twitter, :all
end
对于第一种情况,普通用户,我们有以下方案:
elsif !user_signed_in?
对于正常的流程,所有的指南都会进行,但是对于第二种情况(验证字段和艺术家档案),我会发送一个带有随机值的小会话。
session["devise.authorize"]
我从我的艺术家资料控制器中使用新路由调用链接。
<%= link_to "Verify with Twitter", artist_profiles_integrate_twitter_path %>
谁加载会话并重定向到用户omniauth路由?
class ArtistProfilesController < ApplicationController
...
def integrate_twitter
session["devise.authorize"] = current_artist.email
redirect_to user_omniauth_authorize_path(:twitter)
end
end
然后在每个类中定义了几种处理omniauth的方法,第一种是基于railscast教程“devise-omniauth-revised”创建用户,第二种只是更新艺术家资料模型上的字段。你应该覆盖after_omniauth_failure_path_for(scope)方法,它返回登录失败的路径。使用相同的技术,你可以更改错误后的路径(例如连接Twitter失败时将重定向到用户注册路径,并在一段时间内维持会话)。通过这种方式我们可以实现正常的行为并在所有情况下清除会话。希望能对您有所帮助。
祝好!