undefined method `get_access_token' - ruby-on-rails

My twitter controller code is this
class TwitterController < ApplicationController
before_filter :authenticate_user!
def index
unless TwitterOauthSetting.find_by_user_id(current_user.id).nil?
redirect_to "/twitter_profile"
end
end
def generate_twitter_oauth_url
oauth_callback = "http://#{request.host}:#{request.port}/oauth_account"
#consumer = OAuth::Consumer.new("n3yfOi9iEHwnyz5uEsyNotW6t","kqHFm5dRRX00dIQSwBcTEJKZNAzrWcuK0BOAyDVWY8liRI1cPc", :site => "https://api.twitter.com")
#request_token = #consumer.get_request_token(:oauth_callback => oauth_callback)
session[:request_token] = #request_token
redirect_to #request_token.authorize_url(:oauth_callback => oauth_callback)
end
def oauth_account
if TwitterOauthSetting.find_by_user_id(current_user.id).nil?
#request_token = session[:request_token]
#access_token = #request_token.get_access_token(:oauth_verifier => params["oauth_verifier"])
TwitterOauthSetting.create(atoken: #access_token.token, asecret: #access_token.secret, user_id: current_user.id)
update_user_account()
end
redirect_to "/twitter_profile"
end
def twitter_profile
#user_timeline = get_client.user_timeline
#home_timeline = get_client.home_timeline
end
private
def get_client
Twitter.configure do |config|
config.consumer_key = "n3yfOi9iEHwnyz5uEsyNotW6t"
config.consumer_secret = "kqHFm5dRRX00dIQSwBcTEJKZNAzrWcuK0BOAyDVWY8liRI1cPc"
end
Twitter::Client.new(
:oauth_token => TwitterOauthSetting.find_by_user_id(current_user.id).atoken,
:oauth_token_secret => TwitterOauthSetting.find_by_user_id(current_user.id).asecret
)
end
def update_user_account
user_twitter_profile = get_client.user
current_user.update_attributes({
name: user_twitter_profile.name,
screen_name: user_twitter_profile.screen_name,
url: user_twitter_profile.url,
profile_image_url: user_twitter_profile.profile_image_url,
location: user_twitter_profile.location,
description: user_twitter_profile.description
})
end
end
On index page add your twitter account option is there. After clicking on that it will authorize app & After authorizaion process i am facing an error "undefined method `get_access_token' .i am facing error in this line " #access_token = #request_token.get_access_token(:oauth_verifier => params["oauth_verifier"])"

