I'm building a social login with Rails, and I've integrated it successfully with Google and Facebook. So, I do the same with Twitter. But I can't redirect to my app after login to Twitter. I received an error like:
ActiveRecord::RecordInvalid in Users::OmniauthCallbacksController#twitter Validation failed: Email can't be blank, Email can't be blank, Email is invalid
This is my code in the controller:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
generic_callback("facebook")
end
def google_oauth2
generic_callback("google_oauth2")
end
def twitter
generic_callback("twitter")
end
def generic_callback provider
@user = User.from_omniauth(request.env["omniauth.auth"])
if @user.persisted?
log_in @user
flash[:success] = t("users.new.welcome")
redirect_to @user
else
flash[:error] = t("sessions.new.error")
redirect_to root_url
end
end
def failure
redirect_to root_path
end
end
A part of code in model to get data
# Generate data from the social
def self.from_omniauth(auth)
user = User.where(email: auth.info.email).first
password = Devise.friendly_token[0,20]
user ||= User.create!(provider: auth.provider,
uid: auth.uid,
email: auth.info.email,
name: auth.info.name,
password: password,
password_confirmation: password)
end
And in file configure devise.rb
config.omniauth :google_oauth2, ENV["CLIENT_ID"], ENV["CLIENT_SECRET"], scope: "email", info_fields: "email,name"
config.omniauth :facebook, ENV["FACEBOOK_ID"], ENV["FACEBOOK_SECRET"], scope: "email", info_fields: "email,name"
config.omniauth :twitter, ENV["TWITTER_ID"], ENV["TWITTER_SECRET"], scope: "email", info_fields: "email,name"