parsing # in rails uris - ruby-on-rails

i am getting the following url information and need to parse it within rails. i already checked request and params but it is not there.
the "#" character seems to f*ck up things.
here's the url:
http://foo.bar.me/whoo#access_token=131268096888809%7C2.5BRBl_qt4xJ08n88ycbpZg__.3600.1276880400-100001151606930%7C0kJ1K-qoGBbDoGbLx6s4z5UEaxM.
thanks for any pointers.

You won't be able to access the part after the '#' character as the browser doesn't send it to the server. You can use it on the client side with javascript though.
It seems that you're trying to use the javascript based authentication which is not what you really want.
I didn't have any problems using this oauth2 library. Then you only need to check for params[:code] within your callback action.
UPDATE:
This is a simplified version of the code I used in my experiments with the new facebook graph API:
# Accessible as facebook_url:
# routes.rb: map.facebook '/facebook', :controller => 'facebook', :action => 'index'
def index
oauth2 = OAuth2::Client.new(FB_API_KEY, FB_API_SECRET, :site => 'https://graph.facebook.com')
if current_user.facebook_token
# The user is already authenticated
fb = OAuth2::AccessToken.new(oauth2, current_user.facebook_sid)
result = JSON.parse(fb.get('/me'))
elsif params[:code]
# Here we get the access token from facebook
fb = oauth2.web_server.get_access_token(params[:code], :redirect_uri => facebook_url)
result = JSON.parse(fb.get('/me'))
current_user.facebook_id = result["id"]
current_user.facebook_token = fb.token.to_s
current_user.save
else
# The user is visiting this page for the first time. We redirect him to facebook
redirect_to oauth2.web_server.authorize_url(:redirect_uri => facebook_url, :scope => 'read_stream,publish_stream,offline_access')
end
end
You don't really need anything else for it to work.

Related

Twilio can't find xml on rails

I am integrating twilio click to call into my rails project.
Everything works fine however the url: in my twilio controller cannot be found on heroku. However, it can be found if you navigate to it in a browser. The phone dials but the voice says "Sorry a problem has occurred, good bye." If I change the url to an external xml file it works fine, just doesn't recognize this particular one. So I'm lead to believe that the controller etc works fine.
twillio_controller.rb
def call
#full_phone = current_user.phone
#partial_phone = #full_phone.last(-1)
#connected_number = "+61" + #partial_phone
#client = Twilio::REST::Client.new ##twilio_sid, ##twilio_token
# Connect an outbound call to the number submitted
#call = #client.calls.create(
:from => ##twilio_number,
:to => #connected_number,
:url => 'http://besttradies.herokuapp.com/mytradies/connect.xml', # Fetch instructions from this URL when the call connects
)
#msg = { :message => 'Phone call incoming!', :status => 'ok' }
end
def connect
# Our response to this request will be an XML document in the "TwiML"
# format. Our Ruby library provides a helper for generating one
# of these documents
response = Twilio::TwiML::Response.new do |r|
r.Say 'If this were a real click to call implementation, you would be connected to an agent at this point.', :voice => 'alice'
end
render text: response.text
end
The OP solved in the comments above:
Figured it out. Routes for connect needed to be POST and I also had to
add skip_before_action :verify_authenticity_token to the twilio
controller as it was behind membership doors.

How to Handle OAuth Response with Octokit Ruby vs Restclient

Hi I'm new to Ruby/Rails and I had a question about handling an OAuth response with the Ruby version of GitHub's Octokit. After reading the documentation I'm a little confused about how to follow best practices with the wrapper vs with RestClient. When I authorize my app the response returns a "code" which I'm supposed to exchange for an access token.
In the GitHub API documentation it shows a Sinatra example of this with Restclient, which is currently in my create action of the sessions controller. However, it says you should approach it differently when building an app and that you should use the Octokit library, but I can't find any documentation on exactly how to exchange the code for an access token with Octokit.
My goal is to be able to crete a new member for the app via a user's GitHub account, save that info, & then sign them in with that account, rather then ever creating a username/password. I've pasted my new.html.erb code below to show the request that I am making as well. Really appreciate any help, thank you!
Sessions Controller
class SessionsController < ApplicationController
def new
#client_id = Octokit.client_id
end
def create
# CHANGE THIS TO USE OCTOKIT INSTEAD
session_code = request.env['rack.request.query_hash']['code']
result = RestClient.post('https://github.com/login/oauth/access_token',
{:client_id => Octokit.client_id,
:client_secret => Octokit.client_secret,
:code => session_code},
:accept => :json)
access_token = JSON.parse(result)['access_token']
end
end
OAuth Request
<p>
Sign In with GitHub
</p>
<p>
Click here to begin!</a>
</p>
As it doesn't explicitly state this in the README. What I recommend is always going through the source code to get a better understanding of how a gem works. Often you will find that the gem's creator(s) have written great code that is self-explanatory, and sometimes even commented to provide more info as in the situation below. Here is the method you're looking for, good luck on your journey to learn to Ruby/Rails and welcome! Let me know if you have any more questions and run into any more issues getting this to work.
# Retrieve the access_token.
#
# #param code [String] Authorization code generated by GitHub.
# #param app_id [String] Client Id we received when our application was registered with GitHub.
# #param app_secret [String] Client Secret we received when our application was registered with GitHub.
# #return [Sawyer::Resource] Hash holding the access token.
# #see http://developer.github.com/v3/oauth/#web-application-flow
# #example
# Octokit.exchange_code_for_token('aaaa', 'xxxx', 'yyyy', {:accept => 'application/json'})
def exchange_code_for_token(code, app_id = client_id, app_secret = client_secret, options = {})
options.merge!({
:code => code,
:client_id => app_id,
:client_secret => app_secret,
:headers => {
:content_type => 'application/json',
:accept => 'application/json'
}
})
post "#{web_endpoint}login/oauth/access_token", options
end