The solution of my problem:
What i did is I added a new method to prepare access token & in get client method used Twitter::REST::Client.new do |config| and also provided access_token & access_token_secret_key and now it is working properly.
class TwitterController < ApplicationController
before_filter :authenticate_user!
def index
unless TwitterOauthSetting.find_by_user_id(current_user.id).nil?
redirect_to "/twitter_profile"
end
end
def generate_twitter_oauth_url
oauth_callback = "http://#{request.host}:#{request.port}/oauth_account"
#consumer = OAuth::Consumer.new("2K763Dgw9y6oAOOLsegegkHW7","pwXauJeR628SL8DhgwikStNYykGCKoabISHI4ZUnKIxt2eSmNY", :site => "https://api.twitter.com")
#request_token = #consumer.get_request_token(:oauth_callback => oauth_callback)
session[:request_token] = #request_token
redirect_to #request_token.authorize_url(:oauth_callback => oauth_callback)
end
def oauth_account
if TwitterOauthSetting.find_by_user_id(current_user.id).nil?
#request_token = session[:request_token]
prepare_access_token(params[:oauth_token],params[:oauth_token_secret])
#consumer = OAuth::Consumer.new(params[:oauth_token],params[:oauth_token_secret], :site => "https://api.twitter.com")
#access_token = prepare_access_token(params[:oauth_token],params[:oauth_token_secret])
TwitterOauthSetting.create(atoken: #access_token.token, asecret: #access_token.secret, user_id: current_user.id)
update_user_account()
end
redirect_to "/twitter_profile"
end
def twitter_profile
#user_timeline = get_client.user_timeline
#home_timeline = get_client.home_timeline
end
private
def get_client
Twitter::REST::Client.new do |config|
config.consumer_key = "n3yfOi9iEHwnyz5uEsyNotW6t"
config.consumer_secret = "kqHFm5dRRX00dIQSwBcTEJKZNAzrWcuK0BOAyDVWY8liRI1cPc"
config.access_token = "access_token key"
config.access_token_secret = "access_token_secret key"
end
end
def update_user_account
user_twitter_profile = get_client.user
current_user.update_attributes({
name: user_twitter_profile.name,
screen_name: user_twitter_profile.screen_name,
url: user_twitter_profile.url,
profile_image_url: user_twitter_profile.profile_image_url,
location: user_twitter_profile.location,
description: user_twitter_profile.description
})
end
def prepare_access_token(oauth_token, oauth_token_secret)
#consumer = OAuth::Consumer.new("APIKey", "APISecret", { :site => "https://api.twitter.com", :scheme => :header })
#consumer = OAuth::Consumer.new("2K763Dgw9y6oAOOLsegegkHW7","pwXauJeR628SL8DhgwikStNYykGCKoabISHI4ZUnKIxt2eSmNY", { :site => "https://api.twitter.com", :scheme => :header })
# 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
end

Your #request_token is apparently a string, which is why the get_access_token method is undefined.
Replace the oauth_account method with the one below to recreate the #request_token because #request_token = session[:request_token] will create a string instead and the get_access_token method is hence undefined.
def oauth_account
if TwitterOauthSetting.find_by_user_id(current_user.id).nil?
# Re-create the request token
#consumer = OAuth::Consumer.new(ENV["consumer_key"], ENV["consumer_secret"], :site => "https://api.twitter.com")
#request_token = OAuth::RequestToken.new(#consumer, session[:request_token], session[:request_secret])
#access_token = #request_token.get_access_token(:oauth_verifier => params["oauth_verifier"])
TwitterOauthSetting.create(atoken: #access_token.token, asecret: #access_token.secret, user_id: current_user.id)
update_user_account()
end
redirect_to "/twitter_profile"
end
Replace the get_client method with the one below to access the user's token and its access which are stored in the session.
def get_client
Twitter::REST::Client.new do |config|
config.consumer_key = ENV["consumer_key"]
config.consumer_secret = ENV["consumer_secret"]
unless TwitterOauthSetting.find_by_user_id(current_user.id).nil?
config.oauth_token = TwitterOauthSetting.find_by_user_id(current_user.id).atoken
config.oauth_token_secret = TwitterOauthSetting.find_by_user_id(current_user.id).asecret
end
end
end

Check using logger the value of #acces_token. Maybe it is not getting the required value or datatype.

Related

Active Merchant paypal recurring payments

I am using Active Merchant gem to handle payments through the site. But now i want to make these payments recurring, on a monthly basis. Is there a way using active merchant or?
subscription_controller.rb
class SubscriptionsController < ApplicationController
def new
#home_page = true
#white = true
#subscription = Subscription.new(token: params[:token])
if !logged_in?
redirect_to signup_url
end
end
def create
#subscription = Subscription.new(subscription_params)
#subscription.remote_ip = request.remote_ip
#subscription.user_id = current_user.id
if #subscription.save
if #subscription.purchase
#subscription.send_thank_you_email
redirect_to thankyou_path
else
raise ActiveRecord::Rollback
flash[:notice] = "It seems something went wrong with the paypal transaction. Please check that your credit card is valid and has credit in it and try again."
redirect_to :back
end
else
flash[:notice] = "Something went wrong with marking your purchase as complete. Please contact support to check it out."
redirect_to :back
end
end
def purchase
response = GATEWAY.setup_purchase(999,
ip: request.remote_ip,
return_url: new_subscription_url,
cancel_return_url: root_url,
currency: "USD",
items: [{name: "Order", description: "Recurring payment for ******", quantity: "1", amount: 999}]
)
redirect_to GATEWAY.redirect_url_for(response.token)
end
def thank_you
#home_page = true
#white = true
end
private
def subscription_params
params.require(:subscription).permit(:token)
end
end
subscription.rb model
def purchase
response = GATEWAY.purchase(999, express_purchase_options)
response.success?
end
def token=(token)
self[:token] = token
if new_record? && !token.blank?
# you can dump details var if you need more info from buyer
details = GATEWAY.details_for(token)
puts details.params["PayerInfo"]["PayerName"].inspect
self.payer_id = details.payer_id
self.first_name = details.params["PayerInfo"]["PayerName"]["FirstName"]
self.last_name = details.params["PayerInfo"]["PayerName"]["LastName"]
end
end
# send thank you email
def send_thank_you_email
UserMailer.thank_you(self).deliver_now
end
private
def express_purchase_options
{
:ip => remote_ip,
:token => token,
:payer_id => payer_id
}
end
production.rb environment
config.after_initialize do
ActiveMerchant::Billing::Base.mode = :production
::GATEWAY = ActiveMerchant::Billing::PaypalExpressGateway.new(
:login => ENV['PAYPAL_LOGIN'],
:password => ENV['PAYPAL_PASSWORD'],
:signature => ENV['PAYPAL_SIGNATURE']
)
end
I think ActiveMerchant used to have something like this:
subscription = PAYPAL_EXPRESS_GATEWAY.recurring(#subscription.price_in_cents, nil,
:description => 'blah',
:start_date => Date.tomorrow,
:period => 'Year',
:frequency => 1,
:amount => price,
:currency => 'USD'
)
See this answer Does ActiveMerchant support Subscription Based transaction
Also see this: https://github.com/activemerchant/active_merchant/blob/master/lib/active_merchant/billing/gateways/paypal_express.rb
https://github.com/activemerchant/active_merchant/blob/master/lib/active_merchant/billing/gateways/paypal/paypal_recurring_api.rb

fineuploader multi-part rails

I am trying to get multi-part upload working with rails as server to sign the requests.
Below is the code snippet. signature.endpoint is create action.
require 'base64'
require 'openssl'
require 'digest/sha1'
class WelcomeController < ApplicationController
skip_before_action :verify_authenticity_token
def success
render json: params
end
def index
end
def create
if(params[:headers])
signature = OpenSSL::HMAC.digest(
OpenSSL::Digest::Digest.new('sha1'),
key,
params[:headers].to_s).gsub("\n", "")
params[:signature]= signature
else
conditions = params[:conditions]
conds = [
{"acl" => "private"},
{"bucket" => conditions[1][:bucket]},
{"Content-Type" => conditions[2]["Content-Type"]},
{"success_action_status" => "200"},
{"key" => conditions[4][:key]},
{"x-amz-meta-qqfilename" => conditions[5]["x-amz-meta-qqfilename"]}
]
policy = Base64.encode64({ "expiration" => params[:expiration],
"conditions" => conds
}.to_json).
gsub("\n","")
signature = Base64.encode64(
OpenSSL::HMAC.digest(
OpenSSL::Digest::Digest.new('sha1'),
key, policy)
).gsub("\n","")
params[:signature]= signature
params[:policy] = policy
end
render :json => params, :status => 200 and return
end
end
This works fine for files < 5mb in size, i.e. else part of if-else block.
But, request is not signed properly when the file size > 5mb.
Please suggest what am I missing here.
Soln:
require 'base64'
require 'openssl'
require 'digest/sha1'
class WelcomeController < ApplicationController
skip_before_action :verify_authenticity_token
def success
render json: params
end
def index
end
def create
if(params[:headers])
logger.info params[:welcome][:headers]
signature = Base64.encode64(OpenSSL::HMAC.digest(
OpenSSL::Digest::Digest.new('sha1'),
key,
params[:welcome][:headers])).gsub("\n", "")
params[:signature]= signature
else
conditions = params[:conditions]
conds = [
{"acl" => "public-read"},
{"bucket" => conditions[1][:bucket]},
{"Content-Type" => conditions[2]["Content-Type"]},
{"success_action_status" => "200"},
{"key" => conditions[4][:key]},
{"x-amz-meta-qqfilename" => conditions[5]["x-amz-meta-qqfilename"]}
]
policy = Base64.encode64({ "expiration" => params[:expiration],
"conditions" => conds
}.to_json).
gsub("\n","")
signature = Base64.encode64(
OpenSSL::HMAC.digest(
OpenSSL::Digest::Digest.new('sha1'),
key, policy)
).gsub("\n","")
params[:signature]= signature
params[:policy] = policy
end
logger.info signature
render :json => params, :status => 200 and return
end
end

Twitter Oauth: where is oauth_token_secret?

I'm getting what seems to be a successful response from Twitter:
/auth/twitter/callback?oauth_token=somelongtoken&oauth_verifier=someverifier
But there's no oauth_token_secret there. Where do I get it?
DETAIL
routes.rb
get '/auth/:provider', to: 'authorisations#authorise', :as => :new_auth
get '/auth/:provider/callback', to: 'authorisations#callback'
authorisations_controller.rb
def authorise
session[:user_id] = current_user.id
#authorisation = Authorisation.new
#authorisation.user_id = current_user.id
if auth_hash.provider == "facebook"
#authorisation.provider = auth_hash.provider
#authorisation.oauth_token = auth_hash.credentials.token
#authorisation.oauth_expires_at = Time.at(auth_hash.credentials.expires_at)
elsif params[:provider] == "twitter"
#authorisation.provider = params[:provider]
#authorisation.oauth_token = params[:oauth_token]
#authorisation.oauth_token_secret = params[:oauth_token_secret]
#authorisation.access_token = params[:oauth_verifier]
end
#authorisation.save!
end
def callback
session[:user_id] = current_user.id
#authorisation = Authorisation.new
#authorisation.user_id = current_user.id
if auth_hash.provider == "facebook"
#authorisation.provider = auth_hash.provider
#authorisation.oauth_token = auth_hash.credentials.token
#authorisation.oauth_expires_at = Time.at(auth_hash.credentials.expires_at)
elsif params[:provider] == "twitter"
#authorisation.provider = params[:provider]
#authorisation.oauth_token = params[:oauth_token]
#authorisation.oauth_token_secret = params[:oauth_token_secret]
#authorisation.access_token = params[:oauth_verifier]
end
#authorisation.save!
redirect_to root_url, notice: "#{current_user.name} and #{params[:provider].titlecase} have been linked."
end
def auth_hash
request.env['omniauth.auth']
end
documents_controller.rb
def twitter
session[:return_to] = request.referer
#document = Document.find(params[:id])
if #document.template.name == "Image"
#document.process_social_media
twitter_user.update_with_media("#{#document.remove_html(#document.components.first.body[0..100])}...", "#{root_url}temporary#{#document.temp_file_name}.jpg")
else
twitter_user.update("#{#document.remove_html(#document.components.first.body[0..100])}... #{root_url.gsub(/\/$/, '')}#{share_path(#document.user.ftp, #document)}")
end
redirect_to session[:return_to], notice: "#{#document.title} has been posted to Twitter."
end
def twitter_user
user = Twitter.configure do |config|
config.consumer_key = ENV['TWITTER_CONSUMER_KEY']
config.consumer_secret = ENV['TWITTER_CONSUMER_SECRET']
config.oauth_token = current_user.single_authorisation("twitter").oauth_token
config.oauth_token_secret = current_user.single_authorisation("twitter").oauth_token_secret
end
end
It has been a while since I did this, so maybe it has changed, but these are the parameters I pass in the authorization request:
oauth_consumer_key
oauth_nonce
oauth_signature
oauth_signature_method
oauth_timestamp
oauth_version
It's here for anyone hunting around:
def create
#authorisation.oauth_token_secret = auth_hash.credentials.secret
end
def auth_hash
request.env['omniauth.auth']
end
Cheers.

oauth permission unknown issue in rspec for linkedin api

when I am call in spec, the get :authenticate_linkedin_login method of controller getting error the oauth:problem permission unknown.
*spec file.*
describe LinkedinProfileController do
include LinkedinStubs
before(:each) do
#temp = Factory(:worker)
controller.stub(:authenticate_user!)
controller.stub!(:current_user).and_return(#temp)
WebMock.allow_net_connect!(:net_http_connect_on_start => true)
end
describe "/login" do
it "should redirect to linkedin authorization url" do
stub_oauth_request_token!
get :linkedin_login
session[:rtoken].should == 't'
session[:rsecret].should == 's'
response.location.should =~ /www.linkedin.com/
response.should be_redirect #request authorize url
end
end
describe "/authenticate_linkedin_login" do
it "should be authorize_from_request" do
get :authenticate_linkedin_login,:oauth_verifier=>'12345'
*Controller*
class LinkedinProfileController < ApplicationController
before_filter :authenticate_worker!
def linkedin_login
client = LinkedIn::Client.new('lrkf3ol8f91k','OGJbzX3lKNSOxNwT')
request_token = client.request_token(:oauth_callback => "http://#{request.host_with_port}/authenticate_linkedin_login")
session[:rtoken] = request_token.token
session[:rsecret] = request_token.secret
redirect_to client.request_token.authorize_url
end
def authenticate_linkedin_login
client = LinkedIn::Client.new('lrkf3ol8f91k','OGJbzX3lKNSOxNwT')
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
else
client.authorize_from_access(session[:atoken], session[:asecret])
end

401 Unauthorized for foursquare OAuth

OK, I am pulling my hair after trying this out too many times to debug.
So please help me out here. I keep getting 401 Unauthorized error after I am redirected back.
Here is my code. What am I doing wrong here?
require 'rubygems'
require 'OAuth'
require 'json'
class SessionController < ApplicationController
before_filter :load_oauth
def index
if session[:request_token] && params[:oauth_token]
#request_token = OAuth::RequestToken.new(#consumer,
session[:request_token], session[:request_secret])
#access_token =
#request_token.get_access_token(:oauth_verifier =>
params[:oauth_verifier])
puts #access_token
#info = #access_token.get("http://api.foursquare.com/v1/
test")
flash[:notice] = "Foursquare! Yay!"
else
redirect_to(#foursqrurl)
end
end
private
def load_oauth
#oauth_key = 'key'
#oauth_secret = 'secret'
#consumer = OAuth::Consumer.new(#oauth_key,#oauth_secret,{
:site => "http://foursquare.com",
:scheme => :header,
:http_method => :post,
:request_token_path => "/oauth/request_token",
:access_token_path => "/oauth/access_token",
:authorize_path => "/oauth/authorize"
})
#request_token = #consumer.get_request_token(:oauth_callback =>
"http://localhost:3001/session")
session[:request_token] = #request_token.token
session[:request_secret] = #request_token.secret
puts #request_token.token
puts #request_token.secret
# redirecting user to foursquare to authorize
#foursqrurl = #request_token.authorize_url
puts #foursqrurl
end
end
I know absolutely nothing about Oauth and this may be completely wrong, but, if http://foursquare.com is not your local machine and oauth_callback is a URL that http://foursquare.com will call when it has completed then it will be calling back to itself as its definition of localhost will be its own 127.0.0.1 i.e itself.
If I have guessed correctly here then change the :oauth_callback to your public IP Address/name.
I think #request_token = OAuth::RequestToken.new(#consumer,
session[:request_token], session[:request_secret]) is wrong.
If you already have the token and the secret, you don't really need to do the verifier thing.
You should construct it like this:
OAuth::RequestToken.from_hash(consumer, { :oauth_token => params[:oauth_token] })
access_token = request_token.get_access_token(:oauth_verifier => params[:oauth_verifier])
Or if you already have the token and the secret, you should do:
access_token = OAuth::AccessToken.from_hash(consumer, {
:oauth_token => "YOUR_TOKEN",
:oauth_token_secret => "YOUR_SECRET"
})

Resources