Search code examples
ruby-on-railsomniauth-twitter

No route matches [GET] "/auth/twitter" OmniA


I am not using devise or some other like-gem. I am very new to RoR.

Here is my routes.rb

# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html

Rails.application.routes.draw do
  get "about", to: "about#index"

  get "password", to: "passwords#edit", as: :edit_password
  patch "password", to: "passwords#update"

  get "password/reset", to: "password_resets#new"
  post "password/reset", to: "password_resets#create"
  get "password/reset/edit", to: "password_resets#edit"
  patch "password/reset/edit", to: "password_resets#update"
  
  get '/auth/:provider/callback', to: 'sessions#create'

  get "sign_up", to: "registrations#new"
  post "sign_up", to: "registrations#create"

  get "sign_in", to: "sessions#new"
  post "sign_in", to: "sessions#create"

  delete "logout", to: "sessions#destroy"

  root to: "main#index"
end

Here is user.rb

# email:string
# password_digest:string
#
# password:string virtual
# password_confirmation:string virtual

class User < ApplicationRecord
  has_secure_password

  validates :email, presence: true, format: { with: /\A[^@\s]+@[^@\s]+\z/, message: "must be a valid email address" }
  
end

here is my omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do
    provider :twitter,Rails.application.credentials.dig(:twitter,:api_key), Rails.application.credentials.dig(:twitter,:api_key)
end

I have made all the settings in my Twitter app. Please help.


Solution

  • I'm the author of the Ruby on Rails for Beginners course. 👋 I've updated the videos to reflect the changes.

    Omniauth 2.0 was released which requires you to use POST requests now for security.

    Now we'll add two gems:

    bundle add omniauth-twitter omniauth-rails_csrf_protection
    

    And make sure you've got api_secret as the second argument in your omniauth.rb initializer:

    Rails.application.config.middleware.use OmniAuth::Builder do
      provider :twitter,Rails.application.credentials.dig(:twitter,:api_key), Rails.application.credentials.dig(:twitter,:api_secret)
    end
    

    Then you can redirect to twitter by adding method: :post to your link_to or button_to

    link_to "Connect Twitter", "/auth/twitter", method: :post, class: "btn btn-primary"
    button_to "Connect Twitter", "/auth/twitter", method: :post, class: "btn btn-primary"
    

    This works with both Project and Standalone Twitter apps so you can use either one. 👍