Undefined Method "authentication" for #<Napster::Client:0x0000559185ef3cf8> - ruby-on-rails

Not used to asking questions On stack, Apologies if the format makes it hard to respond.
Anyway, I'm trying to develop an app using Ruby on Rails with the Napster API. I am currently stuck on setting up the client object that will allow me to make meta data calls.
I am setting up the client in config/initializers as napster.rb. Here is my code
require 'napster'
client_hash = {
api_key: ENV["NAPSTER_API_KEY"],
api_secret: ENV["NAPSTER_API_SECRET"],
username: ENV["NAPSTER_USER"],
password: ENV["NAPSTER_PW"]
}
client = Napster::Client.new(client_hash)
client.access_token
client.authentication.access_token # => returns access_token
client.authentication.refresh_token
client.authentication.expires_in
Now whenever I try to run rails c in the console I get this error
config/initializers/napster.rb:14:in <main>: undefined method authentication' for #<Napster::Client:0x0000559185ef3cf8>
The ENV variables are stored in config/application.yml. I'm not sure what's going on, Here is the #<Napster::Client:0x0000559185ef3cf8>
#<Napster::Client:0x0000559185ef3cf8
#api_key=--Omitted--,
#api_secret=--Omitted--,
#username=--Omitted--, #password=--Omitted--,
#request=#<Napster::Request:0x0000559185ef3b40 #faraday=#
<Faraday::Connection:0x0000559185ef3a28 #parallel_manager=nil,
#headers={"Authorization"=>"Basic
Tm1KbVpHRXlOV0l0WVRJNFppMDBPVEkwTFdJM1l
6WXRPR1ExTTJSaE16WXpORE5tOllXWmlNek5oT0RFdE
5UaG1PUzAwWlRWakxXSXpNRFF0WVRJeU56bG1abUkzTmpJMA==", "User-
Agent"=>"Faraday v0.9.2"}, #params={}, #options=#
<Faraday::RequestOptions (empty)>, #ssl=#<Faraday::SSLOptions
verify=true>, #default_parallel_manager=nil, #builder=#
<Faraday::RackBuilder:0x0000559185ef3758 #handlers=
[Faraday::Request::UrlEncoded, Faraday::Adapter::NetHttp], #app=#
<Faraday::Request::UrlEncoded:0x0000559185efd050 #app=#
<Faraday::Adapter::NetHttp:0x0000559185efd0c8 #app=#
<Proc:0x0000559185efd1b8#/home/leo/.rbenv/versions/
2.4.4/lib/ruby/gems/2.4.0/gems/faraday-
0.9.2/lib/faraday/rack_builder.rb:152 (lambda)>>>>, #url_prefix=#
<URI::HTTPS https://api.napster.com/>, #proxy=nil>>,
#access_token=--Omitted--,
#refresh_token=--Omitted--,
#expires_in=86399>
I omitted the api and access token stuff for obvious security reasons. Any thoughtful input is appreciated, thanks.

Related

Action Mailbox saying "Missing required Mailgun API key" even though key is present

I have Mailgun set up to forward emails to my /rails/action_mailbox/mailgun/inbound_emails/mime endpoint.
When my endpoint receives the request, it gives the following error:
ArgumentError (Missing required Mailgun API key. Set
action_mailbox.mailgun_api_key in your application's encrypted
credentials or provide the MAILGUN_INGRESS_API_KEY environment
variable.)
However, MAILGUN_INGRESS_API_KEY is in fact set. When I run ENV["MAILGUN_INGRESS_API_KEY"] in the console, I see my API key. I even pasted in the API key determination code from GitHub to see if there was a problem there, but the return value I got was my actual API key.
Any ideas on what the problem could be?
Just checking few things to see if can rectify, as I understand you know much better than me about rails.
Do you have setup mailgun api_key in environment configuration like for development config/environments/development.rb
config.action_mailer.delivery_method = :mailgun
config.action_mailer.mailgun_settings = {
api_key: ENV['MAILGUN_INGRESS_API_KEY'],
domain: 'your_domain.com',
# api_host: 'api.eu.mailgun.net' # Uncomment this line for EU region domains
}
Now let us do one test, visit (bin.mailgun.net) and get paste bin url then run rails c
mg_client = Mailgun::Client.new(ENV["MAILGUN_INGRESS_API_KEY"], "bin.mailgun.net", "aecf68de_you_got_visiting_site", ssl = false)
message_params = { from: 'bob#sending_domain.com',
to: 'sally#example.com',
subject: 'The Ruby SDK is awesome!',
text: 'It is really easy to send a message!'
}
result = mg_client.send_message("your_sending_setup_on_mailgun_domain.com", message_params)
puts result.inspect
See what message came and you may get idea. There could be environment configuration issue also for development you have to setup different then for production. Also check on paste-bin does it got any hit.

Configuring Ruby On Rails Application With Iex-Ruby-Client Gem

