Diolor
Diolor

Reputation: 13450

Link facebook to existing account / omniauth

Simple as that, I want to link to an existing user account his facebook profile (giving priority to the email that has originally registered with) in my rails app, using omniauth and devise.

I have read this but wasn't much helpful to me.

My current structure is like this one.

Upvotes: 2

Views: 1835

Answers (1)

littleforest
littleforest

Reputation: 2245

Below is an example of how I implemented this. If the user is already signed in, then I call a method that links their account with Facebook. Otherwise, I go through the same procedure outlined in the Devise-Omniauth wiki page.

# users/omniauth_callbacks_controller.rb

def facebook
  if user_signed_in?
    if current_user.link_account_from_omniauth(request.env["omniauth.auth"])
      flash[:notice] = "Account successfully linked"
      redirect_to user_path(current_user) and return
    end
  end

  @user = User.from_omniauth(request.env["omniauth.auth"])

  if @user.persisted?
    sign_in_and_redirect @user, event: :authentication #this will throw if @user is not activated
    set_flash_message(:notice, :success, kind: "Facebook") if is_navigational_format?
  else
    session["devise.facebook_data"] = request.env["omniauth.auth"]
    redirect_to new_user_registration_url
  end
end

# app/models/user.rb

class << self
  def from_omniauth(auth)
    new_user = where(provider: auth.provider, uid: auth.uid).first_or_initialize
    new_user.email = auth.info.email

    new_user.password = Devise.friendly_token[0,20]
    new_user.skip_confirmation!
    new_user.save
    new_user
  end
end

def link_account_from_omniauth(auth)
  self.provider = auth.provider
  self.uid = auth.uid
  self.save
end

Upvotes: 3

Related Questions