rails twitter gem for multiple users - ruby-on-rails

using the twitter gem I want to get all the followers of the authenticated user. I only get the followers of the registered twitter id for the application though.
I have a twitter.rb in the initializers which uses the consumer key/secret of the registered app on twitter
Twitter.configure do |config|
config.consumer_key = '****'
config.consumer_secret = '****'
end
When you login you do so via Devise. Then in the user profile the user can authenticate with Twitter and at that point I store the token and secret.
def create
auth = request.env["omniauth.auth"]
currentAuthentication = Authentication.find_by_provider_and_uid(auth['provider'], auth['uid'])
if currentAuthentication
flash[:notice] = "Logged in successfully."
else
current_user.authentications.create(:provider => auth['provider'], :uid => auth['uid'], :token => auth['credentials']['token'], :secret => auth['credentials']['secret'])
flash[:notice] = "Authentication successful."
end
redirect_to authentications_url
end
Then at a later stage I authenticate that user with the information I stored and want to get his followers.
def getwords
# authenticate at twitter
authenticationDetails = current_user.authentications.first()
wordClient = Twitter::Client.new(
:oauth_token => authenticationDetails.token,
:oauth_token_secret => authenticationDetails.secret
)
# get the users followers
#wordClient.update("I'm tweeting using the Twitter Gem.")
cursor = "-1"
followerIds = []
while cursor != 0 do
followers = wordClient.follower_ids
cursor = followers.next_cursor
followerIds+= followers.ids
sleep(2)
end
return followerIds
end
When I do wordClient.update I sent a tweet out from the registered application, and I also get the followers of the registered application.
I was expecting to sent out a tweet and get the followers of the authenticated user? Where am I going wrong? All examples I've been able to find are on the bases of twittering with one single user.

Related

multi step registration with omniauth

