I'm trying to grab Twilio recordings with the following GET request to their API in my Rails controller:
def myrecordings
account_sid = 'AC32a3c49700934481addd5ce1659f04d2'
auth_token = 'asd89f677asd897asdfd9' #this is made up for now
client = Twilio::REST::Client.new(account_sid, auth_token)
#recordings = client.account.recordings.list()
render :json => #recordings
end
As a result I'm getting a 500 response error with the message "Authenticate"
My application trace is
app/controllers/campaigns_controller.rb:13:in `myrecordings' [the #recordings line]
To the best of my knowledge I'm following what are in the Twilio docs here:
http://www.twilio.com/docs/api/rest/recording
But clearly I'm missing something. The account_sid and auth_token are correct, but is there a security issue?
require 'rubygems'
require 'twilio-ruby' # Download twilio-ruby from twilio.com/docs/libraries
# Get your Account Sid and Auth Token from twilio.com/user/account
account_sid = 'AC32a3c49700934481addd5ce1659f04d2'
auth_token = '{{ auth_token }}'
#client = Twilio::REST::Client.new account_sid, auth_token
# Loop over recordings and print out a property for each one
#client.account.recordings.list.each do |recording|
puts recording.sid
end
From the docs, this should work too, assuming you change the sid and token to the right ones
Related
I spent hours looking for a solution to my problem without luck.
I created a Rails app that interacts with Google Calendar API and, following a guide, I was able to make it work. Then I shut down my local server and ran it again after 2/3 hours and I started receiving this error when I make a request to the API:
Signet::AuthorizationError (Unexpected error: #<ArgumentError: Missing authorization code.>)
I figured out that the problem is that the token is expired, 'cause I can't understand why it was working and then not anymore.
This is my controller:
require 'google/api_client/client_secrets.rb'
require 'google/apis/calendar_v3'
CALENDAR_ID = Here I have my Calendar_ID
GOOGLE_CLIENT_ID = Here I have my Google_Client_ID
GOOGLE_CLIENT_SECRET = Here I have my Google_Client_Secret
class CalendarController < ApplicationController
def calendars
client = Signet::OAuth2::Client.new(client_options)
client.update!(session[:authorization])
service = Google::Apis::CalendarV3::CalendarService.new
service.authorization = client
#calendar_list = service.list_calendar_lists
rescue Google::Apis::AuthorizationError
response = client.refresh!
session[:authorization] = session[:authorization].merge(response)
retry
end
def redirect
client = Signet::OAuth2::Client.new(client_options)
redirect_to client.authorization_uri.to_s, allow_other_host: true
end
def callback
client = Signet::OAuth2::Client.new(client_options)
client.code = params[:code]
response = client.fetch_access_token!
session[:authorization] = response
redirect_to calendars_url
end
private
def client_options
{
client_id: GOOGLE_CLIENT_ID,
client_secret: GOOGLE_CLIENT_SECRET,
authorization_uri: 'https://accounts.google.com/o/oauth2/auth',
token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
scope: Google::Apis::CalendarV3::AUTH_CALENDAR,
redirect_uri: callback_url
}
end
end
Then my routes:
get '/redirect', to: 'calendar#redirect', as: 'redirect'
get '/callback', to: 'calendar#callback', as: 'callback'
get '/calendars', to: 'calendar#calendars', as: 'calendars'
What can I do to solve my issue? I'm a newbie on Rails, so it's not quite simple for me
When I send any message it gives an error.
Twilio::REST::RequestError: The requested resource /2010-04-01/Accounts/cafac01e41ad5fbad3da4ad8619c8d36/Messages.json was not found
# set up a client to talk to the Twilio REST API
#client = Twilio::REST::Client.new account_sid, auth_token
#client.account.messages.create({
:from => 'xxxxxx',
:to => 'xxxxxx',
:body => 'Twilio Testing',
})
Aside from the potential issue Devin brought up in the comments regarding an incorrect Account SID in your Url, the following code examples may help.
Code to setup Twilio-Ruby:
require 'rubygems' # not necessary with ruby 1.9 but included for completeness
require 'twilio-ruby'
# put your own credentials here
account_sid = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
auth_token = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'
# set up a client to talk to the Twilio REST API
#client = Twilio::REST::Client.new account_sid, auth_token
# alternatively, you can preconfigure the client like so
Twilio.configure do |config|
config.account_sid = account_sid
config.auth_token = auth_token
end
# and then you can create a new client without parameters
#client = Twilio::REST::Client.new
And then the code to send an SMS:
#client.messages.create(
from: '+1415XXXXXXX',
to: '+1610XXXXXXX',
body: 'Hey there!'
)
I'm trying to access all the contacts from Google Contacts for invite purposes from my site.
So I'm using OAuth2 but when I first request I get a 401 error with access_token. :(
Keep in mind I'm working local!!
Here's my code.
def authenticate
# initiate authentication w/ gmail
# create url with url-encoded params to initiate connection with contacts api
# next - The URL of the page that Google should redirect the user to after authentication.
# scope - Indicates that the application is requesting a token to access contacts feeds.
# secure - Indicates whether the client is requesting a secure token.
# session - Indicates whether the token returned can be exchanged for a multi-use (session) token.
next_param = "http://localhost:3000/import/authorise"
scope_param = "https://www.google.com/m8/feeds/"
#session_param = "1"
state="profile"
client_id="535946964206.apps.googleusercontent.com"
root_url = "https://accounts.google.com/o/oauth2/auth"
response_type="token"
#TO FIND MORE ABOUT THESE PARAMETERS AND THERE MEANING SEE GOOGLE API DOCS.
query_string = "?scope=#{scope_param}&state=#{state}&redirect_uri=#{next_param}&response_type=#{response_type}&client_id=#{client_id}"
#render :text=> root_url + query_string and return
# redirect_to "https://accounts.google.com/o/oauth2/auth?
#scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&
#state=%2Fprofile&
#redirect_uri=http://localhost:3000/import/authorise&
#response_type=token&
#client_id=535946964206.apps.googleusercontent.com
#"
redirect_to root_url + query_string
end
this is for authentication now i get response with access token
http://localhost:3000/import/authorise#state=profile&access_token=ya29.1.AADtN_WPohnlKYBH16kFrqEcYUTZ558WDICpqCqiz1mwBKESFr5PTiJFA5vsyoc&token_type=Bearer&expires_in=3600
Now next it will redirected to here,this is where i get above error
# YOU WILL BE REDIRECTED TO THIS ACTION AFTER COMPLETION OF AUTHENTICATION PROCESS WITH TEMPORARY SINGLE USE AUTH TOKEN.
def authorise
#FIRST SINGEL USE TOKEN WILL BE RECEIVED HERE..
token = params[:token]
#PREPAIRING FOR SECOND REQUEST WITH AUTH TOKEN IN HEADER.. WHICH WILL BE EXCHANED FOR PERMANENT AUTH TOKEN.
uri = URI.parse("https://www.google.com")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
path = '/accounts/AuthSubSessionToken'
headers = {'Authorization' => "AuthSub token=#{token}"}
render :text=> http.get(path, headers) and return
#GET REQUEST ON URI WITH SPECIFIED PATH...
resp, data = http.get(path, headers)
#ender :text=> data and return
resp.code="200"
#SPLIT OUT TOKEN FROM RESPONSE DATA.
if resp.code == "200"
token = ''
data.split.each do |str|
if not(str =~ /Token=/).nil?
token = str.gsub(/Token=/, '')
end
end
return redirect_to(:action => 'import', :token => token)
else
redirect_to root_url , :notice => "fail"
end
end
here at above function when it requests resp, data = http.get(path, headers) the responce resp.code is 401 . i dont know what's wrong i'm following https://gist.github.com/miketucker/852849 example which uses AuthSub which is now not in use so i'm adapting oauth2 .
i already have made app at clode console and given return url and other info.
any help or point me to other working example,thanks you!!!
thank you.
I want to write a script which calls a REST API using a URL like:
http://localhost:3000/api/v1/user/xyz
If I open this URL in the browser, it asks for a user email and password. Once I've authenticated, it returns a JSON response with a user id. I don't know how I should I authenticate through the script. Can someone give me a suggestion?
This is what I started with:
require 'rubygems'
require 'net/http'
require 'json'
api_url = "http://localhost:3000/api/v1//user/xyz"
response = Net::HTTP.get_response(URI.parse(api_url))
data = JSON.parse(response.body)
fields = data.keys
puts fileds
puts data.keys
This is the authentication for the API:
before_filter :authorize, :except => [:keys]
private
def authorize
authenticate_or_request_with_http_basic do |username, password|
user = User.find_by_email(username)
if user && user.valid_password?(password)
sign_in :user, user
end
end
end
How I can pass email and password to authenticate this API so I can get "id" as return?
rest_client gem works great for me. As far as what the API returns that should be in the documentation. You can always try it in IRB and see what the response contains.
HTTP Basic authentication is pretty simple to add to your request, though I don't think you can use the get_response convenience method.
See: http://ruby-doc.org/stdlib-2.0/libdoc/net/http/rdoc/Net/HTTP.html#label-Basic+Authentication
Example from the documentation:
uri = URI('http://example.com/index.html?key=value')
req = Net::HTTP::Get.new(uri)
req.basic_auth 'user', 'pass' # username, password go here.
res = Net::HTTP.start(uri.hostname, uri.port) {|http|
http.request(req)
}
puts res.body
So I logged in with Google and it hits my callback url with a code parameter.
Here is how I initiate my client, I'm using oauth2 gem.
def oauth_client(channel_name)
file = YAML.load_file("#{Rails.root}/config/oauth_credentials.yml")
client_id = file['oauth_credentials'][channel_name]['client_id']
client_secret = file['oauth_credentials'][channel_name]['secret']
site = file['oauth_credentials'][channel_name]['site']
OAuth2::Client.new(client_id, client_secret, site: site, authorize_url: "/o/oauth2/auth", connection_opts: { params: { scope: "https://www.googleapis.com/auth/adsense https://www.googleapis.com/auth/analytics.readonly" } })
end
def oauth_url_for(channel_name)
client = oauth_client(channel_name)
client.auth_code.authorize_url(:redirect_uri => oauth_callback_url(channel: channel_name))
end
Here's my controller
class Oauth2Controller < ApplicationController
include ApplicationHelper
def callback
token = oauth_client(params[:channel]).auth_code.get_token(params[:code], :redirect_uri => oauth_callback_url(channel: params[:channel]))
current_user.connections.create!(channel: params[:channel], token: token)
render text: request.inspect
end
end
Unfortunately I can't get_token due to a response from google saying The page you requested is invalid.
It doesn't look like you're defining the token_url value in your initialization of the client, or later. It is "o/oauth2/token". By default "/oauth/token" is used, so that's likely the cause of your "page you requested is invalid" error.
Source:
http://rubydoc.info/gems/oauth2/0.8.0/OAuth2/Client#initialize-instance_method