简体   繁体   English

Twitter登录的弹出窗口

[英]Popup window for Twitter login

I'm trying to implement a pop-up window for my RoR project for the login functionality for Twitter. 我正在尝试为我的RoR项目实现一个弹出窗口,以实现Twitter的登录功能。 Currently, when you hit login, you are redirected to the authorization page, and then once you've logged in, you're redirected back. 当前,当您单击登录名时,您将被重定向到授权页面,然后登录后将被重定向回。 I want a pop-up window to come on top of the current browser window and then close after authentication. 我希望弹出窗口位于当前浏览器窗口的顶部,然后在身份验证后关闭。

This is my sessions controller: 这是我的会话控制器:

def create
auth_hash = request.env['omniauth.auth']
@user = User.find_by_user_id(auth_hash["uid"])
if @user
    @authorization = @user.authorization
    flash.now[:notice] = "Welcome back #{@user.name}! You have already signed up."
  session[:user_id] = auth_hash["uid"].to_i 
else
    @user = User.new :name => auth_hash["info"]["name"], :user_name => auth_hash["info"]["nickname"], :user_id => auth_hash["uid"], :profile_image_url => auth_hash["info"]["image"].sub("_normal", "")
  @user.build_authorization :secret => auth_hash['credentials']['secret'], :token => auth_hash['credentials']['token']
  @user.build_preference 
    @user.save!
    @user.errors.each do |error|
        puts error
end
    flash.now[:notice] = "Hi #{@user.name}! You've signed up."
  session[:user_id] = auth_hash["uid"].to_i
end
  redirect_to :root
end

def logout
session[:user_id] = nil
redirect_to :root
end

def failure
render :text => "Sorry, but you didn't allow access to our app!"
 end

 def destroy
@user = current_user
if @user
    @user.destroy
    end
redirect_to :root
   end

 end

I searched around and I see that a Javascript pop-up is the way to do it, so I got this from one of the other StackOverflow questions: 我四处搜索,然后发现可以使用Javascript弹出窗口,因此我从其他StackOverflow问题之一中获得了此信息:

Turn omniauth facebook login into a popup 将omniauth facebook登录名变成弹出窗口

Where the code for the pop up is as below: 弹出的代码如下:

    function popupCenter(url, width, height, name) {
    var left = (screen.width/2)-(width/2);
    vartop = (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);
    }

    $("a.popup").click(function(e) {
    popupCenter($(this).attr("href"), $(this).attr("data-width"), $(this).attr("data-height"), "authPopup");
    e.stopPropagation(); return false;
    });

And I've done the callback view, but what I don't know is where to put this line: 我已经完成了回调视图,但是我不知道在哪里放置这一行:

     =link_to "Log in with Facebook", omniauth_authorize_path(:user, :facebook), :class => "popup", :"data-width" => 600, :"data-height" => 400

The class => popup line is supposed to go where we set the Twitter key/secret key, but I don't think that is the right location ( Omniauth - Display facebook connect as popup ). class => popup行应该放在我们设置Twitter键/秘钥的位置,但是我认为这不是正确的位置( Omniauth-Display facebook connect as popup )。 It didn't work regardless. 无论如何,它没有用。 :/ :/

Any ideas? 有任何想法吗?

This is what you want ? 这就是你想要的吗?

Application Helper: 应用程序助手:

module ApplicationHelper
  def link_to_login_with(provider, url, html_options = {})
    add_default_class(html_options)
    convert_popup_attributes(html_options)

    link_to t('.login_with_link', provider: provider), url, html_options
  end

  private

  def add_default_class(html_options)
    default_class = "js-popup"

    if html_options.has_key?(:class)
      html_options[:class] << " " << default_class
    else
      html_options[:class] = default_class
    end
  end

  def convert_popup_attributes(html_options)
    width = html_options.delete(:width)
    height = html_options.delete(:height)

    if width && height
      html_options[:data] ||= {}
      html_options[:data].merge!({width: width, height: height})
    end
  end
end

Application.html.erb Application.html.erb

<!DOCTYPE html>
<html>
<head>
  <title>Omniauth Popup</title>
  <%= stylesheet_link_tag    'application' %>
  <%= javascript_include_tag 'application' %>
  <%= csrf_meta_tags %>
</head>
<body>
  <header class='main'>
    <nav class='user-nav'>
      <ul>
        <% if current_user %>
          <li>
            <%= link_to current_user do %>
              <%= image_tag current_user.image, class: 'user-pic' if current_user.image %>
              <%= content_tag :span, current_user.name %>
            <% end %>
          </li>
          <li><%= link_to t('.logout_link'), sign_out_path %></li>
        <% else %>
          <li><%= link_to_login_with 'Facebook', '/auth/facebook', { width: '460', height: '460' } %></li>
          <li><%= link_to_login_with 'GitHub', '/auth/github', { width: '1050', height: '700' } %></li>
          <li><%= link_to_login_with 'Google', '/auth/google', { width: '800', height: '470' } %></li>
          <li><%= link_to_login_with 'Twitter', "/auth/twitter?lang=#{I18n.locale}", { width: '660', height: '710' } %></li>
        <% end %>
      </ul>
    </nav>
  </header>

  <div id='js-messages' class='messages'>
    <% flash.each do |type, message| %>
      <span class='message <%= type %>'>
        <%= message %>
      </span>
    <% end %>
  </div>

  <div class='content'>
    <%= yield %>
  </div>
</body>
</html>

app/assets/javascripts/login.js 应用程序/资产/ JavaScript的/ login.js

$(document).ready(function() {
    $('.js-popup').click(function() {
        centerPopup($(this).attr('href'), $(this).attr('data-width'), $(this).attr('data-height'));
        return false;
    });
});

function centerPopup(linkUrl, width, height) {
    var sep = (linkUrl.indexOf('?') !== -1) ? '&' : '?',
        url = linkUrl + sep + 'popup=true',
        left = (screen.width - width) / 2 - 16,
        top = (screen.height - height) / 2 - 50,
        windowFeatures = 'menubar=no,toolbar=no,status=no,width=' + width +
            ',height=' + height + ',left=' + left + ',top=' + top;
    return window.open(url, 'authPopup', windowFeatures);
}

Controller 调节器

class SessionsController < ApplicationController
  def create
    # Have a look at the info returned by the provider by uncommenting the next line:
    # render text: "<pre>" + env["omniauth.auth"].to_yaml and return
    omniauth = env['omniauth.auth']
    user = User.find_or_create_with_omniauth(omniauth)
    session[:user_id] = user.id
    flash[:notice] = t('controllers.sessions.create', provider: pretty_name(omniauth.provider))
    render_or_redirect
  end

  def failure
    flash[:alert] = t('controllers.sessions.failure', provider: pretty_name(env['omniauth.error.strategy'].name))
    render_or_redirect
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_url, notice: t('controllers.sessions.destroy')
  end

  protected

  def render_or_redirect
    page = env['omniauth.origin']
    if env['omniauth.params']['popup']
      @page = page
      render 'callback', layout: false
    else
      redirect_to page
    end
  end

  def pretty_name(provider_name)
    provider_name.titleize
  end
end

app/views/sessions/callback.html.erb 应用程序/视图/会话/ callback.html.erb

<%= javascript_tag do %>
  window.opener.location = '<%= @page %>';
  window.close();
<% end %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM