Every time the user post a comments, I want it to send the same comment to my Twitter automatically.
First of all, I have it already done with Twitter developer settings.
So I made a test action in my App to make it send a tweet to my Twitter account.
However, it says this error
NoMethodError (undefined method `[]' for nil:NilClass):
app/controllers/top_controller.rb:173:in `test_action'
How can I solve this? These are my codes
gems related that are already bundled (I'm on rails 3.2.11)
gem 'omniauth-twitter'
gem 'twitter'
gem 'figaro'
config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :twitter, ENV['TWITTER_KEY'], ENV['TWITTER_SECRET']
Twitter.configure do |config|
config.consumer_key = ENV["TWITTER_KEY"]
config.consumer_secret = ENV["TWITTER_SECRET"]
end
end
config/application.yml
TWITTER_KEY: 6TeBX6HkeHzMXesgc
TWITTER_SECRET: JyfOndg8xHcM81KEpgmBT7h2vFJJujMP14YTdt6ruvLbsQk
test_action
def test_action
#twitter = Twitter::Client.new(oauth_token: request.env["omniauth.auth"][:credentials][:token], oauth_token_secret: request.env["omniauth.auth"][:credentials][:secret])
#twitter.update("Your message")
flash[:notice] = "Successfully tweeted on your account."
redirect_to root_path
return
end
I think your issue may be with your controller configuration of Twitter:
instead of:
#twitter = Twitter::Client.new(oauth_token: request.env["omniauth.auth"][:credentials][:token], oauth_token_secret: request.env["omniauth.auth"][:credentials][:secret])
try this:
#twitter = Twitter::REST::Client.new do |config|
config.consumer_key = ENV['CONSUMER_KEY']
config.consumer_secret = ENV['CONSUMER_SECRET']
config.access_token = request.env["omniauth.auth"][:credentials][:token]
config.access_token_secret = request.env["omniauth.auth"][:credentials][:secret]
end
You also might want to confirm that your API keys have read and write permissions, which you can check on your Twitter developer account here.
Related
I have this recaptcha error We detected that your site is not verifying reCAPTCHA solutions. This is required for the proper use of reCAPTCHA on your site. Please see our developer site for more information.
I did everything exactly but its still there recaptcha checkbox return false even after I checked the button
Here is my codes:
In gemfile
gem "recaptcha", require: "recaptcha/rails"
in config in in initializer in recaptcha.rb
Recaptcha.configure do |config|
config.site_key = 'my site key'
config.secret_key = 'my secret key'
end
In view:
<%= recaptcha_tags %>
In controller:
def create
#contact = Contact.new(contact_attributes)
if verify_recaptcha(model: #contact) && #contact.save
ContactMailer.message_send(#contact).deliver
redirect_to contacts_path, notice: "Thank you... Your Message was sent successfully."
else
flash.now[:error] = "Please correct the form"
render :index
end
end
I even try this in recaptcha.rb
Recaptcha.configure do |config|
config.public_key = ENV["RECAPTCHA_PUBLIC_KEY"]
config.private_key = ENV["RECAPTCHA_PRIVATE_KEY"]
end
but I got this error
undefined method `public_key=' for #<Recaptcha::Configuration:0x00007fc132b363e8> (NoMethodError)
Did you mean? public_send
In this link https://www.google.com/recaptcha/api/siteverify
I have
{
"success": false,
"error-codes": [
"missing-input-response",
"missing-input-secret"
]
}
Not sure what to do please help me and thanks in advance
Where did you put <%= recaptcha_tags %>?
As per: https://github.com/ambethia/recaptcha/blob/master/lib/recaptcha/configuration.rb
You can:
Recaptcha.configure do |config|
config.site_key = 'my site key'
config.secret_key = 'my secret key'
end
other wise the gem will automatically pick it from ENV['RECAPTCHA_SECRET_KEY'] and ENV['RECAPTCHA_SITE_KEY'].
This won't work:
Recaptcha.configure do |config|
config.public_key = ENV["RECAPTCHA_PUBLIC_KEY"]
config.private_key = ENV["RECAPTCHA_PRIVATE_KEY"]
end
My doubts now goes towards that you place recaptcha_tags in a wrong place (maybe out of the form). that it does not get sent to the controller/backend.
I'm using the Twitter Gem and Figaro but my credentials aren't being stored. Here's my setup:
config/initializers/twitter.rb
client = Twitter::REST::Client.new do |config|
config.consumer_key = ENV["TWITTER_CONSUMER_KEY"]
config.consumer_secret = ENV["TWITTER_CONSUMER_SECRET"]
config.access_token = ENV["TWITTER_ACCESS_TOKEN"]
config.access_token_secret = ENV["TWITTER_ACCESS_SECRET"]
end
config/application.yml:
TWITTER_CONSUMER_KEY: "12345"
TWITTER_CONSUMER_SECRET: "12345"
TWITTER_ACCESS_TOKEN: "12345"
TWITTER_ACCESS_SECRET: "12345"
Placing the below in a View results in a "Unable to verify your credentials" error which I believe is caused by the initializer not correctly storing my credentials.
<%=
#client = Twitter::REST::Client.new
#client.user_timeline("cnn") %>
I've tried putting various items in a Controller but nothings works. Via console:
client = Twitter::REST::Client.new
=> #<Twitter::REST::Client:0x007fadf06364b0>
client.consumer_key
=> nil
Any help would be much appreciated, thanks
client = Twitter::REST::Client.new is creating a new object with no params; it is not reusing what has been configured in config/initializers/twitter.rb
Try putting the initialization code & the accessing code in the controller together as follows:
#client = Twitter::REST::Client.new do |config|
config.consumer_key = ENV["TWITTER_CONSUMER_KEY"]
config.consumer_secret = ENV["TWITTER_CONSUMER_SECRET"]
config.access_token = ENV["TWITTER_ACCESS_TOKEN"]
config.access_token_secret = ENV["TWITTER_ACCESS_SECRET"]
end
#client.user_timeline("cnn")
I've set up Devise and Omniauth for users to sign in via email, twitter, and facebook. I'm not trying to allow users to tweet a message from inside the app.
I’ve got it currently working with the following code but it’s only posting from MY twitter account. I’m assuming this has to do with not setting up the Oauth_token correctly. No matter what account logins into the app, it still comes from my account.
In my User model, I have the following code (I’ve changed my key and tokens)…
def self.find_for_twitter_oauth(auth, signed_in_resource=nil)
user = User.where(:provider => auth.provider, :uid => auth.uid).first
if user
return user
else
registered_user = User.where(:email => auth.uid + "#twitter.com").first
if registered_user
return registered_user
else
user = User.create(full_name:auth.extra.raw_info.name,
provider:auth.provider,
uid:auth.uid,
email:auth.uid+"#twitter.com",
oauth_token:auth.credentials.token,
oauth_secret:auth.credentials.secret,
password:Devise.friendly_token[0,20],
)
end
end
end
def tweet(tweet)
client = Twitter::REST::Client.new do |config|
config.consumer_key = "XXXXXXXX"
config.consumer_secret = "XXXXXXX"
config.access_token = "XXXXXXX-XXXXX"
config.access_token_secret = "XXXXXXX"
end
client.update(tweet)
end
In my config/initializer/devise.rb I have the following:
# Add Twitter OmniAuth
require 'omniauth-twitter'
config.omniauth :twitter, ENV['TWITTER_CONSUMER_KEY'], ENV['TWITTER_CONSUMER_SECRET']
# Add Facebook OmniAuth
require 'omniauth-facebook'
config.omniauth :facebook, ENV['FACEBOOK_APP_ID'], ENV['FACEBOOK_APP_SECRET'], :scope => 'basic_info, email, publish_stream'
In my view, I'm using a form for them to fill out and submit the tweet.
<p>
<%= form_for :tweet, url: tweets_path, method: :post do |f| %>
<%= f.text_field :message %>
<%= f.submit "Send Tweet" %>
<% end %>
</p>
You should authorize each twitter user with your app (as I remember with consumer key and consumer secret only).
I did this with simple way:
consumer = OAuth::Consumer.new($TWITTER_CONSUMER_KEY, $TWITTER_CONSUMER_SECRET, :site => "https://api.twitter.com")
request_token = consumer.get_request_token(:oauth_callback => "http://localhost/twitter/auth_callback")
return request_token.authorize_url
by URL I have
access_token = request_token.get_access_token(:oauth_verifier => params[:oauth_verifier] )
token = access_token.token
secret = access_token.secret
Now if you set these toekn and secret in to your REST client you can post tweets from your user account.
I'm developing a mountable engine (called SimpleUser) which uses Devise, OmniAuth and OmniAuth-Facebook. First I made a test app with the gems about and every worked fine. Next, I started building the engine from scratch, using the code of the test app as an example.
Everything is almost done, except for the connection with Facebook (it uses the Javascript popup). When I click in "log in" the FB popup is displayed, I grant the app, it redirects to the route specified (see routes), but throws this error:
NoMethodError in SimpleUser::AuthController#create
undefined method `[]' for nil:NilClass
The error occurs in that action, in the line authentication = Authentication.find_by_provider_and_uid(auth['provider'], auth['uid']) where auth is nil (auth comes from auth = request.env["omniauth.auth"]).
One thing I check is that the Callback phase it's no initialised. This is the log of the test app:
Started GET "/auth/facebook/callback" for 127.0.0.1 at 2013-03-14
08:52:56 -0600 (facebook) Callback phase initiated. Processing by
AuthController#create as HTML Parameters: {"provider"=>"facebook"}
This is the log of the engine app:
Started GET "/simple_user/auth/facebook/callback" for 127.0.0.1 at 2013-03-14 08:51:19 -0600
Processing by SimpleUser::AuthController#create as HTML
Parameters: {"provider"=>"facebook"}
For manage OmniAuth, I added the gem to the .gemspec and to the Gemfile; also, I require the gems in the engine, and within a generator of the engine I move a template of omniauth.rb to config/initializers of the parent app during installation. This is what I have:
AuthController (located in app/controllers/simple_user/auth_controller.rb)
module SimpleUser
class AuthController < ApplicationController
def create
auth = request.env["omniauth.auth"]
authentication = Authentication.find_by_provider_and_uid(auth['provider'], auth['uid'])
if authentication
flash[:notice] = "Signed in successfully."
sign_in(:user, authentication.user)
redirect_to root_url
else
user = User.build_new_auth(auth)
#user.apply_omniauth(auth)
if user.save(:validate => false)
flash[:notice] = "Account created and signed in successfully."
sign_in(:user, user)
redirect_to root_url
else
flash[:error] = "Error while creating the user account. Please try again."
redirect_to root_url
end
end
end
end
end
Engine
module SimpleUser
require 'rubygems'
require 'devise'
require 'cancan'
require 'rolify'
require 'omniauth'
require 'omniauth-facebook'
require 'simple_form'
class Engine < ::Rails::Engine
isolate_namespace SimpleUser
config.before_configuration do
env_file = File.join(Rails.root, 'config', 'fb_config.yml')
YAML.load(File.open(env_file)).each do |key, value|
ENV[key.to_s] = value.to_s
end if File.exists?(env_file)
env_file = File.join(Rails.root, 'config', 'devise_config.yml')
YAML.load(File.open(env_file)).each do |key, value|
ENV[key.to_s] = value.to_s
end if File.exists?(env_file)
end
end
end
Generator
module SimpleUser
module Generators
class InstallGenerator < ::Rails::Generators::Base
source_root File.expand_path("../templates", __FILE__)
desc "Install SimpleUser"
def copy_config_file
copy_file "fb_config.yml", "config/fb_config.yml"
copy_file "devise_config.yml", "config/devise_config.yml"
copy_file "omniauth.rb", "config/initializers/omniauth.rb"
end
def copy_migrations
rake "simple_user:install:migrations"
SimpleUser::Engine.load_seed
end
end
end
end
Template of the omniauth.rb
require 'omniauth'
require 'omniauth-facebook'
OmniAuth.config.logger = Rails.logger
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'], :scope => ENV['FACEBOOK_SCOPE']
end
Routes (on engine)
match 'auth/:provider/callback', to: 'auth#create'
match 'auth/failure', to: redirect('/')
Routes (on dummy app)
mount SimpleUser::Engine => "/simple_user", :as => "simple_user"
.gemspec dependencies
s.add_dependency "rails", "~> 3.2.12"
s.add_dependency "devise"
s.add_dependency "cancan"
s.add_dependency "rolify"
s.add_dependency "omniauth"
s.add_dependency "omniauth-facebook", "1.4.1"
s.add_dependency "simple_form"
#s.add_development_dependency "mysql2"
s.add_development_dependency "sqlite3"
s.add_development_dependency "jquery-rails"
s.add_development_dependency "debugger"
Gemfile
source "http://rubygems.org"
gemspec
gem 'devise'
gem 'cancan'
gem 'rolify'
gem 'omniauth'
gem 'omniauth-facebook', '1.4.1'
gem 'simple_form'
# Development
gem 'jquery-rails'
gem 'debugger'
I think the problem is the callback that is not initialised, and the reason may be that OmniAuth doesn't get loaded, but I don't know if it is and how to solve it.
You can check the project in https://github.com/pablomarti/simple_user, and if you want to clone it and test you can use the generator rails g simple_user:install, and you can see the code of test/dummy also to get the idea.
Thank you very much in advance.
The solution was to remove the omniauth.rb and include the middleware of OmniAuth in the engine, so the engine looks like this:
module SimpleUser
require 'rubygems'
require 'devise'
require 'cancan'
require 'rolify'
require 'omniauth'
require 'omniauth-facebook'
require 'simple_form'
class Engine < ::Rails::Engine
isolate_namespace SimpleUser
middleware.use OmniAuth::Builder do
provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'], :scope => ENV['FACEBOOK_SCOPE']
end
config.before_configuration do
env_file = File.join(Rails.root, 'config', 'fb_config.yml')
YAML.load(File.open(env_file)).each do |key, value|
ENV[key.to_s] = value.to_s
end if File.exists?(env_file)
env_file = File.join(Rails.root, 'config', 'devise_config.yml')
YAML.load(File.open(env_file)).each do |key, value|
ENV[key.to_s] = value.to_s
end if File.exists?(env_file)
end
end
end
Thanks to Dmitry Lihachev for his answer https://stackoverflow.com/a/8413724/347501 in a similar problem.
I have installed omniauth 1.0. Also I have oauth-0.4.5, oauth2-0.5.1, omniauth-facebook-1.0.0, omniauth-twitter-0.0.6.
omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :developer unless Rails.env.production?
provider :facebook, ENV['167257285348131'], ENV['c8c722f697scb2afcf1600286c6212a9'], :scope => 'email,offline_access,read_stream', :display => 'popup'
provider :twitter, ENV['fma2L22ObJCW52QrL7uew'], ENV['4aZfhCAOdiS7ap8pHJ7I1OZslFwVWWLiAMVpYUI']
end
session_controller.rb
class SessionsController < ApplicationController
require 'omniauth-facebook'
require 'omniauth-twitter'
require 'omniauth'
def create
#user = User.find_or_create_from_auth_hash(auth_hash)
self.current_user = #user
redirect_to '/'
end
def auth_hash
request.env['omniauth.auth']
end
end
Also I add
'omniauth'
'omniauth-facebook'
'omniauth-twitter' gems to gemfile
There are two problems:
When I go http://localhost:3000/auth/facebook I get
{
"error": {
"message": "Missing client_id parameter.",
"type": "OAuthException"
}
}
And the link graph.facebook.com/oauth/authorize?response_type=code&client_id=&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Ffacebook%2Fcallback&parse=query&scope=email%2Coffline_access%2Cread_stream&display=popup
And there is no client_id!!!
When I go to http://localhost:3000/auth/twitter I get OAuth::Unauthorized
401 Unauthorized
Any ideas?
Alex D. is correct in that the ENV[] breaks it. To create omniauth.rb so that it uses different keys in different environments just put:
provider :twitter, TWITTER_KEY, TWITTER_SECRET
in omniauth.rb
and then in your environment config files (config/environments/development.rb, etc.) put the key you want to use for that environment.
config/environments/development.rb:
TWITTER_KEY = 'aaaaaaa'
TWITTER_SECRET = 'aaaabbbbbb'
config/environments/production.rb:
TWITTER_KEY = 'ccccccc'
TWITTER_SECRET = 'ccccdddddd'
ENV['something']
looks into your environment vars for "something", so it would expect
something='12345'
so you should do it like that
export AUTH_FB_KEY='....'
export AUTH_FB_SECRET='...'
check with
env
and update your config
provider :facebook, ENV['AUTH_FB_KEY'], ENV['AUTH_FB_SECRET']
if you use heroku
heroku config:add AUTH_FB_KEY='....'
There have been breaking changes made in omniauth 1.0 - https://github.com/intridea/omniauth
OmniAuth 1.0 has several breaking changes from version 0.x. You can
set the dependency to ~> 0.3.2 if you do not wish to make the more
difficult upgrade. See the wiki for more information.
I would try reverting omniauth to 0.3.2:
gem install omniauth --version '~> 0.3.2'
or if you're using bundler, in your Gemfile:
gem omniauth, '~> 0.3.2'