4
votes

I'm using Devise Invitable on my app, and Omniauth to allow users to sign in with Facebook.

The only thing I'm having trouble with is when a user chooses to sign in with Facebook using the link within the Invitation Accept page, they're redirected to the New User Registration page with some details already filled in. The problem is since Devise Invitable creates a new users when it sends an invitation, users are unable to login using the email that was supplied when the invitation was sent.

Omniauth Callbacks Controller

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
1

1 Answers

0
votes

You have diagnosed the issue, which is that you have something like a User but not really. You must detect whether this is the case, and update the record you have in place with the data you've gathered from Facebook.

if user.persisted?
  flash.notice = "Signed in!"
  sign_in_and_redirect user
elsif user.previously_invited?
  invited_user = User.where(email: user.email).first
  invited_user.attributes = user.attributes
  invited_user.save
  sign_in_and_redirect invited_user
else
  session["devise.user_attributes"] = user.attributes
  redirect_to new_user_registration_url
end

User#previously_invited? is left as an exercise to the reader, but it would contain a where lookup on email with some of the devise-invitable maintained fields included in the query.

This is unlikely to be a complete solution, as devise-invitable maintains many fields that may need adjusting on invited_user after this action. Whether you recognize the invitation as fulfilled or not is up to you. You may find this reason enough to move to a different mechanism for invitations other than devise-invitable.