I've gotten the omniauth to work with google by following this tutorial. The problem I'm currently having is that instead of creating the user when they sign up, I want to route them to a finish registration page where they have to enter additional data. This is similar to how pastebin handles their oauth registration.
UserModel (taken from tutorial):
def self.find_for_google_oauth2(access_token, signed_in_resource=nil)
data = access_token.info
user = User.where(:provider => access_token.provider, :uid => access_token.uid ).first
if user
return user
else
registered_user = User.where(:email => access_token.info.email).first
if registered_user
return registered_user
else
user = User.create(name: data["name"],
provider:access_token.provider,
email: data["email"],
uid: access_token.uid ,
password: Devise.friendly_token[0,20],
)
end
end
end
omniauthCallBacksController
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2
#user = User.find_for_google_oauth2(request.env["omniauth.auth"], current_user)
if #user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google"
sign_in_and_redirect #user, :event => :authentication
else
session["devise.google_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
It looks like the problem is that your find_for_google_oauth2 is creating the user. This means that the else in your google_oauth2 callback isn't getting hit, so it'll never go to your new_user_registration_url. One solution is to separate your find and create steps rather than combining them in find_for_google_oauth2. Then, when the find doesn't find an existing user, you hit your else in your google_oauth2 callback and the omniauth data is put in the session and you get sent to new_user_registration_url. Then once they've entered the extra info and submit the form, you can use that, combined with the omniauth data you saved in the session, to create the user.
Two things about putting the omniauth data in the session:
You probably want to pick what you want to keep from the omniauth hash (especially if you're using CookieStore for the session storage) as it's quite large.
If you're using the CookieStore and Rails < 4 then the omniauth data being stored in the session (i.e. in the cookie on the user's computer) is unencrypted.

Rails + OmniAuth Facebook: how to obtain Access Token?

I am trying to fetch the list of friends from Facebook. Sign in through Facebook is not a problem, but the problem is to fetch person's friends - because of access token.
puts request.env["omniauth.auth"].inspect
puts '==='
#user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user)
#fb_user = FbGraph::User.fetch(#user.uid).friends
puts #fb_user.inspect
The problem is on the #4 line - in this case I am getting error
OAuthException :: An access token is required to request this resource.
When I put there something like this:
#fb_user = FbGraph::User.fetch(request.env["omniauth.auth"].credentials.token).friends
I'll get
OAuthException :: (#803) Some of the aliases you requested do not exist: PRINTED OUT TOKEN
What's the proper way to obtain the access token?
EDIT: Current flow
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
#user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user)
#fb_user = FbGraph::User.fetch(request.env["omniauth.auth"].credentials.token).friends
if !#user
flash[:error] = 'This email address is already used in the system.'
redirect_to :back
elsif #user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Facebook"
sign_in_and_redirect #user, :event => :authentication
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
In User model:
def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
data = access_token.extra.raw_info
if user = User.where(:provider => 'facebook', :uid => data.id).first
user
elsif user = User.where('email = ? AND provider IS NULL', data.email).first
return false
else
...saving data...
end
return user if user
end
You can get an access token for test purposes via the Facebook Graph API Explorer. Make sure you select the proper fields that you want access to, and click "get access token". A more permanent solution is to register your app with Facebook so that you will be able to continually make requests without the token dying.
You should look into the Facebook OAuth dialogue.
I'm assuming you're trying to use the OAuth2 strategy instead of the Javascript SDK. Make sure you have set up a callback url like so:
client.redirect_uri = "http://your.client.com/facebook/callback"
In the controller that handles your callback, you should do something like this:
client.authorization_code = params[:code]
access_token = client.access_token! :client_auth_body
FbGraph::User.me(access_token).fetch
Make sure you've let fb_graph know what your app's id and secret are. You should look into this stackoverflow to keep your apps info safe.
I'll also plug the koala gem

LinkedIn API returning extra/incorrect login prompt

I have a Rails application running the omniauth-linkedin gem and linkedin gem (essentialy an API wrapper). When a user logs in, they receive a primary login prompt that displays to them the correct scopes (FULL PROFILE and EMAIL ADDRESS), as below:
However, after they log in, they get another login prompt that should not come up, and that ignores the initial scope request. It tells them that LinkedIN is only requesting their PROFILE OVERVIEW, which is incorrect:
The problem must lie in my auth_controller, and I think it has do to with the url that is created in one of the authentication stages (definitely right after the user enters their LinkedIn authentication credentials). Here is my auth_controller:
require 'linkedin'
class AuthController < ApplicationController
def auth
client = LinkedIn::Client.new(ENV['LINKEDIN_KEY'], ENV['LINKEDIN_SECRET'])
request_token = client.request_token(:oauth_callback => "http://#{request.host_with_port}/callback")
session[:rtoken] = request_token.token
session[:rsecret] = request_token.secret
redirect_to client.request_token.authorize_url
end
def callback
client = LinkedIn::Client.new(ENV['LINKEDIN_KEY'], ENV['LINKEDIN_SECRET'])
if session[:atoken].nil?
pin = params[:oauth_verifier]
atoken, asecret = client.authorize_from_request(session[:rtoken], session[:rsecret], pin)
session[:atoken] = atoken
session[:asecret] = asecret
#user = current_user
#user.uid = client.profile(:fields => ["id"]).id
flash.now[:success] = 'Signed in with LinkedIn.'
else
client.authorize_from_access(session[:atoken], session[:asecret])
#user.uid = client.profile(:fields => ["id"]).id
flash.now[:success] = 'Signed in with LinkedIn.'
end
#user = current_user
#user.save
redirect_to current_user
end
end
Just in case, here is my omniauth.rb file that states the scopes I am requesting for my application:
Rails.application.config.middleware.use OmniAuth::Builder do
provider :linkedin, ENV['LINKEDIN_KEY'], ENV['LINKEDIN_SECRET'],
:scope => 'r_fullprofile r_emailaddress', :fields => ['id', 'email-address', 'first-name', 'last-name', 'headline', 'industry', 'picture-url', 'public-profile-url', 'location', 'positions', 'educations']
end
Can't figure out how to get rid of that second unnecessary and misleading prompt from LinkedIn and would appreciate any guidance!
Thank you.

Setting Facebook redirect_uri

I'm making a FB Canvas app.
The problem: After users authenticate, they are returned to the non-Canvas version of the app. Here's my code:
provider :facebook, CONFIG['app_id'], CONFIG['secret_key'], :scope => "publish_stream, rsvp_event"
match "/auth/facebook/callback" => "sessions#oauth_create"
match "/auth/facebook", :as => "facebook"
match "/auth/failure" => "sessions#oauth_failure"
When the user is returned from Facebook, they are sent to oauth_create (below)- however, they are sent to it via the normal (non-Canvas) app url (localhost:3000), rather than the canvas app (apps.facebook.com/my-app-namespace) so the redirect_to root_path below just sends them to the regular app.
def oauth_create
auth = request.env["omniauth.auth"]
t = auth["credentials"]["token"]
session[:facebook_token] = t
redirect_to root_path
end
I'm using omniauth-facebook gem.
How can I tell FB to send users to the canvas app after authentication?

Omniauth and Foursquare not working

So I'm using Omniauth to authenticate with the likes of Twitter and Foursquare. Twitter works fine, but Foursquare doesn't appear to return a secret.
Anyone know what's going wrong?
Here's the create action in the controller, Foursquare is passing the user back to this, but as I said, it's not getting the secret, just the token
def create
omniauth = request.env["omniauth.auth"]
unless current_user.authentications.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
current_user.apply_omniauth(omniauth)
current_user.save
end
flash[:notice] = "Authentication Successfull"
redirect_to authentications_url
end
Here is the apply omniauth method:
def apply_omniauth(omniauth)
authentications.build(
:provider => omniauth['provider'],
:uid => omniauth['uid'],
:token => omniauth['credentials']['token'],
:secret => omniauth['credentials']['secret']
)
end
Foursquare should not pass back a secret, just the token. The foursquare api key and and secret are provided to you by foursquare when you register your app on their developers site. You must use these values in your omniauth.rb
Twitter uses Oauth 1.0 and foursquare uses 2.0
That could be your issue there

Resources