How do I write to someone's Facebook or Twitter wall using Omniauth? - facebook

I know Omniauth is just for authentication and it doesn't really have FB or Twitter tools included.
However, let's say my Rails 3 app uses Omniauth and I now have some users registered in my system.
How can I then post to their wall? Or do I need some other type of authorization system?
Thanks for any pointers.

I found this link which allowed me to post to both Facebook and Twitter. Very good tutorial:
http://blog.assimov.net/post/2358661274/twitter-integration-with-omniauth-and-devise-on-rails-3

I used this guide while setting up my application to connect to twitter:
http://philsturgeon.co.uk/news/2010/11/using-omniauth-to-make-twitteroauth-api-requests
Helped me a ton, hope it does for you the same.
Original post
Posted: Nov 16, 2010
Using the brilliant user system gem Devise and a gem called OmniAuth you can make a Rails application that logs in or registers users via Twitter, Facebook, Gowalla, etc with amazing ease. But once the user is logged in, how do you go about actually interacting with the API on behalf of the account that has just been authorized?
This article starts where RailsCasts leaves off, so if you are not already up and running with Devise and OmniAuth then you might want to watch:
RailsCast #209: Introducing Devise
RailsCast #235: OmniAuth Part 1
RailsCast #236: OmniAuth Part 2
So, assuming we are all about at the point that the third video ends on, we are all ready to go. I'll be using the example of Twitter but really any of the providers using oAuth will use the same approach. Like in the "ye-olden days" when we used the Twitter username and password to authenticate an API request, we now use a Access Token and Token Secret. You can think of these as being basically the same thing as for the purpose of authenticating API requests, to us, they are.
To get the token and secret you need to add some fields to your authentications table:
rails g migration AddTokenToAuthentications token:string secret:string
rake db:migrate
Now the database is ready to save the credentials we can change the authentication code to populate the fields. Assuming you placed the method in user.rb like RailsCast #236 suggested then open user.rb and modify the following line:
authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'])
and replace it with:
authentications.build(
:provider => omniauth['provider'],
:uid => omniauth['uid'],
:token => omniauth['credentials']['token'],
:secret => omniauth['credentials']['secret']
)
Now whenever anybody authenticates their account we can save their credentials which are passed back from the internal hidden magic that is OmniAuth.
The next step is to actually make some requests using these saved credentials, which is described almost perfectly in the Twitter Developer Documentation. You'll want to install the oauth gem (put it in your Gemfile and run bundle install) then you can use the following code to test-dump a list of tweets from the user:
class TwitterController < ApplicationController
def recent_tweets
# Exchange your oauth_token and oauth_token_secret for an AccessToken instance.
def prepare_access_token(oauth_token, oauth_token_secret)
consumer = OAuth::Consumer.new("APIKey", "APISecret"
{ :site => "http://api.twitter.com"
})
# now create the access token object from passed values
token_hash = { :oauth_token => oauth_token,
:oauth_token_secret => oauth_token_secret
}
access_token = OAuth::AccessToken.from_hash(consumer, token_hash )
return access_token
end
auth = current_user.authentications.find(:first, :conditions => { :provider => 'twitter' })
# Exchange our oauth_token and oauth_token secret for the AccessToken instance.
access_token = prepare_access_token(auth['token'], auth['secret'])
# use the access token as an agent to get the home timeline
response = access_token.request(:get, "http://api.twitter.com/1/statuses/user_timeline.json")
render :json => response.body
end
end
By pulling the content from current_user.authentications (im finding the first as in my application they should only have one) I can grab the credentials and have full permissions to get their recent tweets, post new ones, see friends tweets, etc.
Now I can tweak this, get stuff saved, faff with the JSON and take what I need. Working with Facebook or any other oAuth provider will work in an almost identical way, or you can install specific gems to interact with their API's if the direct approach is not as smooth as you'd like.
end of original post

Related

Generate access token Instagram API, without having to log in?

