0

我在将我的 Twitter 用户登录到我的 Rails 项目时遇到问题。它确实连接成功,但它只是将我再次重定向到注册页面并且没有登录 Twitter 用户。

我的意图是从 Facebook 更改为 Twitter,因为我在将 Facebook 用户登录到localhost:3000.

这是gemfile:

gem 'devise'

gem 'omniauth'
gem 'omniauth-rails_csrf_protection'
gem 'omniauth-twitter'

然后,回调控制器:

class CallbacksController < Devise::OmniauthCallbacksController
    
    # def twitter
    #     @user = User.from_omniauth(request.env["omniauth.auth"])
    #     sign_in_and_redirect @user
    # end

    def twitter
        # You need to implement the method below in your model (e.g. app/models/user.rb)
        @user = User.from_omniauth(request.env["omniauth.auth"])
    
        if @user.persisted?
          sign_in_and_redirect @user, event: :authentication #this will throw if @user is not activated
          set_flash_message(:notice, :success, kind: "Twitter") if is_navigational_format?
        else
          session["devise.twitter_data"] = request.env["omniauth.auth"].except("extra")
          redirect_to new_user_registration_url
        end
      end
    
      def failure
        redirect_to root_path
      end    

end

这就是我在用户模型中的内容:

class User < ActiveRecord::Base
  validates :username, presence: true
  has_many :reviews
  has_many :categories, through: :reviews
  has_many :comments
  has_many :commented_posts, through: :comments 
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable,
         :omniauthable, :omniauth_providers => [:twitter]

  def self.from_omniauth(auth)
      where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
        user.provider = auth.provider
        user.uid = auth.uid
        user.email = auth.info.email
        user.password = Devise.friendly_token[0,20]
      end
  end

最后,使用 Twitter 登录的链接:

<%- if devise_mapping.omniauthable? %>
  <%- resource_class.omniauth_providers.each do |provider| %>
    <%= button_to "Sign in with Twitter", user_twitter_omniauth_authorize_path %>
  <% end %>

任何建议都将受到欢迎。谢谢。

4

0 回答 0