Develop, Omniauth and "new with session"
I have a method in my user model (which uses devise and confirmable) called new_with_session
as required by Omniauth + Devise ( https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview ):
def self.new_with_session(params, session)
super.tap do |user|
if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"] || session["devise.google_data"] && session["devise.google_data"]["extra"]["raw_info"]
user.email = data["email"]
end
end
end
Users are allowed to login using Google or Facebook and I use this line to keep the correct one user.email
:
if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"] || session["devise.google_data"] && session["devise.google_data"]["extra"]["raw_info"]
but I don't think this is the right way, so ...
- Do you know which is better to build
user.email
than to use an operator||
? - If I want to save some data from Google / Facebook like username, should I add it to my username
new_with_session
? If so, why?
source to share
new_with_session is used in build_resource. It is used with registrants (user registration forms).
This is only useful when your Facebook / Omniauth session already exists and you want to pre-populate your registration form with some data from omniauth. (unless you created an account automatically on callback)
# Build a devise resource passing in the session. Useful to move
# temporary session data to the newly created user.
def build_resource(hash=nil)
hash ||= params[resource_name] || {}
self.resource = resource_class.new_with_session(hash, session)
end
source to share
Do you want to authenticate an existing account on your system via Facebook or Gmail using an email address as an identifier and create an account with that email address if it doesn't already exist? If so, I don't think you need to use new_with_session
; you can use the model method as described in the link you provided:
def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
data = access_token.extra.raw_info
if user = User.where(:email => data.email).first
user
else # Create a user with a stub password.
User.create!(:email => data.email, :password => Devise.friendly_token[0,20])
end
end
You can create a similar method self.find_for_google_oauth
and a corresponding google method in Users::OmniauthCallbacksController
.
If you want to use additional data from a Facebook or Google callback, when creating a user, you can simply add it to a string User.create!
in the find_for_oauth methods, for example:
User.create!(:email => data.email,
:first_name => data.first_name,
:last_name => data.last_name,
:password => Devise.friendly_token[0,20])
This worked great for me and I didn't have to do anything with new_with_session
. However, I am still learning about Devise and OmniAuth, so if there is anything wrong with this approach, I would love to hear about it.
source to share