I'm using the omniauth-twitter gem to authenticate users and to fill in names, avatars, etc. with this in my User.rb file
def self.from_omniauth(auth)
where(auth.slice("provider", "uid")).first || create_from_omniauth(auth)
end
def self.create_from_omniauth(auth)
create! do |user|
user.provider = auth["provider"]
user.uid = auth["uid"]
user.name = auth["info"]["name"]
user.nickname = auth["info"]["nickname"]
user.location = auth["info"]["location"]
user.image = auth["info"]["image"].sub("_normal", "")
user.description = auth["info"]["description"]
end
end
end
Works great, except I happened to change my avatar in Twitter and noticed that the data never changes even after I log out and reauthorize. It would be nice if data like location, image, description got refreshed each time a user logged in.
Well, the workings of that logic are up to you. Here's an example of a possible solution:
def self.from_omniauth(auth)
user = find_by(auth.slice(:provider, :uid)) || initialize_from_omniauth(auth) # Rails 4
user = where(auth.slice(:provider, :uid)).first || initialize_from_omniauth(auth) # Rails 3
user.update_dynamic_attributes(auth)
end
def self.initialize_from_omniauth(auth)
new do |user|
user.provider = auth[:provider]
user.uid = auth[:uid]
user.name = auth[:info][:name]
end
end
def update_dynamic_attributes(auth)
self.location = auth[:info][:location]
self.image = auth[:info][:image]
self.description = auth[:info][:description]
save!
self
end
Also, you don't have to do this:
auth["info"]["image"].sub("_normal", "")
As the omniauth-twitter gem can already do that for you if you use the image_size option:
OmniAuth::Builder do
provider :twitter, ENV["TWITTER_KEY"], ENV["TWITTER_SECRET"], {
:image_size => 'original'
}
end
Related
I am developing a Rails web application. But when I run rubocop to check the code. It said that the ABC (Assignment Branch Condition) size of the method below is too high. While I'm a newbie in Ruby on Rails, can someone give me some advice to refactor this block of code? For more details, I am implementing the third party authentication which allows user to sign in by facebook or google, etc.
Thank you
def self.from_omniauth auth, current_user
identity = Identity.find_by(provider: auth.provider, uid: auth.id)
.first_or_initialize
if identity.user.blank?
user = current_user || User.find_by("email = ?",
auth["info"]["email"])
if user.blank?
user = User.new
user.password = Devise.friendly_token[0, 10]
user.name = auth.info.name
user.email = auth.info.email
user.picture = auth.info.image
return user.save(validate: false) if auth.provider == "twitter"
user.save
end
identity.user_id = user.id
identity.save
end
identity.user
end
def self.from_omniauth auth, current_user
identity = Identity.find_by(provider: auth.provider, uid: auth.id)
.first_or_initialize
if identity.user.blank?
user = current_user || User.find_by("email = ?",
auth["info"]["email"])
create_user(auth) if user.blank?
identity.user_id = user.id
identity.save
end
identity.user
end
def self.create_user(auth)
user = User.new
user.password = Devise.friendly_token[0, 10]
user.name = auth.info.name
user.email = auth.info.email
user.picture = auth.info.image
return user.save(validate: false) if auth.provider == "twitter"
user.save
end
Is something you can try. But if the complexity is actually needed you can set a comment to ignore that cop # rubocop:disable ABC (Assignment Branch Condition), or whatever the actual name of the cop is. Also you can configure the ABC size if you feel the size set is too low
I don't get any error like you are saying, so probably you should try # rubocop:disable ABC
when I saved this it added bracket in parameters
def self.from_omniauth(auth, current_user)
identity = Identity.find_by(provider: auth.provider, uid: auth.id)
.first_or_initialize
if identity.user.blank?
user = current_user || User.find_by("email = ?",
auth["info"]["email"])
if user.blank?
user = User.new
user.password = Devise.friendly_token[0, 10]
user.name = auth.info.name
user.email = auth.info.email
user.picture = auth.info.image
return user.save(validate: false) if auth.provider == "twitter"
user.save
end
identity.user_id = user.id
identity.save
end
identity.user
end
I have the following method setup to assist with refreshing Oauth tokens:
module WhiplashOmniAuthentication
extend ActiveSupport::Concern
module ClassMethods
def from_omniauth(auth)
Rails.logger.debug auth.inspect
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.email = auth.info.email
user.store_token(auth.credentials)
end
end
end
def refresh_token!
settings = Devise.omniauth_configs[:whiplash].strategy
strategy = OmniAuth::Strategies::Whiplash.new(nil, settings.client_id, settings.client_secret, client_options: settings.client_options)
client = strategy.client
access_token = OAuth2::AccessToken.new client, token, refresh_token: refresh_token
if access_token
begin
result = access_token.refresh!
store_token(result)
save
rescue OAuth2::Error => e
errors[:token] << e.inspect
return false
end
else
errors[:token] << e.inspect
return false
end
end
def store_token(auth_token)
self.token = auth_token.token
self.refresh_token = auth_token.refresh_token
self.token_expires_at = Time.at(auth_token.expires_at).to_datetime
end
def token_expired?
Time.now > token_expires_at
end
end
I tried breaking this out into separate methods but it keeps blowing up, so I am going to defer to readers here. I am looking for recommendations to pass the cops and learning.
You definitely have too many things going on in the refresh_token! implementation. You always want to keep methods to do one thing and only one thing. It makes it easier for testing (for ex: stub out a particular method), debugging and readability.
See if the following helps:
module WhiplashOmniAuthentication
extend ActiveSupport::Concern
module ClassMethods
def from_omniauth(auth)
Rails.logger.debug auth.inspect
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.email = auth.info.email
user.store_token(auth.credentials)
end
end
end
def refresh_token!
access_token ? refresh_access_token! : false
end
def refresh_access_token!
result = access_token.refresh!
store_token(result)
save
rescue OAuth2::Error
false
end
def settings
#settings ||= Devise.omniauth_configs[:whiplash].strategy
end
def strategy
#strategy ||= OmniAuth::Strategies::Whiplash.new(nil, settings.client_id, settings.client_secret, client_options: settings.client_options)
end
def client
#client ||= strategy.client
end
def access_token
OAuth2::AccessToken.new(client, token, refresh_token: refresh_token)
end
def store_token(auth_token)
self.token = auth_token.token
self.refresh_token = auth_token.refresh_token
self.token_expires_at = Time.at(auth_token.expires_at).to_datetime
end
def token_expired?
Time.now > token_expires_at
end
end
I'm able to get the Facebook avatar through Omniauth, but I'm only able to resize the default image not the Facebook image which is 50 x 50px by default. How can I resize it to 38px?
Here's my application helper:
module ApplicationHelper
def avatar_url(current_user)
if current_user.avatar.present?
current_user.avatar
else
gravatar_id = Digest::MD5.hexdigest(current_user.email.downcase)
"http://gravatar.com/avatar/#{gravatar_id}.png?s=28&d=mm"
end
end
end
and my User class:
class User < ActiveRecord::Base
def self.from_omniauth(auth)
where(auth.slice(:sprovider, :uid)).first_or_create do |user|
user.sprovider = auth.provider
user.uid = auth.uid
user.first_name = auth.info.first_name
user.last_name = auth.info.last_name
user.email = auth.info.email
user.cell_phone = auth.info.cell_phone
user.avatar = auth.info.image
end
end
I have the following code in user.rb using the Facebook-omniauth gem that logs in a single user:
def self.from_omniauth(auth)
where(auth.slice(:provider, :fb_id)).first_or_initialize.tap do |user|
user.provider = auth.provider
user.fb_id = auth.uid
user.name = auth.info.name
user.first_name = auth["info"]["first_name"] unless auth["info"].blank?
user.last_name = auth["info"]["last_name"] unless auth["info"].blank?
user.picture_url = auth.info.image
user.email = auth.info.email
user.oauth_token = auth.credentials.token unless auth["info"].blank?
user.location = auth.info.location unless auth["info"].blank?
user.save!
end
I want to build user accounts for multiple facebook users. When I log its fine but when another person signs in, the app replaces my user instance. Is there a way to keep building user accounts from this gem?
Thanks!
The solution was in the second line at: where(auth.slice(:provider, :fb_id))
I changed it from :uid to :fb_id to match the facebook id of everything else in all my other tables but after inspecting the auth hash I realized that :fb_id was not found at all and thus wasn't producing any new Users.
I renamed my User fb_id column back to uid and it now collects new users properly:
def self.from_omniauth(auth)
where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.first_name = auth["info"]["first_name"] unless auth["info"].blank?
user.last_name = auth["info"]["last_name"] unless auth["info"].blank?
user.picture_url = auth.info.image.sub("square", "large")
user.email = auth.info.email
user.oauth_token = auth.credentials.token unless auth["info"].blank?
user.location = auth.info.location unless auth["info"].blank?
user.save!
end
end
I am using omniauth-facebook gem with devise to authenticate with Facebook in my rails application in my user model
def self.from_omniauth(auth)
# immediately get 60 day auth token
oauth = Koala::Facebook::OAuth.new("App Key", "App secrets" )
new_access_info = oauth.exchange_access_token_info auth.credentials.token
new_access_token = new_access_info["access_token"]
new_access_expires_at = DateTime.now + new_access_info["expires"].to_i.seconds
begin
where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
user.provider = auth.provider
user.uid = auth.uid
user.username = auth.info.first_name
user.lastname =auth.info.last_name
user.email =auth.info.email
user.authentication_token = new_access_token
user.oauth_expires_at = new_access_expires_at
user.save!
end
rescue ActiveRecord::RecordInvalid
end
end
#interact with facebook
def facebook
#facebook ||= Koala::Facebook::API.new(authentication_token)
block_given? ? yield(#facebook) : #facebook
rescue Koala::Facebook::APIError => e
logger.info e.to_s
nil # or consider a custom null object
end
def self.new_with_session(params, session)
if session["devise.user_attributes"]
new(session["devise.user_attributes"], :without_protection=> true) do |user|
user.attributes = params
user.valid?
end
else
super
end
end
and on my omniauth_callbacks controller I have this method:
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
redirect_to new_user_registration_url
end
end
alias_method :facebook, :all
These methods are used to authenticate user from scratch via Facebook. I need a way to connect existing users with their Facebook accounts not new ones if they registered via normal devise registration method
When an existing user is trying to sign in via Facebook the following error occurs:
A `NoMethodError` occurred in `omniauth_callbacks#facebook`:
undefined method `persisted?' for nil:NilClass
app/controllers/omniauth_callbacks_controller.rb:4:in `all'
You can find user by email first and just update provider and uid fields in case he is already exists.
So your User.from_omniauth may looks like that:
def self.from_omniauth(auth)
# immediately get 60 day auth token
oauth = Koala::Facebook::OAuth.new("", "" )
new_access_info = oauth.exchange_access_token_info auth.credentials.token
new_access_token = new_access_info["access_token"]
new_access_expires_at = DateTime.now + new_access_info["expires"].to_i.seconds
user = where(provider: auth.provider, uid: auth.uid).first
unless user
# in that case you will find existing user doesn't connected to facebook
# or create new one by email
user = where(email: auth.info.email).first_or_initialize
user.provider = auth.provider # and connect him to facebook here
user.uid = auth.uid # and here
user.username = auth.info.first_name
user.lastname = auth.info.last_name
user.authentication_token = new_access_token
user.oauth_expires_at = new_access_expires_at
# other user's data you want to update
user.save!
end
user
end
upd:
In case you faced password validation error you can override User#password_required? method to skip validation for user's signed in via Facebook.
That behavior described in following episode of RailsCasts
Just for add an updated version of the answer for rails 4 and devise 3.4.x
Like this is how an updated omniauth would look like
def self.from_omniauth(auth)
if !where(email: auth.info.email).empty?
user = where(email: auth.info.email).first
user.provider = auth.provider # and connect him to facebook here
user.uid = auth.uid # and here
user.save!
user
else
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.first_name = auth.info.name # assuming the user model has a name
user.avatar = process_uri(auth.info.image) # assuming the user model has an image
end
end
end
Just look for user by email, if there is one, just add the provider and uid, if there is not one, just create it as suggested in the documentation
You can have your from_omniauth be something like this:
def self.from_omniauth(auth)
where(auth.info.slice(:email)).first_or_create do |user|
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
user.username = auth.info.name
user.description = auth.extra.raw_info.bio
end
end
In this way, if there's an existing user with email same as the facebook account, then the first_or_create will return it and then the user can sign in (it won't be update).