Omniauth GEM
apps.twitter.com
in the twitter create an app
in the required url http://127.0.0.1:3000/ or lvh.me:3000 which points to your localhost
In your app_keys.rb add twitter_consumer_key tiwtter_consumer_secret
omniauth twitter
In your Gem.rb
add gem 'omniauth-twitter'
In your initializer create config/initializers/omniauth.rb
In the file above Rails.application.config.middleware.use OmniAuth::Builder do provider :twitter, "API_KEY", "API_SECRET" end
API_KEY and API_SECRET has to be replaced
Set up n url to redirect to twitter
https://api.twitter.com/oauth/authenticate
In your Routes.rb get "/auth/twitter", as: :sign_in_with_twitter
When the user hits this route Twitter will send the user back to our app with info we need so we would need to create a controller to handle the info
bin/rails g controller callbacks
In your Routes.rb
get "auth/twitter/callback" => "callback#twitter"In your callback.controller To see that everything is working we are going to pass text back to our app by defining def twitter to render text
def twitter
render json: request.env["omniauth.auth"]
endWe will add few fields in the user table to store the data we are receiving from twitter bin/rails g migration add_oauth_fields_to_users uid provider twitter_toke twitter_secret twitter_raw_data:text
in the migration file
add_index :users, [:uid, :provider] (composite index)
#this will help us find the user from twitter easily as :uid and :provider are the info required to find the userIn callback_controller If we find the user we sign them in right away. If we cant find the user we need to create the user and sign them in
def twitter
omniauth_data = request.env["omniauth.auth"]
user = User.where(provider: "twitter", uid: "omniauth_data["uid"]").first
is user
sign_in(user)
redirect_to root_path, notice: "Sign In!"
else
# Create the user account
User = User.crate_from_twitter(ominauth_data)
sign_in(user)
redirect_to root_path, alert: "Signed In!"
end
end
end
end
#this code can be refactored
User ||= User.crate_from_twitter(ominauth_data)
sign_in(user)
redirect_to root_path, alert: "Signed In!"
end
endIn your user.rb
serialize :twitter_data, Hash
#this enables us to store a Hash to the twitter_data field and retrieve it as a Hash.
#Rails will take care of encoding/decoding the data of the Hash to and from the database. It will be stored as Text
#in the database.
validates :emal presence: true,
uniqueness: true,
unless: :from_oauth?
def from_ouath?
uid.present? && provider.present?
end
def self.crate_from_twitter(twitter_data)
name = twitter_data["info"]["name"].split(" ")
user = User.create(provider: "twitter", uid: twitter_data["uid"],first_name: name[0],
last_name: name[1],twitter_token: twitter_data["credentials"]["token"],
twitter_secret: twitter_data["credentials"]["secret"],
password: SecureRandom.hex,
twitter_raw_data: twitter_data)
endIn your user.rb
def find_twitter_user(omniauth_data)
where(provider: "twitter", uid: omniauth_data["uid"]).first
end