5

这个问答线程之后,我得到了它,以便用户可以使用弹出窗口通过 Omniauth Facebook 策略登录。这是我的代码:

看法:

<%= link_to("Sign in with Facebook", "/auth/facebook", :id => "signin", 
:data => {:width => 600, :height => 400}) %>

应用程序.js:

function popupCenter(url, width, height, name) {
  var left = (screen.width/2)-(width/2);
  var top = (screen.height/2)-(height/2);
  return window.open(url, name, "menubar=no,toolbar=no,status=no,width="+width+",height="+height+",toolbar=no,left="+left+",top="+top);
}

$(document).ready(function() {
  $('a#signin').click(function(e) {
    popupCenter($(this).attr('href'), $(this).attr('data-width'), $(this).attr('data-height'), 'authPopup');
    e.stopPropagation();
    return false;
  });
});

session_controller.rb:

  def create
    user = AuthProviders::FacebookUser.find_or_create_user_from(auth_hash)
    session[:current_user_id] = user.id
    @return_to = origin || root_url
    render :callback, :layout => false
  end

  protected

  def auth_hash
    request.env['omniauth.auth']
  end

  def origin
    request.env['omniauth.origin']
  end

意见/会话/callback.html.erb:

<script type="text/javascript">
  if (window.opener) {
    window.opener.location = '<%= @return_to %>';
  }
  else {
    window.location = '<%= @return_to %>';
  }
  return window.close();
</script>

这很好用,但我需要代码能够处理两个额外的场景:

(1) 用户点击一个链接,控制器动作呈现一个普通的旧 html 响应,但只有当有 current_user(即登录)时才能查看该页面。单击链接后,用户将被迫使用弹出窗口通过 Facebook 登录。一旦通过身份验证,用户将被转发到原始请求页面。 例如,用户单击此链接,但由于他未登录,系统会提示他通过 Facebook 登录,然后返回到请求的页面:

<%= active_link_to("Your Stuff", user_stuff_path(current_user), :wrap_tag => :li) %>

当您不使用弹出窗口时,使用Hartly 的友好转发章节很容易做到这一点。

(2) 另一个场景与 (1) 类似,但控制器操作不是 html,而是呈现 javascript,然后打开一个(Twitter 引导)模式对话框。用户必须登录才能查看此模态框,因此应用程序需要向用户显示 Facebook 身份验证对话框,然后将他/她转发回模态框。这是我的应用程序中的示例链接:

<%= link_to(event.home_pick_path, :remote => true, :class => "#{event.home_button_class}", :rel => "tooltip", :data => {:placement => "top", "original-title" => "#{event.home_bet_tooltip}"}) do %>
  <div class="team-name"><%= event.home_team_nickname %></div>
<% end %>

请求 URL 如下所示:/picks/new?pick_line_id=1&pick_num=1

所以我想无论这两种情况的解决方案是什么,都会涉及到一些管道,所以我很感谢您抽出时间提前做出回应。

4

1 回答 1

0

我认为你过度工程。我会采用一种非常简单的方法,但这当然取决于您的业务逻辑。

如果没有当前用户,我将在同一个 url 中呈现带有“登录”按钮的“401”模板,这将触发 Fb 登录按钮。

在回调中(未测试)..

def create
  if session[:redirect_to].nil?
    session[:redirect_to] = origin
  end
  user = AuthProviders::FacebookUser.find_or_create_user_from(auth_hash)
  session[:current_user_id] = user.id
  unless session[:redirect_to].nil?
    redirect = session[:redirect_to] || root_url
    session[:redirect_to] = nil
    redirect_to redirect
  end 
end

当然,没有模板可以处理它,因为您不需要它。

于 2012-11-16T08:12:36.180 回答