Omniauth facebook sessions controller create action integration after Michael Hartl tutorial

Viewed 563

I have just finished the Michael Hartl tutorial. I am trying to implement omniauth-facebook to sign-up and sign-in users. I am having trouble creating the master variable to use in the create action in the sessions controller. My assumption is that I should put in an if else statement to see if the master is either signing on through facebook or through the default form? Or should I use and or statement:

(master = Master.find_by(email: params[:session][:email].downcase) || Master.from_omniauth(env["omniauth.auth"])) ?

Here is the omniauth-facebook sessons controller create action code:

def create
    user = User.from_omniauth(env["omniauth.auth"])
    session[:user_id] = user.id
    redirect_to root_url
  end

And here is my current sessions controller create action code:

class SessionsController < ApplicationController

    def new
    end

    def create
        master = Master.find_by(email: params[:session][:email].downcase)
        if master && master.authenticate(params[:session][:password])
            sign_in master
            redirect_back_or master
        else
            flash.now[:error] = 'Invalid email/password combination'
            render 'new'
        end
    end
    .
    .
    .


end
3 Answers

Timur's answer is excellent, but assumes that the OP has already configured some things for OmniAuth. Unfortunately some readers will not have done the config and will get errors. The minimum config for omniauth is to set up facebook credientials, make them available to the app and create a file called config/initializers/omniauth.rb with the following:

    Rails.application.config.middleware.use OmniAuth::Builder do
      provider :developer unless Rails.env.production?
      provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET']
    end

And of course, it would be wise to write some tests for this feature.

Neither this nor Timur's answer deals with the situation where a user has created a local login account, then tries to log in from Facebook. It will fail due to a duplicate email or create a new account if the Facebook email is different. the User.from_omniauth(auth) function should be updated to handle this case. omniauth has a page about how to handle this, but will require significant rework from Miachal's hartl's tutorial: https://github.com/omniauth/omniauth/wiki/Managing-Multiple-Providers

Related