Omniauth Base Controller

Adds Omniauth gem, adds OmniauthController, adds Identity model, runs migrations
Icons/chart bar
Used 100 times
Created by
D Dale Zak

Usage
1. Update your routes.rb to reference controller:

  devise_for :users, controllers: { omniauth_callbacks: "omniauth" }

Run this command in your Rails app directory in the terminal:

rails app:template LOCATION="https://railsbytes.com/script/xkjsK3"
Template Source

Review the code before running this template on your machine.

run 'bundle add omniauth'

run 'bundle install'

rails_command 'generate model identity user:references provider:string:index uid:string:index token:string:index refresh_token:string:index'

rails_command 'generate migration AddIdentityToUsers identities_count:integer'

rails_command "db:migrate"

inject_into_file 'config/routes.rb', after: "devise_for :users\n" do
" # devise_for :users, controllers: { omniauth_callbacks: 'omniauth' }"
end

inject_into_file 'app/models/user.rb', after: ":database_authenticatable, " do
":omniauthable, "
end

inject_into_file 'app/models/identity.rb', after: "belongs_to :user" do
", counter_cache: true"
end

inject_into_file 'app/models/user.rb', after: "class User < ApplicationRecord\n" do <<-EOF
  
  has_many :identities, dependent: :destroy
  
  def self.from_omniauth(auth)
    if auth.present? && auth.provider.present? && auth.uid.present?
      identity = Identity.where(provider: auth.provider, uid: auth.uid).first_or_initialize
      if auth.credentials.present?
        identity.token = auth.credentials.token
        identity.refresh_token = auth.credentials.refresh_token
      end
      if identity.user.nil? && auth.info.email.present?
        user = User.where(email: auth.info.email).first_or_initialize
        user.name = auth.info.name
        user.password = Devise.friendly_token if user.new_record?
        user.save!
        identity.user = user
      end
      identity.save!
      identity.user
    end
  end
  
  EOF
end

file 'app/controllers/omniauth_controller.rb', <<~CODE
class OmniauthController < Devise::OmniauthCallbacksController

end
CODE

puts "IMPORTANT: Add devise_for :users, controllers: { omniauth_callbacks: 'omniauth' } to your routes.rb"
Comments
Aldo Rincón Mora
I try to use this template but it does not work from the url, User.rb and Identity.rb are using capital U and I. could you update it to a lower case filenames? 

Thanks for the scripts! 
Dale Zak
Good catch , I've updated the template 👍