Omniauth not updating OAuth token secret on log in - ruby-on-rails-3

I'm using Omniauth to authenticate users with Twitter and Facebook, going by the "standard" tutorial on the topic (Ryan Bates' screencast, although I'm using Authlogic, not Devise).
I can log in using Twitter, but can't handle authenticated requests back because my Twitter access token secret has been changed on Twitter's end, but is not being updated on my application's end. I've tried deleting the authentication, but it just saves the old one for some reason.
authentications_controller.rb
def create
omniauth = request.env['omniauth.auth']
authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
if authentication
# User is already registered with application
flash[:notice] = 'Signed in successfully.'
sign_in_and_redirect(authentication.user)
elsif current_user
# User is signed in but has not already authenticated with this social network
current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'], :token => (omniauth['credentials']['token'] rescue nil), :secret => (omniauth['credentials']['secret'] rescue nil))
current_user.apply_omniauth(omniauth)
current_user.save
flash[:notice] = 'Authentication successful.'
redirect_to root_url
else
# User is new to this application
#user = User.new
#user.apply_omniauth(omniauth)
if #user.save
flash[:notice] = 'User created and signed in successfully.'
sign_in_and_redirect(#user)
else
session[:omniauth] = omniauth.except('extra')
redirect_to new_user_path
end
end
end
user.rb
def apply_omniauth(omniauth)
self.email = "foo#example.com"
self.login = omniauth['user_info']['nickname'] if login.blank?
authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'], :token => omniauth['credentials']['token'], :secret => omniauth['credentials']['secret'])
end
Any ideas? Rails 3.0.6 and Ruby 1.8.7

Steve, you can try the following:
if authentication
# Make sure we have the latest authentication token for user
if omniauth['credentials']['token'] && omniauth['credentials']['token'] != authentication.token
# puts "Found Invalid token"
authentication.update_attribute(:token, omniauth['credentials']['token'])
end
flash[:notice] = "Signed in successfully"
sign_in_and_redirect(:user, authentication.user)
elsif ...
This should basically update the user's access token every time an already registered user tries to login and when a token mismatch occurs.

Related

How can I automatically assign extra params to my User with omniauth?

I have omniauth and devise successfully set-up for LinkedIn and Twitter.
When authenticating with LinkedIn, I am able to get the users name and email passed into the sign-up form automatically - but then it still gives an error and ask's the user to 'check the errors' which is bad UX given there technically are no errors.
How can I get them automatically assigned to the user during the create process, but only when they are present? Here's the relevant code:
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def all
user = User.from_omniauth(request.env["omniauth.auth"])
if user.persisted?
flash.notice = "Signed in!"
sign_in_and_redirect user
else
session["devise.user_attributes"] = user.attributes
flash.notice = "Please confirm your name and email"
redirect_to sign_up_path
end
end
alias_method :linkedin, :all
alias_method :twitter, :all
end
From the User model:
def self.from_omniauth(auth)
where(auth.slice(:provider, :uid)).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.email = auth.info.email
end
end

How to allow a user to enter a password when deleting an authorization in devise/omniauth

I have a rais 3 app that uses devise and omniauth to allow users to register/login via their twitter account and/or with local login credentials. Everything works fine for registering and logging in. My problem occurs when a user chooses to destroy their twitter authorization without first establishing a local password. If a user destroys their authorizations, then I would like to route them to new_password_path so that they can choose a password for future log-ins.
Here is the controller code:
class AuthenticationsController < ApplicationController
before_filter :authenticate_user!, :except => [:create, :failure]
def create
omniauth = request.env["omniauth.auth"]
authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
if authentication #existing user is logging-in with existing authentication service
flash[:notice] = "Signed in successfully."
set_home_location_cookies(authentication.user, authentication.user.home_lat, authentication.user.home_lng)
sign_in(:user, authentication.user)
redirect_to root_path
elsif current_user #existing user who is already logged-in is creating a new authentication service for future use
current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'], :token => omniauth['credentials']['token'])
current_user.update_posting_preferences(omniauth['provider'])
flash[:notice] = "Successfully linked to your #{omniauth['provider'].titleize} account."
redirect_to root_path
else #new user is creating a new authentication service and logging in
user = User.new
user.apply_omniauth(omniauth)
if user.save
flash[:notice] = "Signed in successfully."
sign_in(:user, user)
redirect_to root_path
else
session[:omniauth] = omniauth.except('extra')
session[:user_message] = {:success => false, :message => "userSaveError"}
redirect_to new_user_registration_url
end
end
end
def failure
flash[:alert] = "Could not authorize you from your social service."
redirect_to root_path
end
def destroy
#authentication = current_user.authentications.find(params[:id])
current_user.update_posting_preferences(#authentication.provider)
#authentication.destroy
flash[:notice] = "You have successfully destroyed your link to your #{#authentication.provider.titleize} account."
if current_user.authentications.empty? && current_user.encrypted_password.empty?
sign_out
flash[:alert] = "Alert: Your account does not currently have a password for account authorization. You are in danger of losing your account unless you create a new password by using this form."
redirect_to new_password_path(current_user) and return
else
redirect_back_or(root_path)
end
end
The code results in a "could not find valid mapping for nil" error triggered by my redirect_to new_password_path(current_user) and return command
I would greatly appreciate some help figuring out this problem.
Thanks!
OK. I'll admit it. I implemented the authentications controller from a tutorial without studying devise routing to learn what was going on behind the scenes. Last night I reviewed the docs and figured out my problem. What is funny is that the above routine did work on an older version of devise but does not work on devise 1.5.3.
In the destroy action I sign-out the current_user then I try to route to the new_password_path sending in "current_user" as a parameter. Not surprisingly, at that point "current_user" has been nulled out. So, I get the, "could not find a valid mapping for nil" error. Here is my easy fix:
def destroy
#authentication = current_user.authentications.find(params[:id])
user = current_user
current_user.update_posting_preferences(#authentication.provider)
#authentication.destroy
flash[:notice] = "You have successfully destroyed your link to your #{#authentication.provider.titleize} account."
if current_user.authentications.empty? && current_user.encrypted_password.empty?
sign_out
flash[:alert] = "Alert: Your account does not currently have a password for account authorization. You are in danger of losing your account unless you create a new password by using this form."
redirect_to new_password_path(user) and return
else
redirect_back_or(root_path)
end
end

devise+omniauth devise helper like current_user,user_signed_in? not working

I am using devise and create login with Facebook using omniauth, but having problem of lost the devise helper methods access like current_user and user_signed_in? methods are not working.
EDIT
AuthenticationController
def create
omniauth = request.env["omniauth.auth"]
user = User.find_by_provider_and_uid(omniauth["provider"], omniauth["uid"]) || User.create_with_omniauth(omniauth)
session[:user_id] = user.id
redirect_to dashboard_path(user.id), :notice => "Signed in!"
end
redirect_to USercontroller dashboard method
UserController
before_filter :logged_in
def dashboard
#user = User.find(params[:id])
#comment = Comment.new
#comments = #user.comments.all.paginate(:page => params[:page], :per_page => 5)
end
so here control should go to dashboard method after checking logged_in method in ApplicationController
logged_in method in ApplicationController
Application Controller
def logged_in
if user_signed_in?
return true
else
redirect_to root_path
flash[:message] = "please login"
end
end
when I logged in using facebook following code generated at console
Started GET "/users/52/dashboard" for 127.0.0.1 at Thu Mar 29 12:51:55 +0530 2012
Processing by UsersController#dashboard as HTML
Parameters: {"id"=>"52"}
Redirected to http://localhost:3000/
Filter chain halted as :logged_in rendered or redirected
Completed 302 Found in 2ms (ActiveRecord: 0.0ms)
in the above code control is render from logged_in method to root_path but it shold render dashboard_path
So I am guessing User_signed_in? helper is not working I also use current_user in stead of that generate same error
As I see, user_signed_in? is working, but returns false, as for Devise user is not logged in. To fix this, just replace the session id storing with Devise sign_in method in your controller action:
def create
omniauth = request.env["omniauth.auth"]
user = User.find_by_provider_and_uid(omniauth["provider"], omniauth["uid"]) || User.create_with_omniauth(omniauth)
sign_in(:user, user)
# actually if you really really need that id in the session, you can leave this line too :)
session[:user_id] = user.id
redirect_to dashboard_path(user.id), :notice => "Signed in!"
end
After creating the user account via Facebook, how do you sign in the user?
You should still be using devise helpers like sign_in_and_redirect. Something like:
user = User.build_from_omniauth(omniauth)
if user.save
sign_in_and_redirect(:user, user)
end
Then you should be able to use helpers like current_user and user_signed_in? (which just check if current_user is not nil).
Taking a look at your edit, my answer is still valid. What you need to do is use sign_in_and_redirect(:user, user) instead of just setting the id in the session.
You can easily customize where the user is redirected after sign in with devise.
Another thing, remove this logged_in filter, Devise has a authenticate_user! method that you can use as a before_filter. It will redirect the user to the sign in page, and when they login, it will redirect them to the page they were trying to access.
You're using Devise, so try to take advantage of that, and go read the doc ;)

Authentication between applications using OAuth

I have two rails application running at different ports. First at 3000 and the second at 4000. Both of them use Devise gem for auth.
First application plays the role of OAuth provider and the second on OAuth consumer.
I've followed this and that tutorials to build my environment.
Almost all works fine. I've successfully generated key and secret for consumer application. And successfully authorize at provider application.
There are two methods at my client application:
def auth
#consumer = OAuth::Consumer.new 'KEY', 'SECRET', :site => "http://localhost:3000"
#request_token = #consumer.get_request_token
session[:request_token] = #request_token
redirect_to #request_token.authorize_url
end
def auth_callback
#request_token ||= session[:request_token]
#access_token = #request_token.get_access_token :oauth_verifier => params[:oauth_verifier]
#request = #access_token.get '/user_info.json'
render :text => #request.body.inspect
end
And API method at provider application:
class UsersController < InheritedResources::Base
before_filter :login_or_oauth_required
load_and_authorize_resource
def info
logger.info current_user.present? # => false
#info = { } # here I've collect user info for current_user
respond_to do |format|
format.json { render :json => #info }
end
end
end
Shit happens when I try getting user info at line: #request = #access_token.get '/user_info.json'
When I call it in consumer application user already unauthorized at provider application.
How I can stay authorized at provider's resource?
upd: I've got current_user.present? # => false in case I pass authorization for info action (before_filter :login_or_oauth_required, :except => [:info]) otherwise I've got redirected to login page.
You don't stay authorized in the provider.
On every request to your API, you'll receive the access token (either in parameters or header), and from this token you'll be able to determine who is the current_user. There is no session among requests.
This gem may help if you need an OAuth provider.
The load_and_authorize_resource will deny access to info action.
just add :except attribute
load_and_authorize_resource :except => [:info]

Rails 3: updating user attributes when authentications are created

I followed Railscasts #235 and #236 to setup creating user authentications with omniauth.
http://railscasts.com/episodes/235-omniauth-part-1
http://railscasts.com/episodes/236-omniauth-part-2
I have a 2 boolean attributes on the user model called :facebok_share and :twitter_share that I want to set to true when a new authentication is created.
I have this working for me when I create a new user, but if an existing user adds an authentication I cannot get the boolean to update to true.
When apply_omniauth(omniauth) is called it sets self.facebook_share = true or self.twitter_share = true in my user model.
I've tried to add a new method called apply_share which changes the booleans depending on provider, and I'm trying to call current_user.apply_share(omniauth) but nothing is happening in the database.
What am I doing wrong? Thanks!
## authentications controller
class AuthenticationsController < ApplicationController
def index
#title = "Authentications"
#authentications = current_user.authentications if current_user
end
def create
# creates omniauth hash and looks for an previously established authentication
omniauth = request.env["omniauth.auth"]
authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
# if previous authentication found, sign in user
if authentication
flash[:notice] = "Signed in successfully"
sign_in_and_redirect(:user, authentication.user)
# for users already signed in (current_user), create a new authentication for the user
elsif current_user
current_user.apply_share(omniauth)
current_user.authentications.create(:provider => omniauth['provider'], :uid => omniauth['uid'], :token => (omniauth['credentials']['token'] rescue nil),
:secret => (omniauth['credentials']['secret'] rescue nil))
flash[:notice] = "authentications successful"
redirect_to authentications_url
# new user is created and authentications are built through apply_omniauth(omniauth)
else
user = User.new
user.apply_omniauth(omniauth)
if user.save
flash[:notice] = "Signed in successfully"
sign_in_and_redirect(:user, user)
# if validations fail to save user, redirects to new user registration page
# new twitter authentications redirect so user can enter their password
else
session[:omniauth] = omniauth
redirect_to new_user_registration_url
end
end
end
def destroy
#authentication = current_user.authentications.find(params[:id])
#authentication.destroy
flash[:notice] = "Successfully destroyed authentication."
redirect_to authentications_url
end
end
## user model
# set share booleans to true depending on 'provider' type
def apply_share(omniauth)
case omniauth['provider']
when 'facebook'
self.facebook_share = true
when 'twitter'
self.twitter_share = true
end
end
# from authentications controller, new user split into type of provider
def apply_omniauth(omniauth)
case omniauth['provider']
when 'facebook'
self.apply_facebook(omniauth)
when 'twitter'
self.apply_twitter(omniauth)
end
# builds authentication with provider, uid, token, and secret
authentications.build(hash_from_omniauth(omniauth))
end
protected
# sets new user attributes from facebook
def apply_facebook(omniauth)
self.name = omniauth['user_info']['name']
self.email = omniauth['user_info']['email'] if email.blank?
self.facebook_share = true
end
# sets new user attributes from twitter
def apply_twitter(omniauth)
if (extra = omniauth['extra']['user_hash'] rescue false)
# Example fetching extra data. Needs migration to User model:
# self.firstname = (extra['name'] rescue '')
self.name = (extra['name'] rescue '')
self.bio = (extra['description'] rescue '')
end
self.twitter_share = true
end
# set authentication attributes to those from 'omniauth' hash
def hash_from_omniauth(omniauth)
{
:provider => omniauth['provider'],
:uid => omniauth['uid'],
:token => (omniauth['credentials']['token'] rescue nil),
:secret => (omniauth['credentials']['secret'] rescue nil)
}
end
end
## new methid with :before add => :apply_share
def apply_share(authentication)
case authentication['provider']
when 'facebook'
self.facebook_share = true
when 'twitter'
self.twitter_share = true
end
self.save
end
I believe your never actually saving current_user. So your setting your attributes to true, and then redirecting. The association is stored in the authentication model, so Rails, trying to be helpful, doesn't update current_user, just the new instance of authentication
try:
current_user.apply_share(omniauth)
current_user.save
and see if that fixes it. Now if it does, I would strongly recommend using a callback instead. Take a look here:
http://guides.rubyonrails.org/association_basics.html
Section 4.5 about association callbacks. You can do a before_add callback on your has_many authentications assocation to remove that code from your controller as its getting pretty bloated as is.
class User < ActiveRecord::Base
has_many :authentications, :before_add => :apply_share
def apply_share(authentication)
#update attributes
#save model
end
end
You need to call #save on the User object after setting the *_share attributes.
Adding new items to a has_many collection automatically saves the collection item, but does not trigger a save operation on the parent (belongs_to).