So I am building a restaurant app and one of the features I want is to allow a user of the app to see photos from a particular restaurant's Instagram account.
And I want a user to be able to see this without having to login to their Instagram account, so they shouldn't even need an Instagram account for this to work.
So I have read this answer How can I get a user's media from Instagram without authenticating as a user?
And I tried what it said and used the client_id(which I recieved when I registered my app using my personal Instagram account), but I still get an error back saying :
{
meta: {
error_type: "OAuthAccessTokenException",
code: 400,
error_message: "The access_token provided is invalid."
}
}
The endpoint I am trying to hit is :
https://api.instagram.com/v1/users/search?q=[USERNAME]&client_id=[CLIENT ID]
So do I absolutely need an access token for this to work(and thus have to enforce a user to log in) ?
If I do, then is there way to generate an access token somehow without forcing the user log in?
I believe there is a way around this, as the popular dating app Tinder has this desired functionality I am looking for, as it allows you to see photos from people's Instagram account without having to log in! (I have just verified this 5 minutes ago!)
Any help on this would be much appreciated.
Thanks.
Edit April 2018: After facebook privacy case this endpoint is immediately put out of service. It seems we need to parse the JSON embedded in <script> tag directly within the profile page:
<script type="text/javascript">window._sharedData = {"activity_counts":...
Any better ideas are welcome.
You can use the most recent link
GET https://www.instagram.com/{username}/?__a=1
to get latest 20 posts in JSON format. Hope you put this to good use.
edit: other ways aren't valid anymore:
https://www.instagram.com/{username}/media/
Instagram used to allow most API requests with just client_id and without access_token, the apps registered back in the day still work with way, thats how some apps are able to show instagram photos without user login.
Instagram has changes the API specification, so new apps will have to get access_token, older apps will have to change before June 2016.
One way you can work around this is by using access_token generated by your account to access photos. Login locally and get access_token, use this for all API calls, it should not change, unless u change password,if it expires, regenerate and update in your server.
Since the endpoints don't exist anymore I switched to a PHP library -
https://github.com/pgrimaud/instagram-user-feed
Installed this lib with composer:
composer require pgrimaud/instagram-user-feed "^4.0"
To get a feed object -
$cache = new Instagram\Storage\CacheManager();
$api = new Instagram\Api($cache);
$api->setUserName('myvetbox');
$feed = $api->getFeed();
Example of how to use that object -
foreach ($feed->medias as $key => $value) {
echo '<li><img src="'.$value->thumbnailSrc.'"></li>';
}

REST web service Basic authentication + Client Facebook app authentication = double authentication?

I have built a web service based on a REST design. Of course some of the operations available on resources require authentication (delete a user for example). I use Basic authentication and so far everything is fine.
I have built a client to consume the web service : a set of Ajax function. Again, everything is fine (also for the Basic authentication).
I want now to create a whole web app that will use the set of Ajax function above to interact with the web service. But, to enhance the user experience, some of the web app functions will require Facebook authentication.
So here is my problem. The web app will require username and password to call the web service via the Basic authentication. But it will also require Facebook credentials to use Facebook API and the user will have to log in twice. Moreover, every time I will have to check if the Facebook user (currently logged in Facebook) corresponds to the user of the web service and it is quite troublesome.
Does anyone have an idea to simplify the process ?
It's a bit related to that post authentication-scheme-for-multi-tiered-web-application-utilizing-rest-api but I did not find any answer I could understand.
In such scenarios, I use only Facebook authentication. If user is logged into Facebook by JS SDK, you can simply get accessToken by FB.getAuthResponse().accessToken. Then, you can pass it into webservice and use it to authenticate on server side.
First, client side authentication with JS SDK:
/* assumed, that you alredy called FB.login() and stuff */
var accessToken = FB.getAuthResponse().accessToken;
$.ajax({
'url' : 'rest.php',
'type' : 'get',
'dataType' : 'json',
'data' : { accessToken : accessToken },
'success' : function(response) {
/* some fancy code, blah blah blah */
}
});
I use PHP SDK, so I'll show example in PHP.
<?php
require 'facebook.php';
$accessToken = $_GET['accessToken'];
$facebook = new Facebook(array(
'appId' => 'xxxxx',
'secret' => 'xxxxx'
));
$facebook->setAccessToken($accessToken);
if ($facebook->getUser()) {
// yaay, user is authenticated
echo json_encode($mySuperDuperSecretContentForLoggedUserOnly);
} else {
// authentication failed
echo json_encode(null);
}
If your main design uses basic authentication, but you want on some cases to be able to connect with facebook, then I suggest that you use an adapter/bridge on your server that will be able to take the facebook auth data and then handle the basic authentication itself.
That way the facebook users won't have to go through 2 authentication processes, and you don't break anything in your original flow.
It should not be hard to implement, when a user signs up just associate his fb account with a user in your system, then when he logs in with facebook take his id and log him into the system using the basic authentication.
One thing though, if you want to implement the facebook authentication using client side then you should send the auth data in https.

Devise and OmniAuth remembering OAuth

So, I just got setup using Rails 3, Devise and OmniAuth via https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview.
I'm successfully authenticating users via Facebook, but they are not "rememberable" despite being marked with:
devise [...]: rememberable, :omniauthable
I tried calling:
#the_user.remember_me!
...to no avail. No cookie is being stored/set which means the user does not persist across sessions.
Has anybody managed to get a user sourced from FB remembered via cookies? In my mind, this should be happening automatically.
Thanks for any ideas or feedback you guys might have.
I'd like to elaborate on the (correct) answer #jeroen-van-dijk gave above which worked for me.
In config/routes.rb, add a new route in the devise_for block:
devise_for :users, :controllers => {
:omniauth_callbacks => "user_omniauth_callbacks" } do
...
get '/users/connect/:network', :to => redirect("/users/auth/%{network}"),
:as => 'user_oauth_connect'
end
Then change your "login using facebook" link to use the new route:
<!-- before it linked to user_omniauth_authorize_path -->
<%= link_to "Sign in using Facebook", user_oauth_connect_path(:facebook) %>
In app/controllers/user_omnniauth_callbacks_controller.rb
class UserOmniauthCallbacksController < Devise::OmniauthCallbacksController
include Devise::Controllers::Rememberable
def facebook
#user = User.find(...)
...
remember_me(#user) # set the remember_me cookie
end
end
This solution works well for me using Rails 3.1 and Devise 1.4.9.
I agree that you would expect Devise to set a session before the request goes to FB. I guess this is a missing feature of Devise.
I had the problem myself where I used token_authenticatable. An api client was calling the following url directly:
/users/auth/facebook?auth_token=TnMn7pjfADapMdsafOFIHKgJVgrBEbjKqrubwMXUca0n16m3Hzr7CnrP1s4z
Since I was using token_authenticatable i was assuming this would sign in the user. Unfortunately this doesn't work out of the box. What you have to do to get this working is making sure that the user is logged in before it gets to this path. You can do it in other ways, but the easiest way is to give a different url to the API client (in this case "users/connect/facebook". Here is my addition to the routes file that makes it work (assuming you have a user model with devise and you didn't change defaults):
authenticate :user do
get 'users/connect/:network', :to => redirect("/users/auth/%{network}")
end
This will make sure the session is correctly created so the user is being recognized when he/she returns from facebook.
It is fixed by devise contributors:
You should just add
user.remember_me = true
# then add your signing in code
sign_in(:user, user)
ref: https://github.com/plataformatec/devise/issues/776#issuecomment-807152
fyi - if you want to also use the extend_remember_period feature in devise - you need to force this on the user object in the callback controller
added one line to #mustafaturan's answer
user.remember_me = true
user.extend_remember_period = true
# then add your signing in code
sign_in(:user, user)

More settings for the facebook php API

Maybe I searched completely in the wrong way, and the facebook documentation pretty much sucks in my opinion.
I was wondering, I'm connecting to facebook with the settings below and that works (I'm able to retrieve the profile information of the logged in user allows my application to access his profile.) Are there other options I can set, like the callback url and the expiration (which I want to set to never, so I can save the token in my db and re-use it)?
This is the config now:
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxx',
'cookie' => true
));
I'm also connection to twitter and there I'm able to this:
$this->configTwitter = array(
'callbackUrl' => 'xxxxxxxxxxxx',
'siteUrl' => 'http://twitter.com/oauth',
'consumerKey' => 'xxxxxxxxxxxx',
'consumerSecret' => 'xxxxxxxxxxxx'
);
Thanks in advance!
Facebook should take a look at Twitter
After trying a few days, spitting the documentation of the Graph OAuth 2.0 (which doesn't work as good as expected and searching the internet I found a solution which I used to create the following script:
// Config
$this->redirectUrl = 'http://www.mywebsite.com/facebook'
$this->clientId = 'APPLICATION_ID';
$this->permissions = 'publish_stream,offline_access';
// Check if a sessions is present
if(!$_GET['session'])
{
// Authorize application
header('Location: http://www.facebook.com/connect/uiserver.php?app_id='.$this->clientId.'&next='.$this->redirectUrl.'&perms='.$this->permissions.'&return_session=1&session_version=3&fbconnect=0&canvas=1&legacy_return=1&method=permissions.request');
}
else
{
$token = json_decode($_GET['session']);
echo $token->access_token; // This is the access_token you'll need!
// Insert token in the database or whatever you want
}
This piece of code works great and performs the following actions:
Log in if the user isn't logged in to facebook
Asks if the user wants to add the application and grants the requested permissions (in my case: publish_stream and offline_access) in one dialog
returns to the page you specified under redirectUrl with an access_token (and because we requested for offline access this one doesn't expire)
I then store the token in the database so I won't have to request it again
Now you can, if you wish use the facebook code, or you're own code to get the users data, or other information from facebook (be sure you requested the right permissions)
Don't now if this is facebook-valid code, but it works great and I can easily define the 'config' like I wanted....
There are many settings you can set at the point of authenticating. Extended permissions let you set the offline_access so that you can authenticate and store your session in a db. More info on extended permissions are at developers.facebook.com/docs/authentication/permissions and you can read my blog post for more info on how to use them at http://www.joeyrivera.com/2010/facebook-graph-api-app-easy-w-php-sdk/

Facebook access_token invalid?

I'm attempting to use the new Graph API Facebook recently released, but I can't seem to get it to work correctly.
I've gone through the steps, and after the /authorize call, I receive an access_token:
access_token=109002049121898|nhKwSTJVPbUZ5JYyIH3opCBQMf8.
When I attempt to use that token I get:
{
"error": {
"type": "QueryParseException",
"message": "An active access token must be used to query information about the current user."
}
}
I'm stumped as too why...
-AC
When using your Facebook Application's token
If you're using the me alias as in https://graph.facebook.com/me/ but your token is acquired for a Facebook Application, then "me" isn't you anymore - it's the app or maybe nothing. Anyway, that's not your intention for the app to interact with itself.
In this case you will want to interact with your personal user account from an app. What you need to do (after giving the app the permissions it requests in the UI when it asks) is find your facebook userid # and put it in place of "me" to access your own info. e.g. Mark Zuckerberg's facebook userid is 4 so he is https://graph.facebook.com/4/
The alias me only works if you're you! Sometimes it's hard to remember who the current user is when programming facebook (i.e. you, the Page, the App, etc) because we're accustomed to using the facebook UI as ourselves most of the time. From a programming standpoint it depends on what the acquired token represents.
A great blog post that always helps correct me is Ben Biddington | Facebook Graph API — getting access tokens.
same thing here. I followed Ben Biddington's blog to get the access token. Same error when trying to use it. Facebook's OAuth implementation doesn't follow the spec completely, i am fine with it as long as the doc is clear, which obviously is not the case here. Aslo, it would be nice if the userid and username are returned with the access token.
Just to clarify -- after you call
https://graph.facebook.com/oauth/authorize?
you should receive a CODE which, in conjunction with your CLIENT_ID and CLIENT_SECRET (assuming you have registered your application) can be exchanged for an access_token at
https://graph.facebook.com/oauth/access_token?
If this is indeed how you came by your ACCESS_TOKEN, you should then be able to request
https://graph.facebook.com/me/
Adding type parameter returns the auth_token for the application level, so it is better to OMIT it. What worked for me, after countless attempts and combinations, is using the same redirect_url parameter in the call to /oath/access_token as was used in the call to /oath/authorize.
So the full sequence to authorize your app on someone's behalf is:
1. call or redirect to:
"https://graph.facebook.com/oauth/authorize?client_id=" + my_clientId + "&scope=publish_stream,offline_access,manage_pages" + "&redirect_uri=" + "http://my_redirect_url?blah"
2. in the page located at the return_url above, issue a request or what ever else to this url:
"https://graph.facebook.com/oauth/access_token?client_id=" + client_id + "&client_secret=" + secret + "&code=" + Request.QueryString["code"] + "&redirect_uri=" + "http://my_redirect_url?blah"
I've been having the exact same problem. A couple of things I've done to resolve it:
Try it all out in the browser first to make sure the urls are correct at each stage
Ensure the redirect url is identical, not just equivalent. Parameters in the same order, encoding the same
Don't use the type=client_cred, or anything else for that matter
Encode any ampersands in the redirect_url (but not the rest of the url) e.g. http://example.com/fb?foo=234%26bar=567. This one caused me the most issues. When the callback page was run, only the url before the first ampersand was included, as the ampersand was assumed to be part of the url for graph.facebook.com, not part of the redirect_url. I was then getting the values from the querystring to put in the redirect_url for the second call, but they weren't there. Once I encoded the ampersands they appeared correctly.
Don't have any empty values in you encoded querystring parameters (e.g. ?foo=%26bar=123)
I want to point out what has sort of been said on Ben Biddington's blog, and what I noticed from looking at the "malformed" access_token in the initial question. Others have said similar things in this thread, but I want to be explicit.
The token is not actually malformed, but rather a token that allows you to do actions on behalf of the APP, not the user. This is the token you'd use if you wanted to get all of the users of the app, or view insights for your app, etc, with the requests typically coming from your server, not the client. This type of token is gained by using the type=client_cred parameter. If you want to do things on behalf of the user, do not specify type=client_cred, and make sure you specify the following parameters in your call to http://graph.facebook.com/oauth/access_token:
'client_id' => APP_ID
'redirect_uri' => REDIRECT_URI
'client_secret' => APP_SECRET
'code' => $_GET['code']
I've written this as key-value pairs of a PHP array, but I think you get the point. The code GET value is gained after making the initial call to http://graph.facebook.com/oauth/authorize with the following parameters:
'client_id' => APP_ID
'redirect_uri' => "http://your.connect.url/some/endpoint"
I hope this helps! What the Facebook docs say, but don't say well, is that getting an access_token is a two-request process.
I actually noticed that if your return uri doesn't have a slash on the end you have issues. I'm currently testing in the browser and return_uri=https://mydomain.com doesn't work but return_uri=https://mydomain.com/ does work. If I use the first I get "Error validating verification code."
This seems a bit odd, but I prolly just missed a word in the spec/instructions some where. Did lose two hours of my life to it though.
I had the same problem, but getting rid of type=client_cred and making sure that the redirect_uri parameter is the same when making the authorize and the access_token call fixed the issue.
I had the same issue in IE8 only.
The solution for me was sending the access_token in the API request.
Something like this:
FB.api('/me/friends?access_token=<YOUR TOKEN>
I obtained my token through PHP like this:
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => '<API_ID>',
'secret' => '<SECRET>',
'cookie' => false,
));
$session = $facebook->getSession();
$token = $session['access_token'];