OmniAuth Facebook added to Devise - ruby-on-rails

I'm using Rails 4.1 and already have devise configured but now would like to add sign up through Facebook and Twitter. Devise is fully set up and working for a user to sign up via email.
I've gone ahead and added the "omniauth-facebook" gem to my gemlist.
I've set up my api key and api secret
#config/initializers/devise.rb
config.omniauth :facebook, "API KEY", "API SECRET"
My Route file
#routes.rb
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks", :registrations => "registrations" }
My omniauth_callbacks_controller.rb
def facebook
#user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user)
if #user.persisted?
sign_in_and_redirect #user, :event => :authentication #this will throw if #user is not activated
set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
and my user model
def self.find_for_facebook_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.info.email).first
if registered_user
return registered_user
else
user = User.create(name:auth.extra.raw_info.name,
provider:auth.provider,
uid:auth.uid,
email:auth.info.email,
password:Devise.friendly_token[0,20],
)
end
end
end
I also added the link to the signup page but when i click on the button I'm getting the following error
{
error: {
message: "Invalid redirect_uri: Given URL is not allowed by the Application configuration.",
type: "OAuthException",
code: 191
}
}

It looks like Facebook is objecting to the url you've told it to redirect to after someone has logged in via Facebook. Check what you've specified in your Facebook app setup in "Manage Apps" -> Your App via your Facebook developer account. Check that one of your App Domains on the Settings->Basic tab matches the domain you want to redirect to after Facebook login. Also check that you're redirecting to a URL you've specified in "Valid OAuth redirect URIs" (if any) on the Settings -> Advanced tab.
My relevant config (with real domain name changed) is as follows:
On Settings -> Basic:
App Domains: mydomain.com
A web platform with URL: http://www.mydomain.com/
On Settings -> Advanced:
Client OAuth login: YES
App Secret Proof for Server API calls: YES (optional, but I like security and I don't think it'll exacerbate your problem - conversely, if you've got it as NO, then I don't think it'll matter if you leave it like that for the purposes of this problem)
Valid OAuth redirect URLs: https://www.mydomain.com/users/auth/facebook/callback https://staging.mydomain.com/users/auth/facebook/callback http://dev.mydomain.com:3000/users/auth/facebook/callback
So you can see I allow redirects to production, staging and dev environments. Your paths might vary depending on how you've set up your routes.
Then, I add an alias for the dev domain to my /etc/hosts file:
127.0.0.1 localhost dev.mydomain.com
so when Facebook tells my browser to redirect to dev.mydomain.com, it goes to the rails app on my machine.
If you specify the redirect urls, you should double-check that you're definitely supplying one of them to Facebook when you send the user there when they click on the button (I found devise/omniauth needed a bit of bludgeoning to get the paths as I wanted).

Related

Rails devise omniauth-facebook .persisted? returning false

I've spent the last day trying to fix this issue and it's driving me nuts.
Last night, I had facebook login working on my site and was retrieving basic user info. My problems started when I added :scope => 'user_birthday' to config/initializers/omniauth.rb which now looks like this
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, "APP_ID", "APP_SECRET", :scope => 'user_birthday'
end
For reference, I've removed the line config.omniauth :facebook, "APP_ID", "APP_SECRET" from config/initializers/devise.rb
I spent hours trying to get this to work but had to give up eventually. Then this morning I ran it again and it worked. Overjoyed, I tried to add another parameter to :scope but now the whole thing is broken again. I can get it to work if I remove the :scope but when I put it back in it fails every time (even if it's just :scope => 'user_birthday' like I had working first thing this morning).
To locate the problem, I put debug code in omniauth_callbacks_controller.rb and it now looks like:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
# You need to implement the method below in your model (e.g. app/models/user.rb)
#user = User.from_omniauth(request.env["omniauth.auth"])
puts "start before persist debug"
puts #user.birthday
puts #user.persisted?
puts "end before persist debug"
if #user.persisted?
puts "Start persisted debug"
puts request.env["omniauth.auth"]
puts "End debug"
sign_in_and_redirect #user, :event => :authentication #this will throw if #user is not activated
set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
puts "Start unpersisted debug"
puts request.env["omniauth.auth"]
puts "End debug"
redirect_to new_user_registration_url
end
end
end
This debug clearly shows that facebook is returning the necessary information but the app is failing because .persisted? is returning false and so I get re-directed to the new_user_registration page which returns the following:-
NoMethodError in Devise::Registrations#new
Showing /home/action/workspace/cloudapp/app/views/devise/shared/_links.html.erb where line #23 raised:
undefined method `omniauth_authorize_path' for #<#<Class:0x007f3aeffff038>:0x007f3aefffdf08>
I can't for the life of me figure out why .persisted? is returning false. I'm using Nitrous.io for development with a Heroku postgresql database. I've confirmed there are no users in the database by running
rails c
User.all
This returns:
User Load (89.4ms) SELECT "users".* FROM "users"
=> #<ActiveRecord::Relation []>
I have a feeling the problem is in models/user.rb but I can't figure out how to debug it to see if it's finding a user and therefore not persisting or trying to create one and failing. Does anyone know a simple way to debug this?
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
user.name = auth.info.name # assuming the user model has a name
user.birthday = auth.extra.raw_info.birthday
# user.image = auth.info.image # assuming the user model has an image
end
end
I've gone over everything about 50 times and am close to giving up.
The only thing I can think of is that where(provider: auth.provider, uid: auth.uid) is returning something (which it shouldn't because my database is empty). Would there possibly be an index that exists somewhere outside my database and that's what it's searching?
Please, for my sanity, can anyone help? If you need more info I'll gladly provide it
Edit 1
Just tried the following and it works which make me more confused than ever:
Delete the app from my facebook account as I'm testing using that account
Try to log in with facebook with :scope => 'user_birthday' left in. Facebook lists the permissions sought as your public profile and birthday. Accept and get sent back to my site which fails as per above (even though the info is definitely being sent back)
Remove :scope => 'user_birthday' and try log in using facebook again. Get directed to facebook which lists permission sought as your public profile and email address. Accept and get directed back to site which now works and also has the user birthday stored and accessible because I had the permisision from facebook from number 2 above.
I'm completely at a loss now
To find out about why is the object not being saved. You need to puts the errors.
puts #user.errors.to_a
And to check the content of the auth
puts request.env["omniauth.auth"]
I had the same problem and follow the answer above and I put "#user.errors.to_yaml" on my code to I see where was the error and I found.
I am using "devise" and "omniauth-facebook" too. The default scope of the omniauth-facebook is "email". However, I put on the scope the properties: "user_about_me, user_status, user_location, user_birthday, user_photos". I need to add "EMAIL" on the scope to devise to use on creation of the 'user'. I discover this when I saw my error: "email don't be blank".
Summary:
If you insert properties on the scope, ALWAYS put "email" too.
Facebook not always returning email for user
from facebook developers https://developers.facebook.com/bugs/298946933534016
Some possible reasons:
No Email address on account
No confirmed email address on account
No verified email address on account
User entered a security checkpoint which required them to reconfirm
their email address and they have not yet done so
Users's email address is unreachable
You also need the 'email' extended permission, even for users who have a valid, confirmed, reachable email address on file.
User entered a security checkpoint which required them to reconfirm their email address and they have not yet done so
Users's email address is unreachable
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
puts request.env["omniauth.auth"] # check if request.env["omniauth.auth"] is provided an email
if request.env["omniauth.auth"].info.email.present?
#user = User.from_omniauth(request.env["omniauth.auth"])
if #user.persisted?
sign_in_and_redirect #user, :event => :authentication #this will throw if #user is not activated
set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
else
redirect_to new_user_registration_url, notice: "Can't sign in to your #{request.env["omniauth.auth"].provider} account. Try to sign up."
end
end
end

Rails + OmniAuth Facebook: how to obtain Access Token?

I am trying to fetch the list of friends from Facebook. Sign in through Facebook is not a problem, but the problem is to fetch person's friends - because of access token.
puts request.env["omniauth.auth"].inspect
puts '==='
#user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user)
#fb_user = FbGraph::User.fetch(#user.uid).friends
puts #fb_user.inspect
The problem is on the #4 line - in this case I am getting error
OAuthException :: An access token is required to request this resource.
When I put there something like this:
#fb_user = FbGraph::User.fetch(request.env["omniauth.auth"].credentials.token).friends
I'll get
OAuthException :: (#803) Some of the aliases you requested do not exist: PRINTED OUT TOKEN
What's the proper way to obtain the access token?
EDIT: Current flow
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
#user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user)
#fb_user = FbGraph::User.fetch(request.env["omniauth.auth"].credentials.token).friends
if !#user
flash[:error] = 'This email address is already used in the system.'
redirect_to :back
elsif #user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Facebook"
sign_in_and_redirect #user, :event => :authentication
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
In User model:
def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
data = access_token.extra.raw_info
if user = User.where(:provider => 'facebook', :uid => data.id).first
user
elsif user = User.where('email = ? AND provider IS NULL', data.email).first
return false
else
...saving data...
end
return user if user
end
You can get an access token for test purposes via the Facebook Graph API Explorer. Make sure you select the proper fields that you want access to, and click "get access token". A more permanent solution is to register your app with Facebook so that you will be able to continually make requests without the token dying.
You should look into the Facebook OAuth dialogue.
I'm assuming you're trying to use the OAuth2 strategy instead of the Javascript SDK. Make sure you have set up a callback url like so:
client.redirect_uri = "http://your.client.com/facebook/callback"
In the controller that handles your callback, you should do something like this:
client.authorization_code = params[:code]
access_token = client.access_token! :client_auth_body
FbGraph::User.me(access_token).fetch
Make sure you've let fb_graph know what your app's id and secret are. You should look into this stackoverflow to keep your apps info safe.
I'll also plug the koala gem

Setting Facebook redirect_uri

I'm making a FB Canvas app.
The problem: After users authenticate, they are returned to the non-Canvas version of the app. Here's my code:
provider :facebook, CONFIG['app_id'], CONFIG['secret_key'], :scope => "publish_stream, rsvp_event"
match "/auth/facebook/callback" => "sessions#oauth_create"
match "/auth/facebook", :as => "facebook"
match "/auth/failure" => "sessions#oauth_failure"
When the user is returned from Facebook, they are sent to oauth_create (below)- however, they are sent to it via the normal (non-Canvas) app url (localhost:3000), rather than the canvas app (apps.facebook.com/my-app-namespace) so the redirect_to root_path below just sends them to the regular app.
def oauth_create
auth = request.env["omniauth.auth"]
t = auth["credentials"]["token"]
session[:facebook_token] = t
redirect_to root_path
end
I'm using omniauth-facebook gem.
How can I tell FB to send users to the canvas app after authentication?

Devise Omniauth, how to link google account

I've set up devise to work with omniauth and. This is how devise.rb looks like:
...
config.omniauth :facebook, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET, :scope => FACEBOOK_APP_PERMISSIONS
config.omniauth :openid, OpenID::Store::Filesystem.new('./tmp'), :name => 'yahoo', :identifier => 'yahoo.com'
config.omniauth :openid, OpenID::Store::Filesystem.new('./tmp'), :name => 'gmail', :identifier => 'https://www.google.com/accounts/o8/id'
...
I want to link an existing account with the the above 3, with the following code from the callback controller:
...
def callback(provider)
if utilizator_signed_in?
# link it's account
if Login.link_omniauth(current_utilizator, omniauth_data)
flash[:notice] = I18n.t "devise.omniauth_callbacks.link.success", :kind => provider
redirect_to :root
end
else
utilizator = Login.auth_with_omniauth(omniauth_data)
if !utilizator.nil?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => provider
sign_in_and_redirect utilizator, :event => :authentication
else
utilizator = Login.register_omniauth(omniauth_data)
flash[:notice] = I18n.t "devise.omniauth_callbacks.register.success", :kind => provider
sign_in_and_redirect utilizator, :event => :authentication
end
end
end
...
It works just great with facebook, but for google and yahoo the current user get's signed out and a new user is created.
How can I skip the user sign_out phase ?
Thank you,
Edit:
I am using the latest version 3.0.rc3.
The functions from Login are easy to guess:
link_omniauth - will link the current logged user to a account
auth_with_omniauth - will auth the user
register_omniauth - will register a new user
The problem here is that utilizator_signed_in? (user_signed_in?) will return false for google when the user is signed in, I think there is a prior sign_out happening that is not happening for facebook.
I highly recommend this tutorial: here (far more in-depth than the rails casts and other tutorials on the topic). In particular, it has a comprehensive 200 line piece of code (services_controller.rb) to create the controller that you will need to handle any authentication service (Twitter/Facebook/Google/Github) efficiently using Omniauth, and either link it to pre-existing Devise accounts, or create new accounts.
I have a (almost) live project running with that here -
You can sign in using Facebook/Twitter (I haven't enabled google/github for now), and if you go to Profile->Services after you are signed in, it will show you the multiple authentication services linked to your account.
I'm reluctant to upload my project's source since it has a lot of other code that isn't relevant to this at all, but if you really feel like you need it, then tell me.
So I finally found the answer to my question.
This guy https://github.com/intridea/omniauth/issues/185 had the same issue.
Thanks for your replies,
I hope already submit my gmail address link to my profile task into my application

Integrating Devise with Twitter

I am currently using this guide to try to integrate twitter into Devise.
It is a little challenging because twitter's OAuth does not provide email addresses. Hence the flow of the sign up should be:
User clicks "Sign in with twitter"
Oauth call back to twitter's callback
Ask for the user for email (I need that for my site)
Sign in user.
I realized that if the user already has an account on my system with Twitter, I must be able to find the account. Hence I have added 2 extra field to the user model: oauth_provider, oauth_uid.
In omniauth_callbacks_controller:
def twitter
#user = User.find_for_twitter_oauth(env["omniauth.auth"], current_user)
if #user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Twitter"
sign_in_and_redirect #user, :event => :authentication
else
flash[:warn] = "We still need a little more info!"
redirect_to new_user_registration_url
end
end
In user.rb
# The trick here is that twitter does not give you an email back
# So we should make use of uid and provider
def self.find_for_twitter_oauth(oauth_hash, signed_in_resource=nil)
uid = oauth_hash['uid']
if user = User.find_by_oauth_provider_and_oauth_uid('twitter', uid)
user
else
User.create(:password => Devise.friendly_token[0,20],
:oauth_provider => "twitter",
:oauth_uid => oauth_hash['uid'])
end
end
However, I have debugged this thoroughly and realized that if I redirect a user to new_registration_url, the User created in user.rb will be wiped.
How can I do the following:
If user cannot be found via oauth_provider and oauth_uid, create a User object with these credentials
direct user to new_registration_url
When the user have submitted his/her email, create the user with the same user object created in 1)
I have tried using session, but it gets really messy as I have to monkey patch devise's new and create for registrationscontroller.rb.
Please someone provide me a way to do this.
I have not been successful yet. Let me show you what I have written.
I followed these 2 screencasts and it is exactly what you want.
You can try it out! He is using the omniauth gem, which is very easy and awesome :-)
http://railscasts.com/episodes/235-omniauth-part-1
http://railscasts.com/episodes/236-omniauth-part-2

Resources