Reputation: 508
I am working on a rails app that allows users to log in via facebook/twitter/linkedin using omniauth. So far, users are able to sign up and create an account using the authentications, but they must pass validations and are therefore forwarded to a signup page where they must enter a valid name, username, and email. I want these fields to be already filled out if possible using the request.env["omniauth.auth"] hash.
Here is my code:
authentications_controller.rb
user = User.new
user.apply_omniauth(omniauth)
if user.save
flash[:notice] = "Signed in successfully."
sign_in_and_redirect(:user, user)
else
session[:omniauth] = omniauth.except('extra')
redirect_to new_user_registration_url
end
registrations_controller.rb:
def build_resource(*args)
super
if session[:omniauth]
@user.apply_omniauth(session[:omniauth])
@user.valid?
end
end
user.rb:
def apply_omniauth(omniauth)
self.name = omniauth['user_info']['name'] if name.blank?
self.email = omniauth['user_info']['email'] if email.blank?
authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'])
end
The line:
self.email = omniauth['user_info']['email'] if email.blank?
results in this NoMethodError:
undefined method `[]' for nil:NilClass
The session[:omniauth] is being passed from the registrations controller to omniauth in the apply_omniauth method. How do I access the name and email in this session?
Thanks
Upvotes: 1
Views: 1373
Reputation: 19203
Quick answer:
omniauth.info.email # which is the same as omniauth['info']['email']
Explanatory answer:
Put this as the first line of your callback controller:
render :text => "<pre>" + env["omniauth.auth"].to_yaml and return
Now try to login and you'll be able to take a good look at the hash of nested hashes returned.
Upvotes: 5