Authenticating Rails App w/ Soundcloud, Getting 401 Unauthorized Error: invalid_grant

Forgive me if this is a stupid question, novice programmer here.
I am trying to use the Soundcloud API to authenticate users in my Rails 3.2.14 app. I'm using the code directly from the Soundcloud developer docs, like so:
client = Soundcloud.new(
:client_id => 'MY_CLIENT_ID',
:client_secret => 'MY_CLIENT_SECRET',
:redirect_uri => 'http://localhost:3000/auth/soundcloud/callback'
)
# redirect user to authorize URL
redirect_to client.authorize_url(:scope => 'non-expiring')
And when I GET the callback URI:
client = Soundcloud.new(
:client_id => 'MY_CLIENT_ID',
:client_secret => 'MY_CLIENT_SECRET',
:redirect_uri => 'http://localhost:3000/auth/soundcloud/callback'
)
# exchange authorization code for access token
code = params[:code]
access_token = client.exchange_token(:code => code)
Everything works fine (I am taken to the Soundcloud page to give my app permissions) but when I am sent back to the callback URI I receive the following error:
SoundCloud::ResponseError at /auth/soundcloud/callback
HTTP status: 401 Unauthorized Error: invalid_grant
I've obviously googled this and the only suggestion made was that my token is expiring. That doesn't make sense to me because I'm not reusing the access_token later, I'm just doing the initial authentication. Just in case I included the scope => non-expiring parameter when I redirected to Soundcloud, which made no difference.
Any suggestions? Has anyone had success integrating Rails with Soundcloud recently? All of the resources I've found seem quite outdated.
I got this error, when I was not exchanging the :code for the access_token correctly. Check your variables using pry and make sure your :code is not nil
its also shows up when the access_token has expired, I know you are passing in :scope => 'non-expiring', but perhaps it loses the parameter at some point

Rails 3 + fb_graph how to get access token to post to my own FB page

I am using Rails 3 + fb_graph to post to my own Facebook page. I have code that works, but it uses an access token that only works for a couple of hours. And it is very annoying to refresh this access token a couple of times a day. So I registrated for a FB app. I now have:
my_app = FbGraph::Application.new("App ID");
acc_tok = my_app.get_access_token("App Secret");
me = FbGraph::User.me(acc_tok)
me.fetch
me.accounts
account = me.accounts.select {|account| account if account.name == "BoaJobs.com"}.first
page = FbGraph::Page.new(account.identifier)
note = page.note!(:access_token => account.access_token, :subject => #title, :message => #message, :link => #url)
But I am getting an error on the me.fetch line:
OAuthException :: An active access token must be used to query information about the current user.
Can somebody post some code that helps me solve this problem. Thank you very much in advance.
ill refer you to https://github.com/nov/fb_graph/wiki/Page-Management
where nov states: You need the page’s access token to manage your page.
Your (an user’s) access token doesn’t work here.
follow his link to the facebook developers site for more info
you'll need the users access_token and i do this through omniauth-facbook https://github.com/mkdynamic/omniauth-facebook
which you retrieve the use by first inputting this initializer into your app
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'],
:scope => 'email,user_birthday,read_stream', :display => 'popup'
end
(note you can change the permissions on the scope here check facebook developers login permissions for more
there are some inner workings to omniauth and omniauth-facebook but the jist is
when you get the callback from facebook you have a rack omniauth hash from the request
omniauth = request.env["omniauth.auth"]
from that has you can access the users access token like this
facebook_user_token = omniauth['credentials']['token']
you can then feed that token into your fb_graph page call
page = FbGraph::Page.new('FbGraph').fetch(
:access_token => facebook_user_token,
:fields => :access_token
)
you will then simply be able to create a note by calling your desired method without a reference to the access token
note = page.note!(:subject => #title, :message => #message, :link => #url)

Post to an application's page with the page using application token? koala

Every day I want to run a rake task that will post an update to the application's Facebook page. The page is defined under Facebook > App > Settings > Advanced (at the bottom).
I want to get the an app access token and then post as the page to the page. This is kind of what I was thinking, but it doesn't work:
#oauth = Koala::Facebook::OAuth.new(CONFIG['appid'], CONFIG['appsecret'])
#token = #oauth.get_app_access_token
#page_graph = Koala::Facebook::API.new(#token)
#page_graph.put_connections('NAME_OF_PAGE','feed', :message => 'This is posted as the page')
The error I get:
OAuthException: (#200) The user hasn't authorized the application to perform this action
I don't know if there is a place for (I tried passing as an option in #oauth.get_app_access_token):
#oauth.get_app_access_token(:permissions => "manage_pages")
Still nothing. Any ideas?
[UPDATE]
So I changed to:
#oauth = Koala::Facebook::OAuth.new(CONFIG['appid'], CONFIG['appsecret'])
#token = #oauth.get_app_access_token
#page_graph = Koala::Facebook::API.new(#token)
#postid = #page_graph.put_connections(CONFIG['appid'],'feed', :message => 'This is posted as the page')
Then when I output #postid, I get a valid ID. I put this id into: https://graph.facebook.com/POSTID and I get a valid response.
This is super confusing. Why is it not appearing on the page??
I'm having the same problem. So far, I only found this method for OAuth, in order to get permission to publish:
#oauth.url_for_oauth_code(:permissions => "publish_stream")
but I keep having the error that I can't apply this method to a string. I presume it fails and it doesn't return a oAuth structure, but a string instead.

Resources