I am a beginner programmer. I recently built an application that uses the iex-ruby-client gem to pull stock quotes for me that I enter into a webpage form. It worked perfectly.
However, in early June, IEX changed their API so that you have to have a publishable token from the IEX cloud console. I got my publishable token from IEX cloud console.
The updated gem docs (https://github.com/dblock/iex-ruby-client) say that I have to "Configure" the application now. I simply don't know how or where I would implement the configuration code. Here is the suggested code from the gem documentation. I just don't know where to put it.
Configure IEX::Api.configure do |config|
config.publishable_token = 'token' # defaults to
ENV['IEX_API_PUBLISHABLE_TOKEN']
config.endpoint = 'https://sandbox.iexapis.com/v1' # defaults to
'https://cloud.iexapis.com/v1'
end
The documents also state, "You can also configure an instance of a client directly."
client = IEX::Api::Client.new(
publishable_token: 'token',
endpoint: 'https://sandbox.iexapis.com/v1'
)
I am adding extra code to clarify what I have done based on the response here. Here is my new config/initializers/iex-ruby-client.rb file (token info isn't the real one).
IEX::Api.configure do |config|
config.publishable_token = 'pk_3b38fsdadfsafjsdalfjdsakfjlda12f519'
config.endpoint = 'https://sandbox.iexapis.com/v1'
end
Here is the relevant method in the controller where I require the library:
def index
require 'iex-ruby-client'
if params[:id] == ""
#nothing = "You forgot to enter a symbol ;)."
elsif
if params[:id]
begin
#stock = IEX::Resources::Quote.get(params[:id])
#company = IEX::Resources::Company.get(params[:id])
rescue StandardError
#error = "That stock symbol doesn't seem to exist. Please enter
another symbol."
end
end
end
end
So I have created the config file and required the gem at the top of the method, but I am still getting an error. I'm sure there is some flaw in my implementation of this token requirement. If you have any additional suggestions, I welcome them. But if this is too much to ask on Stack Overflow, I understand. Thanks.
Well, you clearly have two choices:
use initializer by creating a config file(i.e: iex_client.rb) under the directory /config/initializers and add:
Configure IEX::Api.configure do |config|
config.publishable_token = 'token' # defaults to
ENV['IEX_API_PUBLISHABLE_TOKEN']
config.endpoint = 'https://sandbox.iexapis.com/v1' # defaults to
'https://cloud.iexapis.com/v1'
end
just use the client object wherever you want like this:
client = IEX::Api::Client.new(
publishable_token: 'token',
endpoint: 'https://sandbox.iexapis.com/v1'
)
You probably need to replace token with a correct one. You also need to make sure to require the library wherever you wanna use it.
After unsuccessfully attempting to configure the IEX-ruby-client gem (as described in my question here on stack overflow), I switched over to the stock_quote gem. That gem is built off of the same IEX API, and I had no problems configuring the app with a stock_quote.rb file saved inside config/initializers.

How to use Rails Low Level Cache in production?

I have an application which calls an API and authenticates using a token. I need to store this token and refresh it every so often, so I am using Rails.cache.fetch to do so in a custom class for handling the API calls. This works great on my local dev machine, but in production it is erroring. I am running a Mac for my dev machine and production is on Ubuntu 18. Here is the code that raises the error:
def authenticate
Rails.cache.fetch(#token, expires_in: 2.hours.to_i) do
login_uri = #base_uri + "auth/login"
auth_response = HTTParty.post(login_uri, body: { username: ENV["API_USERNAME"], password: ENV["API_PASSWORD"] } )
#token = auth_response.parsed_response["token"]
end
end
Here is the error I am getting:
Errno::ENOTDIR (Not a directory # rb_file_s_rename -
(/var/www/myapp/releases/20190424134348/tmp/cache/.00020190424-1954-lgpvq5,
/var/www/myapp/releases/20190424134348/tmp/cache/001/000/)):
It looks like Rails is attempting to rename or move the cache file for some reason. Looking at the server the /001 directory is there, but the subdirectory /000 does not exist.

Retrieving Youtube comments with fullscreen/yt

I'm using https://github.com/Fullscreen/yt to interact with Youtube API, but after a couple of hours of testing I'm unable to fetch comments from a video.
I suspect the reason is I'm requesting the wrong permissions, but I can't find anything clear in Google docs about what scope to ask. I appears from the OAuth playground it's https://www.googleapis.com/auth/youtube.force-ssl
but still, I'm not able to make it work.
This is the omniauth provider line to request a new token:
provider :google_oauth2, key, secret, {:scope => 'http://gdata.youtube.com,email,profile,youtube,youtube.force-ssl'}
And this is how I try to retrieve the comments:
Yt.configure do |config|
config.client_id = key
config.client_secret = secret
end
youtube_client = Yt::Account.new access_token: 'yadayada'
video = Yt::Video.new id: 'foobar', auth: youtube_client
puts video.comments
What I get is:
Yt::Errors::Forbidden: A request to YouTube API was considered forbidden by the server:
{"error"=>{"errors"=>[{"domain"=>"global", "reason"=>"insufficientPermissions", "message"=>"Insufficient Permission"}], "code"=>403, "message"=>"Insufficient Permission"}}
I've tried pretty much the same on channels too, same problem, that's why I guessed there's something wrong with my access_token.
Has someone done this? What am I doing wrong? Any example?
As per the documentation on the page you have shared the link of, I am not able to see this line of code:
account = Yt::Account.new authorization_code: '4/Ja60jJ7_Kw0', redirect_uri: redirect_uri
Every user who authorizes your app will be redirected to the redirect_uri with an extra code parameter that looks something like 4/Ja60jJ7_Kw0. Just pass the code to the following method to authenticate and initialize the account:
If this does not workout try Configuring with environment variables
As an alternative to the approach above, you can configure your app with variables. Setting the following environment variables:
export YT_CLIENT_ID="1234567890.apps.googleusercontent.com"
export YT_CLIENT_SECRET="1234567890"
export YT_API_KEY="123456789012345678901234567890"
is equivalent to configuring your app with the initializer:
Yt.configure do |config|
config.client_id = '1234567890.apps.googleusercontent.com'
config.client_secret = '1234567890'
config.api_key = '123456789012345678901234567890'
end
so use the approach that you prefer. If a variable is set in both places, then Yt.configure takes precedence.
Hope this Helps!!

Paypal-express gem, working in dev but not in prod

So I have an issue I can't figure out alone.
I have run some test on my app and when launch in dev it's working perfectly but as soon as it's on Prod and so it uses the real identificator, it doesn't work anymore.
I got this error:
Paypal::Exception::APIError (PayPal API Error: 'Security error'):
/offers_controller.rb:218:in choose_step'
if Rails.env.production?
response = request.setup(
payment_request,
"http://www.workiz.com/recruteurs/paypal_callback/" + params[:app_id],
"http://www.workiz.com/recruteurs/offres",
paypal_options # Optional
)
else # Development ou Test
response = request.setup(
payment_request,
"http://localhost:3000/recruteurs/paypal_callback/" + params[:app_id],
"http://localhost:3000/recruteurs/offres",
paypal_options # Optional
)
end
That is the line that crash, so it's when I call request.setup
The request is created like that:
if Rails.env.development?
Paypal.sandbox!
Paypal::Express::Request.new(
username: ENV['PAYPAL_SANDBOX_USERNAME'],
password: ENV['PAYPAL_SANDBOX_CLI_ID'],
signature: ENV['PAYPAL_SANDBOX_SECRET']
)
elsif Rails.env.production?
Rails.logger.info "Paypal SETUP PRODUCTION"
Paypal::Express::Request.new(
username: ENV['PAYPAL_USERNAME'],
password: ENV['PAYPAL_CLI_ID'],
signature: ENV['PAYPAL_SECRET']
)
end
And yes the logger "Paypal SETUP PRODUCTION" appear and the value set are the good one from the ENV variables.
I had to put Paypal.sandbox! in the config/development.rb to make it work for the sandbox but I cannot find a way to make it work for the production...
Any help is welcome. Thank you very much.
I have display the error, it look like that:
ERROR IS: #<Paypal::Exception::APIError::Response:0x007fa61661e040
#raw={
:TIMESTAMP=>"2015-05-24T15:01:30Z",
:CORRELATIONID=>"f3067f049ad",
:ACK=>"Failure",
:VERSION=>"88.0",
:BUILD=>"1675131",
:L_ERRORCODE0=>"10002",
:L_SHORTMESSAGE0=>"Security error",
:L_LONGMESSAGE0=>"Security header is not valid",
:L_SEVERITYCODE0=>"Error"},
#ack="Failure", #build="16751317", #correlation_id="f3067f049a", #timestamp="2015-05-24T15:01:30Z", #version="88.0", #order_time=nil, #pending_reason=nil, #payment_status=nil, #payment_type=nil, #reason_code=nil, #transaction_type=nil,
#error_code="10002",
#severity_code="Error",
#long_message="Security header is not valid",
#short_message="Security error"
Have a detailed look at the exception you're getting.
According to https://github.com/nov/paypal-express/blob/master/lib/paypal/exception/api_error.rb the error should have more useful information from the API response.
Simply catch the exception, and print it's contents:
begin
response = request.setup...
rescue Paypal::Exception::APIError => error
puts error.inspect
raise error
end
You're probably missing some configuration in your PayPal account. The detailed error message and error code should point you in the right direction.
Ok I have finally found my mistake.
It appear, you shouldn't use the CLI ID, PWD and SIGNATURE from the "live page" on your application.
But instead:
Log in to PayPal.com
You must have a PayPal Business account to make calls to the live PayPal servers. Log in to your Business account on the following page: https://www.paypal.com.
Navigate to the API Access page
Click the Tools tab and navigate to Manage your business > API Access.
Here you go, those are the good one...
Very confusing !
Hope it helps
First, double check that the 2 sets of credentials are different. You need a different account for sandbox than production.
PAYPAL_SANDBOX_USERNAME != PAYPAL_USERNAME
PAYPAL_SANDBOX_CLI_ID != PAYPAL_CLI_ID
PAYPAL_SANDBOX_SECRET != PAYPAL_SECRET
Second, double check that the production credentials are correct, i.e. no extra characters or typos.

Resources