oauth permission unknown issue in rspec for linkedin api - oauth

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

Related

How can I parse a json response.body to store a key's value in ruby on rails?

I am receiving a json response (response.body) from the api call I am making with my model and in my controller I would like to parse it to store its id key's value in my session[:user_id].
I've tried to implement it in the following way
parsed_body = JSON.parse(User.new.get_credentials, :symbolize_names => true)
puts "The parsed_body is: #{parsed_body}"
session[:user_id] = parsed_body[0][:id]
puts "The session id is: #{session[:user_id]} "
The response.body is:
{"result":[{"id":"3","username":"Sam","password":"111"},{"id":"4","username":"Harshal","password":"1234"},{"id":"5","username":"Dev","password":"112"},{"id":"6","username":"Lam","password":"113"},{"id":"7","username":"Tim","password":"114"},{"id":"8","username":"Harry","password":"222"}]}
The parsed_body is:
{:result=>[{:id=>"3", :username=>"Sam", :password=>"111"}, {:id=>"4", :username=>"Harshal", :password=>"1234"}, {:id=>"5", :username=>"Dev", :password=>"112"}, {:id=>"6", :username=>"Lam", :password=>"113"}, {:id=>"7", :username=>"Tim", :password=>"114"}, {:id=>"8", :username=>"Harry", :password=>"222"}]}
Here is my code for users controller, user model and sessions controller:
Users Controller
class UsersController < ApplicationController
def create
#users = User.new(token: user_params).credentials
parsed_body = JSON.parse(User.new.get_credentials, :symbolize_names => true)
puts "The parsed_body is: #{parsed_body}"
session[:user_id] = parsed_body[0][:id]
puts "The session id is: #{session[:user_id]} "
redirect_to '/dashboard'
end
private
def user_params
params.require(:user).permit(:id, :username, :password).to_hash
end
end
User Model
class User
def initialize(attributes={})
#token ||= attributes[:token]
end
def credentials
my_connection = Net::HTTP.new('localhost', 8080)
request = my_connection.post('/restapitrial/index.php/Users/insert/', #token.to_json, "Content-Type" => "application/json")
end
def get_credentials
my_connection = Net::HTTP.new('localhost', 8080)
request = my_connection.get('/restapitrial/index.php/Users/displayinfo/', "Content-Type" => "application/json")
puts "The req body is #{request.body}"
return request.body
end
end
Sessions Controller
class SessionsController < ApplicationController
def create
user = User.find_by(id: login_params[:id])
if user && user.authenticate(login_params[:password])
session[:user_id] = user.id
redirect_to '/dashboard'
else
flash[:login_errors] = ['invalid credentials']
redirect_to '/'
end
end
private
def login_params
params.require(:login).permit(:id, :username, :password)
end
end
If you want to get the last id in the array that is returned then use the
parsed_body[:result][-1][:id]

Twilio sending error The requested resource /2010-04-01/Accounts//Messages.json was not found

going through this course to build ROR app and sending a twilio message to verify persons mobile number. I get the error" The requested resource /2010-04-01/Accounts//Messages.json was not found" found a previous question request however they did not have much code to review and he mentioned that he finally has it working mentioned he had a null variable of $sid and token; not sure what to verify. I tried both test and production sid and token #s from my acct. Thanks so much for your attention.
initailizer/twilio.rb
Twilio.configure do |config|
config.account_sid = ENV['TWILIO_ACCOUNT_SID']
config.auth_token = ENV['TWILIO_AUTH_TOKEN']
end
models/user.rb
def generate_pin
self.pin = SecureRandom.hex(2)
self.phone_verified = false
save
end
def send_pin
#client = Twilio::REST::Client.new
#client.messages.create(
from: '+15812345678',
to: self.phone_number,
body: "Your pin is #{self.pin}"
)
end
def verify_pin(entered_pin)
update(phone_verified: true) if self.pin == entered_pin
end
Application.yml
TWILIO_ACCOUNT_SID: '12345678901234567'
TWILIO_AUTH_TOKEN: '123434567890123456'
TWILIO_NUMBER: '+15878551234'
users controller
def update_phone_number
current_user.update_attributes(user_params)
current_user.generate_pin
current_user.send_pin
redirect_to edit_user_registration_path, notice: "Saved!"
rescue Exception => e
redirect_to edit_user_registration_path, alert: "#{e.message}"
end
def verify_phone_number
current_user.verify_pin(params[:user][:pin])
if current_user.phone_verified
flash[:notice] = "FYi Your phone number is verified"
else
flash[:alert] = "Cannot verify your phone number"
end
redirect_to edit_user_registration_path
rescue Exception => e
redirect_to edit_user_registration_path, alert: "#{e.message}"
end
private
def user_params
params.require(:user).permit(:phone_number, :pin)
end
I'm not sure but could you try this
def send_pin
account_sid = 'your-account-sid'
auth_token = 'your-auth-token'
#client = Twilio::REST::Client.new account_sid, auth_token
#client.messages.create({
from: '+15812345678',
to: self.phone_number,
body: "Your pin is #{self.pin}"
})
end

undefined method `get_access_token'

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.

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.

Rescuing from Twitter Gem

I have a tweets_controller
#called when user submits twitter form
def message
unless current_user
session[:twitter_message] = params[:twitter_message] #sets the message from the form so it's available for send_tweet in tweet.rb after we pass through omniauth
redirect_to '/auth/twitter' #redirects to authorize via omniauth/twitter and create the user
else
#auth = Authorization.find_by_user_id(current_user)
Tweet.update_status(#auth, params[:twitter_message])
redirect_to edit_user_path(current_user), :notice => "Tweet sent."
end
end
I'm trying to rescue when the status update fails. I want to display a flash message to the user, but -- this is as far as I can seem to get:
def self.update_status(auth, msg)
#token = auth.token
#secret = auth.secret
#message = msg
#t = Twitter::Client.new
Twitter.configure do |config|
config.consumer_key = '[key]'
config.consumer_secret = '[secret]'
config.oauth_token = #token
config.oauth_token_secret = #secret
config.gateway = '[gateway_url]'
end
ret = #t.update(#message)
tweet ||= Tweet.create_from_response(ret, auth.id)
rescue Twitter::Error => e
logger.error "#{e.message}."
end
How do I get the error message so I can display it to my user through the controller?
You can create and throw a custom exception based on the application.
In app/lib/could_not_update_status_error.rb
class CouldNotUpdateStatusError < StandardError
end
Then in your model:
rescue Twitter::Error => e
logger.error "#{e.message}."
raise CouldNotUpdateStatusError.new("Could not update status")
And in your controller
else
begin
#auth = Authorization.find_by_user_id(current_user)
Tweet.update_status(#auth, params[:twitter_message])
redirect_to edit_user_path(current_user), notice: "Tweet sent."
rescue CoundNotUpdateStatusError => e
# Do error stuff
end
Another option would be to do rescue return false in your Twitter::Error clause and wrap the update_status call in an if statement, however Exceptions are a more robust solution.

Resources