Reputation: 2017
Im using devise
in my rails application and everything is working fine, what Im trying to do now is to allow users to login to my app using their github account and create a profile.
User.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable
has_one :profile
after_create :build_profile
def build_profile
self.create_profile
end
def self.create_with_omniauth(auth)
user = 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
end
routes.rb
devise_for :users, :controllers => { :omniauth_callbacks => "callbacks" }
callbacks_controller.rb
class CallbacksController < Devise::OmniauthCallbacksController
def github
@user = User.from_omniauth(request.env["omniauth.auth"])
sign_in_and_redirect @user
end
end
I also ran the correct migration to add provider and uid column to the users table
rails g migration AddColumnsToUsers provider uid
def change
add_column :users, :provider, :string
add_column :users, :uid, :string
end
config/initializers/devise.rb
config.omniauth :github, 'CLIENT_ID', 'APP_SECRET', :scope => 'user:email'
When i create a user using devise
it all works fine and users are created, but when i click sign in with github on my registration page it merges the devise account and github account together leaving me with one account, its not creating an account with user github credentials. Even if i try and login using 2 different github accounts, it still for some reason only uses the first github account.
problem is github user can login but they are not being created as users, using their github credentials, i need users to login and create a profile with me.
Upvotes: 0
Views: 356
Reputation: 2017
In the Devise's wiki it is said:
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
But I removed that where
method. What happens now is you literally take THE FIRST record from the database and update it.
If no records are present in the database, a record will be created, but on subsequest registrations you will still fetch the first record and modify it. So i changed:
my User.rb to:
def self.from_omniauth(auth)
user = where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
end
end
and callbacks controller to:
@user = User.from_omniauth(request.env["omniauth.auth"])
Upvotes: 0
Reputation: 2244
Did you give the credentials in config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET'], scope:"user:email,user:follow"
end
you can go through by Link
Upvotes: 1